blob: aa534b9ef3fafd694e0428e2e5c510c40eebef38 [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 +000099FormatStyle getLLVMStyle() {
100 FormatStyle LLVMStyle;
101 LLVMStyle.ColumnLimit = 80;
102 LLVMStyle.MaxEmptyLinesToKeep = 1;
103 LLVMStyle.PointerAndReferenceBindToType = false;
104 LLVMStyle.AccessModifierOffset = -2;
105 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000106 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000107 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000108 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000109 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000110 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000111 return LLVMStyle;
112}
113
114FormatStyle getGoogleStyle() {
115 FormatStyle GoogleStyle;
116 GoogleStyle.ColumnLimit = 80;
117 GoogleStyle.MaxEmptyLinesToKeep = 1;
118 GoogleStyle.PointerAndReferenceBindToType = true;
119 GoogleStyle.AccessModifierOffset = -1;
120 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000121 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000122 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000123 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
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 Jasper2408a8c2013-01-11 11:37:55 +0000170/// \brief Checks whether the (remaining) \c UnwrappedLine starting with
171/// \p RootToken fits into \p Limit columns.
172bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit) {
173 unsigned Columns = RootToken.FormatTok.TokenLength;
174 bool FitsOnALine = true;
175 const AnnotatedToken *Tok = &RootToken;
176 while (!Tok->Children.empty()) {
177 Tok = &Tok->Children[0];
178 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
179 // A special case for the colon of a constructor initializer as this only
180 // needs to be put on a new line if the line needs to be split.
181 if (Columns > Limit ||
182 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
183 FitsOnALine = false;
184 break;
185 }
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000186 }
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000187 return FitsOnALine;
188}
189
Daniel Jasperf7935112012-12-03 18:12:45 +0000190class UnwrappedLineFormatter {
191public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000192 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
193 const UnwrappedLine &Line, unsigned FirstIndent,
194 bool FitsOnALine, LineType CurrentLineType,
195 const AnnotatedToken &RootToken,
196 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000197 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000198 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000199 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000200 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000201 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000202 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000203 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 }
205
Manuel Klimek1abf7892013-01-04 23:34:14 +0000206 /// \brief Formats an \c UnwrappedLine.
207 ///
208 /// \returns The column after the last token in the last line of the
209 /// \c UnwrappedLine.
210 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000211 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000212 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000213 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000214 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000215 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000216 State.ForLoopVariablePos = 0;
217 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000218 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000219
220 // The first token has already been indented and thus consumed.
221 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000222
223 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000224 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000225 if (FitsOnALine) {
226 addTokenToState(false, false, State);
227 } else {
228 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
229 unsigned Break = calcPenalty(State, true, NoBreak);
230 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000231 if (State.NextToken != NULL &&
232 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
233 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
234 !fitsIntoLimit(*State.NextToken,
235 getColumnLimit() - State.Column - 1))
236 State.Stack.back().BreakAfterComma = true;
237 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000238 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000239 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000240 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000241 }
242
243private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000244 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000245 ParenState(unsigned Indent, unsigned LastSpace)
246 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
247 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000248
Daniel Jasperf7935112012-12-03 18:12:45 +0000249 /// \brief The position to which a specific parenthesis level needs to be
250 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000251 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000252
Daniel Jaspere9de2602012-12-06 09:56:08 +0000253 /// \brief The position of the last space on each level.
254 ///
255 /// Used e.g. to break like:
256 /// functionCall(Parameter, otherCall(
257 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000258 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000259
Daniel Jaspere9de2602012-12-06 09:56:08 +0000260 /// \brief The position the first "<<" operator encountered on each level.
261 ///
262 /// Used to align "<<" operators. 0 if no such operator has been encountered
263 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000264 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000265
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000266 /// \brief Whether a newline needs to be inserted before the block's closing
267 /// brace.
268 ///
269 /// We only want to insert a newline before the closing brace if there also
270 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000271 bool BreakBeforeClosingBrace;
272
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000273 bool BreakAfterComma;
274
Daniel Jasper337816e2013-01-11 10:22:12 +0000275 bool operator<(const ParenState &Other) const {
276 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000277 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000278 if (LastSpace != Other.LastSpace)
279 return LastSpace < Other.LastSpace;
280 if (FirstLessLess != Other.FirstLessLess)
281 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000282 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
283 return BreakBeforeClosingBrace;
284 return BreakAfterComma;
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 }
286 };
287
288 /// \brief The current state when indenting a unwrapped line.
289 ///
290 /// As the indenting tries different combinations this is copied by value.
291 struct LineState {
292 /// \brief The number of used columns in the current line.
293 unsigned Column;
294
295 /// \brief The token that needs to be next formatted.
296 const AnnotatedToken *NextToken;
297
298 /// \brief The parenthesis level of the first token on the current line.
299 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000300
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000301 /// \brief The column of the first variable in a for-loop declaration.
302 ///
303 /// Used to align the second variable if necessary.
304 unsigned ForLoopVariablePos;
305
306 /// \brief \c true if this line contains a continued for-loop section.
307 bool LineContainsContinuedForLoopSection;
308
Daniel Jasper337816e2013-01-11 10:22:12 +0000309 /// \brief A stack keeping track of properties applying to parenthesis
310 /// levels.
311 std::vector<ParenState> Stack;
312
313 /// \brief Comparison operator to be able to used \c LineState in \c map.
314 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000315 if (Other.NextToken != NextToken)
316 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 if (Other.Column != Column)
318 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000319 if (Other.StartOfLineLevel != StartOfLineLevel)
320 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000321 if (Other.ForLoopVariablePos != ForLoopVariablePos)
322 return Other.ForLoopVariablePos < ForLoopVariablePos;
323 if (Other.LineContainsContinuedForLoopSection !=
324 LineContainsContinuedForLoopSection)
325 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000326 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 }
328 };
329
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000330 /// \brief Appends the next token to \p State and updates information
331 /// necessary for indentation.
332 ///
333 /// Puts the token on the current line if \p Newline is \c true and adds a
334 /// line break and necessary indentation otherwise.
335 ///
336 /// If \p DryRun is \c false, also creates and stores the required
337 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000338 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000339 const AnnotatedToken &Current = *State.NextToken;
340 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 assert(State.Stack.size());
342 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000343
344 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000345 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000346 if (Current.is(tok::r_brace)) {
347 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000348 } else if (Current.is(tok::string_literal) &&
349 Previous.is(tok::string_literal)) {
350 State.Column = State.Column - Previous.FormatTok.TokenLength;
351 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000352 State.Stack[ParenLevel].FirstLessLess != 0) {
353 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000354 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000355 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
356 Current.is(tok::period) || Previous.is(tok::question) ||
357 Previous.Type == TT_ConditionalExpr)) {
358 // Indent and extra 4 spaces after if we know the current expression is
359 // continued. Don't do that on the top level, as we already indent 4
360 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000361 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000362 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000363 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000364 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000365 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000367 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000368 }
369
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000370 // A line starting with a closing brace is assumed to be correct for the
371 // same level as before the opening brace.
372 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000373
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000374 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000375 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000376
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000377 if (!DryRun) {
378 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000379 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
380 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000381 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000382 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000383 WhitespaceStartColumn, Style, SourceMgr,
384 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000385 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000386
Daniel Jasper337816e2013-01-11 10:22:12 +0000387 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000388 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000389 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000392 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
393 State.ForLoopVariablePos = State.Column -
394 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000395
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000396 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
397 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000398 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000399
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000401 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000402
Daniel Jasperbcab4302013-01-09 10:40:23 +0000403 // FIXME: Do we need to do this for assignments nested in other
404 // expressions?
405 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000406 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000407 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000408 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000409 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000410 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000411 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000412
Daniel Jasper206df732013-01-07 13:08:40 +0000413 // Top-level spaces that are not part of assignments are exempt as that
414 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000415 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000416 if (Spaces > 0 &&
417 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000418 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000419 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000420 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000421 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000422 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000423 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000424 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000426 /// \brief Mark the next token as consumed in \p State and modify its stacks
427 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000428 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000429 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000430 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000431
Daniel Jasper337816e2013-01-11 10:22:12 +0000432 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
433 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000434
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000435 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000436 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000437 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
438 Current.is(tok::l_brace) ||
439 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000440 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000441 if (Current.is(tok::l_brace)) {
442 // FIXME: This does not work with nested static initializers.
443 // Implement a better handling for static initializers and similar
444 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000446 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000448 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000450 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000451 }
452
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000453 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000454 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000455 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
456 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
457 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000460
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000461 if (State.NextToken->Children.empty())
462 State.NextToken = NULL;
463 else
464 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000465
466 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000467 }
468
Nico Weber49cbc2c2013-01-07 15:15:29 +0000469 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000470 unsigned splitPenalty(const AnnotatedToken &Tok) {
471 const AnnotatedToken &Left = Tok;
472 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000473
474 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000475 if (RootToken.is(tok::kw_for) &&
476 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000477 return 20;
478
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000479 if (Left.is(tok::semi) || Left.is(tok::comma) ||
480 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000481 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000482 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000483 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000484
Daniel Jasper399d24b2013-01-09 07:06:56 +0000485 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
486 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000487 prec::Level Level = getPrecedence(Left);
488
489 // Breaking after an assignment leads to a bad result as the two sides of
490 // the assignment are visually very close together.
491 if (Level == prec::Assignment)
492 return 50;
493
Daniel Jasperde5c2072012-12-24 00:13:23 +0000494 if (Level != prec::Unknown)
495 return Level;
496
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000497 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000498 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000499
Daniel Jasperf7935112012-12-03 18:12:45 +0000500 return 3;
501 }
502
Daniel Jasper2df93312013-01-09 10:16:05 +0000503 unsigned getColumnLimit() {
504 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
505 }
506
Daniel Jasperf7935112012-12-03 18:12:45 +0000507 /// \brief Calculate the number of lines needed to format the remaining part
508 /// of the unwrapped line.
509 ///
510 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000511 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000512 /// added after the previous token.
513 ///
514 /// \param StopAt is used for optimization. If we can determine that we'll
515 /// definitely need at least \p StopAt additional lines, we already know of a
516 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000517 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000518 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000519 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000520 return 0;
521
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000522 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000524 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000526 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000527 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000528 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000529 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000530 State.LineContainsContinuedForLoopSection)
531 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000532 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
533 State.NextToken->Type != TT_LineComment &&
534 State.Stack.back().BreakAfterComma)
535 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000536
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000537 unsigned CurrentPenalty = 0;
538 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000540 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000541 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000543 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000545 }
546
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000547 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000548
Daniel Jasper2df93312013-01-09 10:16:05 +0000549 // Exceeding column limit is bad, assign penalty.
550 if (State.Column > getColumnLimit()) {
551 unsigned ExcessCharacters = State.Column - getColumnLimit();
552 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
553 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000554
Daniel Jasperf7935112012-12-03 18:12:45 +0000555 if (StopAt <= CurrentPenalty)
556 return UINT_MAX;
557 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000559 if (I != Memory.end()) {
560 // If this state has already been examined, we can safely return the
561 // previous result if we
562 // - have not hit the optimatization (and thus returned UINT_MAX) OR
563 // - are now computing for a smaller or equal StopAt.
564 unsigned SavedResult = I->second.first;
565 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000566 if (SavedResult != UINT_MAX)
567 return SavedResult + CurrentPenalty;
568 else if (StopAt <= SavedStopAt)
569 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000570 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000571
572 unsigned NoBreak = calcPenalty(State, false, StopAt);
573 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
574 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000575
576 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
577 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000578 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000579
580 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000581 }
582
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 FormatStyle Style;
584 SourceManager &SourceMgr;
585 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000586 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000587 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000588 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000589 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000592 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000593 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000594 StateMap Memory;
595
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 OptimizationParameters Parameters;
597};
598
599/// \brief Determines extra information about the tokens comprising an
600/// \c UnwrappedLine.
601class TokenAnnotator {
602public:
603 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000604 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000605 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000606 RootToken(Line.RootToken) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000607
608 /// \brief A parser that gathers additional information about tokens.
609 ///
610 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
611 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
612 /// into template parameter lists.
613 class AnnotatingParser {
614 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000615 AnnotatingParser(AnnotatedToken &RootToken)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000616 : CurrentToken(&RootToken), KeywordVirtualFound(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000617
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000618 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 while (CurrentToken != NULL) {
620 if (CurrentToken->is(tok::greater)) {
621 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000622 next();
623 return true;
624 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000625 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
626 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000627 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
629 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000631 if (!consumeToken())
632 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000633 }
634 return false;
635 }
636
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000637 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000638 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
639 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000640 while (CurrentToken != NULL) {
641 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000642 next();
643 return true;
644 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000645 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000647 if (!consumeToken())
648 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000649 }
650 return false;
651 }
652
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000653 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000654 while (CurrentToken != NULL) {
655 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000656 next();
657 return true;
658 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000659 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000661 if (!consumeToken())
662 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000663 }
664 return false;
665 }
666
Daniel Jasper83a54d22013-01-10 09:26:47 +0000667 bool parseBrace() {
668 while (CurrentToken != NULL) {
669 if (CurrentToken->is(tok::r_brace)) {
670 next();
671 return true;
672 }
673 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
674 return false;
675 if (!consumeToken())
676 return false;
677 }
678 // Lines can currently end with '{'.
679 return true;
680 }
681
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000682 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000683 while (CurrentToken != NULL) {
684 if (CurrentToken->is(tok::colon)) {
685 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000686 next();
687 return true;
688 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000689 if (!consumeToken())
690 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000691 }
692 return false;
693 }
694
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000695 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
697 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000698 next();
699 if (!parseAngle())
700 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000701 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000702 parseLine();
703 return true;
704 }
705 return false;
706 }
707
Daniel Jasperc0880a92013-01-04 18:52:56 +0000708 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000709 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000711 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000712 case tok::plus:
713 case tok::minus:
714 // At the start of the line, +/- specific ObjectiveC method
715 // declarations.
716 if (Tok->Parent == NULL)
717 Tok->Type = TT_ObjCMethodSpecifier;
718 break;
719 case tok::l_paren: {
720 bool ParensWereObjCReturnType =
721 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000722 if (!parseParens())
723 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000724 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
725 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000726 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000727 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
728 CurrentToken->Type = TT_ObjCSelectorStart;
729 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000730 }
Nico Weber9efe2912013-01-10 23:11:41 +0000731 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000732 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000733 if (!parseSquare())
734 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000736 case tok::l_brace:
737 if (!parseBrace())
738 return false;
739 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000741 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000742 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000744 Tok->Type = TT_BinaryOperator;
745 CurrentToken = Tok;
746 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000747 }
748 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000749 case tok::r_paren:
750 case tok::r_square:
751 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000752 case tok::r_brace:
753 // Lines can start with '}'.
754 if (Tok->Parent != NULL)
755 return false;
756 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000757 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 break;
760 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000761 if (CurrentToken->is(tok::l_paren)) {
762 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000763 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
765 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000766 next();
767 }
768 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000769 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
770 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000771 next();
772 }
773 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 break;
775 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000776 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000777 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000778 case tok::kw_template:
779 parseTemplateDeclaration();
780 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 default:
782 break;
783 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000784 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 }
786
Daniel Jasper050948a52012-12-21 17:58:39 +0000787 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000788 while (CurrentToken != NULL) {
789 if (CurrentToken->is(tok::slash))
790 CurrentToken->Type = TT_DirectorySeparator;
791 else if (CurrentToken->is(tok::less))
792 CurrentToken->Type = TT_TemplateOpener;
793 else if (CurrentToken->is(tok::greater))
794 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000795 next();
796 }
797 }
798
799 void parsePreprocessorDirective() {
800 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000801 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000802 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000803 // Hashes in the middle of a line can lead to any strange token
804 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000805 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000806 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000807 switch (
808 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000809 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000810 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000811 parseIncludeDirective();
812 break;
813 default:
814 break;
815 }
816 }
817
Daniel Jasperda16db32013-01-07 10:48:50 +0000818 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000819 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000820 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000821 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000822 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000823 while (CurrentToken != NULL) {
824 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000825 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000826 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000827 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000828 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000829 if (KeywordVirtualFound)
830 return LT_VirtualFunctionDecl;
831 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000832 }
833
834 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000835 if (CurrentToken != NULL && !CurrentToken->Children.empty())
836 CurrentToken = &CurrentToken->Children[0];
837 else
838 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 }
840
841 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000842 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000843 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000844 };
845
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000846 void createAnnotatedTokens(AnnotatedToken &Current) {
847 if (!Current.FormatTok.Children.empty()) {
848 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
849 Current.Children.back().Parent = &Current;
850 createAnnotatedTokens(Current.Children.back());
851 }
852 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000853
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000854 void calculateExtraInformation(AnnotatedToken &Current) {
855 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
856
Manuel Klimek52b15152013-01-09 15:25:02 +0000857 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000858 Current.MustBreakBefore = true;
859 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000860 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
861 TT_LineComment || (Current.is(tok::string_literal) &&
862 Current.Parent->is(tok::string_literal))) {
863 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000864 } else {
865 Current.MustBreakBefore = false;
866 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000867 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000869 if (!Current.Children.empty())
870 calculateExtraInformation(Current.Children[0]);
871 }
872
873 bool annotate() {
874 createAnnotatedTokens(RootToken);
875
876 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000877 CurrentLineType = Parser.parseLine();
878 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000879 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000880
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000881 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000882
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000883 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000884 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000885 else if (RootToken.Type == TT_ObjCDecl)
886 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000887 else if (RootToken.Type == TT_ObjCProperty)
888 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000889
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000890 if (!RootToken.Children.empty())
891 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000892 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000893 }
894
Daniel Jasperda16db32013-01-07 10:48:50 +0000895 LineType getLineType() {
896 return CurrentLineType;
897 }
898
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000899 const AnnotatedToken &getRootToken() {
900 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000901 }
902
903private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000904 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
905 if (getPrecedence(Current) == prec::Assignment ||
906 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
907 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000908
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000909 if (Current.Type == TT_Unknown) {
910 if (Current.is(tok::star) || Current.is(tok::amp)) {
911 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000912 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
913 Current.is(tok::caret)) {
914 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
916 Current.Type = determineIncrementUsage(Current);
917 } else if (Current.is(tok::exclaim)) {
918 Current.Type = TT_UnaryOperator;
919 } else if (isBinaryOperator(Current)) {
920 Current.Type = TT_BinaryOperator;
921 } else if (Current.is(tok::comment)) {
922 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
923 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000924 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000925 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000926 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000927 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000928 } else if (Current.is(tok::r_paren) &&
929 (Current.Parent->Type == TT_PointerOrReference ||
930 Current.Parent->Type == TT_TemplateCloser)) {
931 // FIXME: We need to get smarter and understand more cases of casts.
932 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000933 } else if (Current.is(tok::at) && Current.Children.size()) {
934 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
935 case tok::objc_interface:
936 case tok::objc_implementation:
937 case tok::objc_protocol:
938 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000939 break;
940 case tok::objc_property:
941 Current.Type = TT_ObjCProperty;
942 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000943 default:
944 break;
945 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000946 }
947 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948
949 if (!Current.Children.empty())
950 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000951 }
952
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000953 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000954 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000955 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 }
957
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000958 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
959 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000960 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000962 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000963 const FormatToken &PrevToken = Tok.Parent->FormatTok;
964 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000965
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000966 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
967 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000968 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
969 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000970 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000971
Nico Weber5dafd4a2013-01-12 05:47:16 +0000972 if (PrevToken.Tok.isLiteral() || PrevToken.Tok.is(tok::r_paren) ||
973 PrevToken.Tok.is(tok::r_square) || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000974 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
975 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
976 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
Nico Webereee7b812013-01-12 05:50:48 +0000977 NextToken.Tok.is(tok::l_paren) || NextToken.Tok.is(tok::l_square) ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000978 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000979 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000980
Daniel Jasper542de162013-01-02 15:46:59 +0000981 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
982 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000983 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000984
Daniel Jasper426702d2012-12-05 07:51:39 +0000985 // It is very unlikely that we are going to find a pointer or reference type
986 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000987 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000988 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000989
Daniel Jasperda16db32013-01-07 10:48:50 +0000990 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000991 }
992
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000993 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000994 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000995 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
996 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
997 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +0000998 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
Nico Weber63a54eb2013-01-12 05:41:23 +0000999 Tok.Parent->is(tok::at) || Tok.Parent->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001000 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001001
1002 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001003 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001004 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001005
1006 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001007 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001008 }
1009
1010 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001011 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1012 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001013 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001014
Daniel Jasperda16db32013-01-07 10:48:50 +00001015 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 }
1017
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001018 bool spaceRequiredBetween(const AnnotatedToken &Left,
1019 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001020 if (Right.is(tok::hashhash))
1021 return Left.is(tok::hash);
1022 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1023 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001024 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1025 return false;
Nico Webera6087752013-01-10 20:12:55 +00001026 if (Right.is(tok::less) &&
1027 (Left.is(tok::kw_template) ||
1028 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 return true;
1030 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1031 return false;
1032 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1033 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001034 if (Left.is(tok::at) &&
1035 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1036 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001037 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1038 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001039 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1041 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001042 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001043 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001044 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1045 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001046 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001047 return Right.FormatTok.Tok.isLiteral() ||
1048 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 if (Right.is(tok::star) && Left.is(tok::l_paren))
1050 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001051 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1052 Right.is(tok::r_square))
1053 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001054 if (Left.is(tok::coloncolon) ||
1055 (Right.is(tok::coloncolon) &&
1056 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001057 return false;
1058 if (Left.is(tok::period) || Right.is(tok::period))
1059 return false;
1060 if (Left.is(tok::colon) || Right.is(tok::colon))
1061 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 if (Left.is(tok::l_paren))
1063 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001064 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001065 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1066 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001067 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001068 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1069 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001070 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001071 if (Left.is(tok::at) &&
1072 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001073 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001074 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1075 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 return true;
1077 }
1078
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001079 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001080 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001081 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1082 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001083 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001084 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001085 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001086 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001087 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1088 if (Tok.Type == TT_ObjCSelectorStart)
1089 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001090 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001091 // Don't space between ')' and <id>
1092 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001093 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001094 // Don't space between ':' and '('
1095 return false;
1096 }
Nico Webera2a84952013-01-10 21:30:42 +00001097 if (CurrentLineType == LT_ObjCProperty &&
1098 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1099 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001100
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001101 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001102 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001103 if (Tok.Type == TT_OverloadedOperator)
1104 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001105 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001107 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001108 if (Tok.is(tok::colon))
1109 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001110 if (Tok.Parent->Type == TT_UnaryOperator ||
1111 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001112 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001113 if (Tok.Type == TT_UnaryOperator)
1114 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001115 Tok.Parent->isNot(tok::l_square) &&
1116 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1118 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001119 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1120 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 if (Tok.Type == TT_DirectorySeparator ||
1122 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001123 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001125 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001127 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001128 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001129 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001130 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001131 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001133 }
1134
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 bool canBreakBefore(const AnnotatedToken &Right) {
1136 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001137 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001138 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1139 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001140 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1142 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001143 // Don't break this identifier as ':' or identifier
1144 // before it will break.
1145 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001146 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1147 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001148 // Don't break at ':' if identifier before it can beak.
1149 return false;
1150 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001152 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001153 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001154 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001155 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001156 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001157 return false;
1158
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001159 if (Right.is(tok::comment))
1160 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001161 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001162 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001163 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001164 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1165 Left.is(tok::comma) || Right.is(tok::lessless) ||
1166 Right.is(tok::arrow) || Right.is(tok::period) ||
1167 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001168 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001169 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001170 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1171 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001172 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001173 }
1174
Daniel Jasperf7935112012-12-03 18:12:45 +00001175 FormatStyle Style;
1176 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001177 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001178 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001179 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001180};
1181
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001182class LexerBasedFormatTokenSource : public FormatTokenSource {
1183public:
1184 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001185 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001186 IdentTable(Lex.getLangOpts()) {
1187 Lex.SetKeepWhitespaceMode(true);
1188 }
1189
1190 virtual FormatToken getNextToken() {
1191 if (GreaterStashed) {
1192 FormatTok.NewlinesBefore = 0;
1193 FormatTok.WhiteSpaceStart =
1194 FormatTok.Tok.getLocation().getLocWithOffset(1);
1195 FormatTok.WhiteSpaceLength = 0;
1196 GreaterStashed = false;
1197 return FormatTok;
1198 }
1199
1200 FormatTok = FormatToken();
1201 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001202 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001203 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001204 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1205 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001206
1207 // Consume and record whitespace until we find a significant token.
1208 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001209 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001210 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1211 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001212 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1213
1214 if (FormatTok.Tok.is(tok::eof))
1215 return FormatTok;
1216 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001217 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001218 }
Manuel Klimekef920692013-01-07 07:56:50 +00001219
1220 // Now FormatTok is the next non-whitespace token.
1221 FormatTok.TokenLength = Text.size();
1222
Manuel Klimek1abf7892013-01-04 23:34:14 +00001223 // In case the token starts with escaped newlines, we want to
1224 // take them into account as whitespace - this pattern is quite frequent
1225 // in macro definitions.
1226 // FIXME: What do we want to do with other escaped spaces, and escaped
1227 // spaces or newlines in the middle of tokens?
1228 // FIXME: Add a more explicit test.
1229 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001230 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001231 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001232 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001233 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001234 }
1235
1236 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001237 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001238 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001239 FormatTok.Tok.setKind(Info.getTokenID());
1240 }
1241
1242 if (FormatTok.Tok.is(tok::greatergreater)) {
1243 FormatTok.Tok.setKind(tok::greater);
1244 GreaterStashed = true;
1245 }
1246
1247 return FormatTok;
1248 }
1249
1250private:
1251 FormatToken FormatTok;
1252 bool GreaterStashed;
1253 Lexer &Lex;
1254 SourceManager &SourceMgr;
1255 IdentifierTable IdentTable;
1256
1257 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001258 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001259 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1260 Tok.getLength());
1261 }
1262};
1263
Daniel Jasperf7935112012-12-03 18:12:45 +00001264class Formatter : public UnwrappedLineConsumer {
1265public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001266 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1267 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001268 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001269 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001270 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001271
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001272 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001273
Daniel Jasperf7935112012-12-03 18:12:45 +00001274 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001275 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001276 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001277 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001278 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001279 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1280 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001281 I != E; ++I) {
1282 const UnwrappedLine &TheLine = *I;
1283 if (touchesRanges(TheLine)) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001284 llvm::OwningPtr<TokenAnnotator> AnnotatedLine(
1285 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1286 if (!AnnotatedLine->annotate())
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001287 break;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001288 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001289 TheLine.Level, TheLine.InPPDirective,
1290 PreviousEndOfLineColumn);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001291
1292 UnwrappedLine Line(TheLine);
1293 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1294 I, E);
1295 UnwrappedLineFormatter Formatter(
1296 Style, SourceMgr, Line, Indent, FitsOnALine,
1297 AnnotatedLine->getLineType(), AnnotatedLine->getRootToken(),
1298 Replaces, StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001299 PreviousEndOfLineColumn = Formatter.format();
1300 } else {
1301 // If we did not reformat this unwrapped line, the column at the end of
1302 // the last token is unchanged - thus, we can calculate the end of the
1303 // last token, and return the result.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001304 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001305 PreviousEndOfLineColumn =
1306 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1307 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1308 Lex.getLangOpts()) -
1309 1;
1310 }
1311 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001312 return Replaces;
1313 }
1314
1315private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001316 /// \brief Tries to merge lines into one.
1317 ///
1318 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1319 /// if possible; note that \c I will be incremented when lines are merged.
1320 ///
1321 /// Returns whether the resulting \c Line can fit in a single line.
1322 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
1323 llvm::OwningPtr<TokenAnnotator> &AnnotatedLine,
1324 std::vector<UnwrappedLine>::iterator &I,
1325 std::vector<UnwrappedLine>::iterator E) {
1326 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1327
1328 // Check whether the UnwrappedLine can be put onto a single line. If
1329 // so, this is bound to be the optimal solution (by definition) and we
1330 // don't need to analyze the entire solution space.
1331 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1332 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1333 return FitsOnALine;
1334
1335 // Try to merge the next two lines if possible.
1336 UnwrappedLine Combined(Line);
1337
1338 // First, check that the current line allows merging. This is the case if
1339 // we're not in a control flow statement and the last token is an opening
1340 // brace.
1341 FormatToken *Last = &Combined.RootToken;
1342 bool AllowedTokens =
Manuel Klimek2acb7b72013-01-11 19:17:44 +00001343 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1344 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1345 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1346 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001347 // This gets rid of all ObjC @ keywords and methods.
1348 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus) &&
1349 Last->Tok.isNot(tok::plus);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001350 while (!Last->Children.empty())
1351 Last = &Last->Children.back();
1352 if (!Last->Tok.is(tok::l_brace))
1353 return FitsOnALine;
1354
1355 // Second, check that the next line does not contain any braces - if it
1356 // does, readability declines when putting it into a single line.
1357 const FormatToken *Next = &(I + 1)->RootToken;
1358 while (Next) {
1359 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1360 !Next->Tok.is(tok::r_brace);
1361 Last->Children.push_back(*Next);
1362 Last = &Last->Children[0];
1363 Last->Children.clear();
1364 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1365 }
1366
1367 // Last, check that the third line contains a single closing brace.
1368 Next = &(I + 2)->RootToken;
1369 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1370 if (!Next->Children.empty() || !AllowedTokens)
1371 return FitsOnALine;
1372 Last->Children.push_back(*Next);
1373
1374 llvm::OwningPtr<TokenAnnotator> CombinedAnnotator(
1375 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1376 if (CombinedAnnotator->annotate() &&
1377 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1378 // If the merged line fits, we use that instead and skip the next two
1379 // lines.
1380 AnnotatedLine.reset(CombinedAnnotator.take());
1381 Line = Combined;
1382 I += 2;
1383 }
1384 return FitsOnALine;
1385 }
1386
1387 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001388 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001389 while (!Last->Children.empty())
1390 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001391 return Last;
1392 }
1393
1394 bool touchesRanges(const UnwrappedLine &TheLine) {
1395 const FormatToken *First = &TheLine.RootToken;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001396 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001397 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001398 First->Tok.getLocation(),
1399 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001400 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001401 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1402 Ranges[i].getBegin()) &&
1403 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1404 LineRange.getBegin()))
1405 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001406 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001407 return false;
1408 }
1409
1410 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1411 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001412 }
1413
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001414 /// \brief Add a new line and the required indent before the first Token
1415 /// of the \c UnwrappedLine if there was no structural parsing error.
1416 /// Returns the indent level of the \c UnwrappedLine.
1417 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1418 bool InPPDirective,
1419 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001420 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001421 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1422 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1423
1424 unsigned Newlines = std::min(Tok.NewlinesBefore,
1425 Style.MaxEmptyLinesToKeep + 1);
1426 if (Newlines == 0 && !Tok.IsFirst)
1427 Newlines = 1;
1428 unsigned Indent = Level * 2;
1429
1430 bool IsAccessModifier = false;
1431 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1432 RootToken.is(tok::kw_private))
1433 IsAccessModifier = true;
1434 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1435 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1436 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1437 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1438 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1439 IsAccessModifier = true;
1440
1441 if (IsAccessModifier &&
1442 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1443 Indent += Style.AccessModifierOffset;
1444 if (!InPPDirective || Tok.HasUnescapedNewline) {
1445 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1446 } else {
1447 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1448 SourceMgr, Replaces);
1449 }
1450 return Indent;
1451 }
1452
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001453 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001454 FormatStyle Style;
1455 Lexer &Lex;
1456 SourceManager &SourceMgr;
1457 tooling::Replacements Replaces;
1458 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001459 std::vector<UnwrappedLine> UnwrappedLines;
1460 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001461};
1462
1463tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1464 SourceManager &SourceMgr,
1465 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001466 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1467 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1468 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1469 DiagnosticsEngine Diagnostics(
1470 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1471 &DiagnosticPrinter, false);
1472 Diagnostics.setSourceManager(&SourceMgr);
1473 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001474 return formatter.format();
1475}
1476
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001477LangOptions getFormattingLangOpts() {
1478 LangOptions LangOpts;
1479 LangOpts.CPlusPlus = 1;
1480 LangOpts.CPlusPlus11 = 1;
1481 LangOpts.Bool = 1;
1482 LangOpts.ObjC1 = 1;
1483 LangOpts.ObjC2 = 1;
1484 return LangOpts;
1485}
1486
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001487} // namespace format
1488} // namespace clang