blob: cee587bf32364baacdc34a91a5b6421534bf9bbc [file] [log] [blame]
Daniel Jasperbac016b2012-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 Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperbac016b2012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasper71607512013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasper71607512013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Webercd52bda2013-01-10 23:11:41 +000042 TT_ObjCSelectorStart,
Nico Weber70848232013-01-10 21:30:42 +000043 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000044 TT_OverloadedOperator,
45 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000046 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000047 TT_TemplateCloser,
48 TT_TemplateOpener,
49 TT_TrailingUnaryOperator,
50 TT_UnaryOperator,
51 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000052};
53
54enum LineType {
55 LT_Invalid,
56 LT_Other,
57 LT_PreprocessorDirective,
58 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000059 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000060 LT_ObjCMethodDecl,
61 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000062};
63
Daniel Jasper26f7e782013-01-08 14:56:18 +000064class AnnotatedToken {
65public:
66 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000067 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
68 CanBreakBefore(false), MustBreakBefore(false),
69 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper26f7e782013-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 Jasperbac016b2012-12-03 18:12:45 +000083 TokenType Type;
84
Daniel Jasperbac016b2012-12-03 18:12:45 +000085 bool SpaceRequiredBefore;
86 bool CanBreakBefore;
87 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000088
89 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000090
91 std::vector<AnnotatedToken> Children;
92 AnnotatedToken *Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +000093};
94
Daniel Jasper26f7e782013-01-08 14:56:18 +000095static prec::Level getPrecedence(const AnnotatedToken &Tok) {
96 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +000097}
98
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +0000106 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000107 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000108 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000109 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Webercd52bda2013-01-10 23:11:41 +0000110 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +0000121 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000122 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000123 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Nico Weber5f500df2013-01-10 20:12:55 +0000124 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Webercd52bda2013-01-10 23:11:41 +0000125 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000126 return GoogleStyle;
127}
128
129struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000130 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000131 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000132 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000133};
134
Manuel Klimek3f8c7f32013-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 Jasper7e9bf8c2013-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 Jasper7d19bc22013-01-11 14:23:32 +0000186 }
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000187 return FitsOnALine;
188}
189
Daniel Jasperbac016b2012-12-03 18:12:45 +0000190class UnwrappedLineFormatter {
191public:
Manuel Klimek94fc6f12013-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 Jasper1321eb52012-12-18 21:05:13 +0000197 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000198 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper26f7e782013-01-08 14:56:18 +0000199 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000200 Replaces(Replaces) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000201 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000202 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000203 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000204 }
205
Manuel Klimekd4397b92013-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 Jasper3b5943f2012-12-06 09:56:08 +0000211 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000212 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000213 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000214 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000215 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000216 State.ForLoopVariablePos = 0;
217 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000218 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000219
220 // The first token has already been indented and thus consumed.
221 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000222
223 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000224 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-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 Jasper7e9bf8c2013-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 Jasper1321eb52012-12-18 21:05:13 +0000238 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000239 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000240 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000241 }
242
243private:
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000244 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000245 ParenState(unsigned Indent, unsigned LastSpace)
246 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
247 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000248
Daniel Jasperbac016b2012-12-03 18:12:45 +0000249 /// \brief The position to which a specific parenthesis level needs to be
250 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000251 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000252
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000258 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000259
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000264 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000265
Manuel Klimekc8c8a472013-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 Jasper604eb4c2013-01-11 10:22:12 +0000271 bool BreakBeforeClosingBrace;
272
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000273 bool BreakAfterComma;
274
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000275 bool operator<(const ParenState &Other) const {
276 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000277 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-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 Jasper7e9bf8c2013-01-11 11:37:55 +0000282 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
283 return BreakBeforeClosingBrace;
284 return BreakAfterComma;
Daniel Jasper604eb4c2013-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 Klimekc8c8a472013-01-10 15:58:26 +0000300
Daniel Jaspera324a0e2012-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 Jasper604eb4c2013-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 Jasper26f7e782013-01-08 14:56:18 +0000315 if (Other.NextToken != NextToken)
316 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000317 if (Other.Column != Column)
318 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000319 if (Other.StartOfLineLevel != StartOfLineLevel)
320 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000326 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000327 }
328 };
329
Daniel Jasper20409152012-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 Jasper604eb4c2013-01-11 10:22:12 +0000338 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000339 const AnnotatedToken &Current = *State.NextToken;
340 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000341 assert(State.Stack.size());
342 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000343
344 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000345 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000346 if (Current.is(tok::r_brace)) {
347 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-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 Jasper604eb4c2013-01-11 10:22:12 +0000352 State.Stack[ParenLevel].FirstLessLess != 0) {
353 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000354 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-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 Jasper604eb4c2013-01-11 10:22:12 +0000361 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000362 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000363 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000364 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000365 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000366 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000367 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000368 }
369
Manuel Klimek2851c162013-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 Jaspera4974cf2012-12-24 16:43:00 +0000373
Daniel Jasper26f7e782013-01-08 14:56:18 +0000374 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000375 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000376
Manuel Klimek060143e2013-01-02 18:33:23 +0000377 if (!DryRun) {
378 if (!Line.InPPDirective)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000379 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
380 SourceMgr, Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000381 else
Daniel Jasper9c837d02013-01-09 07:06:56 +0000382 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000383 WhitespaceStartColumn, Style, SourceMgr,
384 Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000385 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000387 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000388 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper26f7e782013-01-08 14:56:18 +0000389 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000391 } else {
Daniel Jasper9c837d02013-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 Jaspera324a0e2012-12-21 14:37:20 +0000395
Daniel Jasper26f7e782013-01-08 14:56:18 +0000396 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
397 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000398 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000399
Daniel Jasperbac016b2012-12-03 18:12:45 +0000400 if (!DryRun)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000401 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000402
Daniel Jasper3fc0bb72013-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 Jasper9cda8002013-01-07 13:08:40 +0000406 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000407 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000408 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000409 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000410 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000411 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000412
Daniel Jasper9cda8002013-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 Jasper3b5943f2012-12-06 09:56:08 +0000415 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000416 if (Spaces > 0 &&
417 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000418 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000419 }
Daniel Jasper20409152012-12-04 14:54:30 +0000420 moveStateToNextToken(State);
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000421 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000422 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000423 }
Daniel Jasper20409152012-12-04 14:54:30 +0000424 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425
Daniel Jasper20409152012-12-04 14:54:30 +0000426 /// \brief Mark the next token as consumed in \p State and modify its stacks
427 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000428 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000429 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000430 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000431
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000432 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
433 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000434
Daniel Jaspercf225b62012-12-24 13:43:52 +0000435 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000436 // prepare for the following tokens.
Daniel Jasper26f7e782013-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 Jasper604eb4c2013-01-11 10:22:12 +0000440 unsigned NewIndent;
Manuel Klimek2851c162013-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 Jasper604eb4c2013-01-11 10:22:12 +0000445 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000446 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000447 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000448 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000449 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000450 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000451 }
452
Daniel Jaspercf225b62012-12-24 13:43:52 +0000453 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000454 // stacks.
Daniel Jasper26f7e782013-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 Jasper604eb4c2013-01-11 10:22:12 +0000458 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000459 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000460
Daniel Jasper26f7e782013-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 Klimek2851c162013-01-10 14:36:46 +0000465
466 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000467 }
468
Nico Weberdecf7bc2013-01-07 15:15:29 +0000469 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000470 unsigned splitPenalty(const AnnotatedToken &Tok) {
471 const AnnotatedToken &Left = Tok;
472 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000473
474 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000475 if (RootToken.is(tok::kw_for) &&
476 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000477 return 20;
478
Daniel Jasper26f7e782013-01-08 14:56:18 +0000479 if (Left.is(tok::semi) || Left.is(tok::comma) ||
480 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000481 return 0;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000482 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000483 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000484
Daniel Jasper9c837d02013-01-09 07:06:56 +0000485 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
486 return prec::Assignment;
Daniel Jasper9cda8002013-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 Jaspere2c7acf2012-12-24 00:13:23 +0000494 if (Level != prec::Unknown)
495 return Level;
496
Daniel Jasper26f7e782013-01-08 14:56:18 +0000497 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000498 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000499
Daniel Jasperbac016b2012-12-03 18:12:45 +0000500 return 3;
501 }
502
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000503 unsigned getColumnLimit() {
504 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
505 }
506
Daniel Jasperbac016b2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000511 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000517 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000518 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000519 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000520 return 0;
521
Daniel Jasper26f7e782013-01-08 14:56:18 +0000522 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000524 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000525 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000526 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000527 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000528 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000529 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000530 State.LineContainsContinuedForLoopSection)
531 return UINT_MAX;
Daniel Jasper7e9bf8c2013-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 Jasperbac016b2012-12-03 18:12:45 +0000536
Daniel Jasper33182dd2012-12-05 14:57:28 +0000537 unsigned CurrentPenalty = 0;
538 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000539 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000540 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000541 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000542 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000543 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000544 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000545 }
546
Daniel Jasper20409152012-12-04 14:54:30 +0000547 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000548
Daniel Jasperceb99ab2013-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 Jasperbac016b2012-12-03 18:12:45 +0000554
Daniel Jasperbac016b2012-12-03 18:12:45 +0000555 if (StopAt <= CurrentPenalty)
556 return UINT_MAX;
557 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000558 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-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 Jasper9a0b4942012-12-17 14:34:14 +0000566 if (SavedResult != UINT_MAX)
567 return SavedResult + CurrentPenalty;
568 else if (StopAt <= SavedStopAt)
569 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000570 }
Daniel Jasperbac016b2012-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 Jasper9a0b4942012-12-17 14:34:14 +0000575
576 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
577 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000578 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000579
580 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000581 }
582
Daniel Jasperbac016b2012-12-03 18:12:45 +0000583 FormatStyle Style;
584 SourceManager &SourceMgr;
585 const UnwrappedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000586 const unsigned FirstIndent;
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000587 const bool FitsOnALine;
Daniel Jasper71607512013-01-07 10:48:50 +0000588 const LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000589 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000590 tooling::Replacements &Replaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591
Daniel Jasper33182dd2012-12-05 14:57:28 +0000592 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000593 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000594 StateMap Memory;
595
Daniel Jasperbac016b2012-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 Klimek6cf58142013-01-07 08:54:53 +0000604 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper26f7e782013-01-08 14:56:18 +0000605 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000606 RootToken(Line.RootToken) {}
Daniel Jasperbac016b2012-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 Jasper26f7e782013-01-08 14:56:18 +0000615 AnnotatingParser(AnnotatedToken &RootToken)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000616 : CurrentToken(&RootToken), KeywordVirtualFound(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000617
Daniel Jasper20409152012-12-04 14:54:30 +0000618 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000619 while (CurrentToken != NULL) {
620 if (CurrentToken->is(tok::greater)) {
621 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000622 next();
623 return true;
624 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000625 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
626 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 return false;
Daniel Jasper26f7e782013-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 Jasperbac016b2012-12-03 18:12:45 +0000630 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000631 if (!consumeToken())
632 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000633 }
634 return false;
635 }
636
Daniel Jasper20409152012-12-04 14:54:30 +0000637 bool parseParens() {
Daniel Jasper46ef8522013-01-10 13:08:12 +0000638 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
639 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000640 while (CurrentToken != NULL) {
641 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000642 next();
643 return true;
644 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000645 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000646 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000647 if (!consumeToken())
648 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000649 }
650 return false;
651 }
652
Daniel Jasper20409152012-12-04 14:54:30 +0000653 bool parseSquare() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000654 while (CurrentToken != NULL) {
655 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000656 next();
657 return true;
658 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000659 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000660 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000661 if (!consumeToken())
662 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000663 }
664 return false;
665 }
666
Daniel Jasper700e7102013-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 Jasper20409152012-12-04 14:54:30 +0000682 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000683 while (CurrentToken != NULL) {
684 if (CurrentToken->is(tok::colon)) {
685 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000686 next();
687 return true;
688 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000689 if (!consumeToken())
690 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000691 }
692 return false;
693 }
694
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000695 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000696 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
697 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000698 next();
699 if (!parseAngle())
700 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000701 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000702 parseLine();
703 return true;
704 }
705 return false;
706 }
707
Daniel Jasper1f42f112013-01-04 18:52:56 +0000708 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000709 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000710 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000711 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-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 Jasper1f42f112013-01-04 18:52:56 +0000722 if (!parseParens())
723 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000724 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
725 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000726 next();
Nico Webercd52bda2013-01-10 23:11:41 +0000727 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
728 CurrentToken->Type = TT_ObjCSelectorStart;
729 next();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000730 }
Nico Webercd52bda2013-01-10 23:11:41 +0000731 } break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000733 if (!parseSquare())
734 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000735 break;
Daniel Jasper700e7102013-01-10 09:26:47 +0000736 case tok::l_brace:
737 if (!parseBrace())
738 return false;
739 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000740 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000741 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000742 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000743 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000744 Tok->Type = TT_BinaryOperator;
745 CurrentToken = Tok;
746 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000747 }
748 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000749 case tok::r_paren:
750 case tok::r_square:
751 return false;
Daniel Jasper700e7102013-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 Jasperbac016b2012-12-03 18:12:45 +0000757 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000758 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000759 break;
760 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000761 if (CurrentToken->is(tok::l_paren)) {
762 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000763 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000764 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
765 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000766 next();
767 }
768 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000769 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
770 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000771 next();
772 }
773 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000774 break;
775 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000776 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000777 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000778 case tok::kw_template:
779 parseTemplateDeclaration();
780 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000781 default:
782 break;
783 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000784 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000785 }
786
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000787 void parseIncludeDirective() {
Daniel Jasper26f7e782013-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 Jaspercd1a32b2012-12-21 17:58:39 +0000795 next();
796 }
797 }
798
799 void parsePreprocessorDirective() {
800 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000801 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000802 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000803 // Hashes in the middle of a line can lead to any strange token
804 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000805 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000806 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000807 switch (
808 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000809 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000810 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000811 parseIncludeDirective();
812 break;
813 default:
814 break;
815 }
816 }
817
Daniel Jasper71607512013-01-07 10:48:50 +0000818 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000819 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000820 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000821 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000822 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000823 while (CurrentToken != NULL) {
824 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000825 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000826 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000827 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000828 }
Daniel Jasper71607512013-01-07 10:48:50 +0000829 if (KeywordVirtualFound)
830 return LT_VirtualFunctionDecl;
831 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000832 }
833
834 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000835 if (CurrentToken != NULL && !CurrentToken->Children.empty())
836 CurrentToken = &CurrentToken->Children[0];
837 else
838 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000839 }
840
841 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000842 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000843 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000844 };
845
Daniel Jasper26f7e782013-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 Jasper71607512013-01-07 10:48:50 +0000853
Daniel Jasper26f7e782013-01-08 14:56:18 +0000854 void calculateExtraInformation(AnnotatedToken &Current) {
855 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
856
Manuel Klimek526ed112013-01-09 15:25:02 +0000857 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000858 Current.MustBreakBefore = true;
859 } else {
Manuel Klimek526ed112013-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 Klimek526ed112013-01-09 15:25:02 +0000864 } else {
865 Current.MustBreakBefore = false;
866 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000867 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000868 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper26f7e782013-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 Jasper71607512013-01-07 10:48:50 +0000877 CurrentLineType = Parser.parseLine();
878 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000879 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000880
Daniel Jasper26f7e782013-01-08 14:56:18 +0000881 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000882
Daniel Jasper26f7e782013-01-08 14:56:18 +0000883 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasper71607512013-01-07 10:48:50 +0000884 CurrentLineType = LT_ObjCMethodDecl;
Nico Webered91bba2013-01-10 19:19:14 +0000885 else if (RootToken.Type == TT_ObjCDecl)
886 CurrentLineType = LT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +0000887 else if (RootToken.Type == TT_ObjCProperty)
888 CurrentLineType = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +0000889
Daniel Jasper26f7e782013-01-08 14:56:18 +0000890 if (!RootToken.Children.empty())
891 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000892 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000893 }
894
Daniel Jasper71607512013-01-07 10:48:50 +0000895 LineType getLineType() {
896 return CurrentLineType;
897 }
898
Daniel Jasper26f7e782013-01-08 14:56:18 +0000899 const AnnotatedToken &getRootToken() {
900 return RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000901 }
902
903private:
Daniel Jasper26f7e782013-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 Jasperbac016b2012-12-03 18:12:45 +0000908
Daniel Jasper26f7e782013-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 Jasper886568d2013-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 Jasper26f7e782013-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 Klimek6cf58142013-01-07 08:54:53 +0000924 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000925 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000926 else
Daniel Jasper26f7e782013-01-08 14:56:18 +0000927 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-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 Webered91bba2013-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 Weber70848232013-01-10 21:30:42 +0000939 break;
940 case tok::objc_property:
941 Current.Type = TT_ObjCProperty;
942 break;
Nico Webered91bba2013-01-10 19:19:14 +0000943 default:
944 break;
945 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000946 }
947 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000948
949 if (!Current.Children.empty())
950 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000951 }
952
Daniel Jasper26f7e782013-01-08 14:56:18 +0000953 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000954 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000955 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 }
957
Daniel Jasper26f7e782013-01-08 14:56:18 +0000958 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
959 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000960 return TT_UnaryOperator;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000961 if (Tok.Children.size() == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000962 return TT_Unknown;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000963 const FormatToken &PrevToken = Tok.Parent->FormatTok;
964 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000965
Daniel Jasper9bb0d282013-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 Jasper5cf7cf32013-01-10 11:14:08 +0000968 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
969 Tok.Parent->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +0000970 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000971
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000972 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000973 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
974 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
975 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
976 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000977 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000979 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
980 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000981 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000982
Daniel Jasper112fb272012-12-05 07:51:39 +0000983 // It is very unlikely that we are going to find a pointer or reference type
984 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000985 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000986 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000987
Daniel Jasper71607512013-01-07 10:48:50 +0000988 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000989 }
990
Daniel Jasper886568d2013-01-09 08:36:49 +0000991 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000992 // Use heuristics to recognize unary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000993 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
994 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
995 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Weber81ed2f12013-01-10 19:36:35 +0000996 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
997 Tok.Parent->is(tok::at))
Daniel Jasper71607512013-01-07 10:48:50 +0000998 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000999
1000 // There can't be to consecutive binary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001001 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001002 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001003
1004 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001005 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001006 }
1007
1008 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001009 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1010 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001011 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001012
Daniel Jasper71607512013-01-07 10:48:50 +00001013 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001014 }
1015
Daniel Jasper26f7e782013-01-08 14:56:18 +00001016 bool spaceRequiredBetween(const AnnotatedToken &Left,
1017 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001018 if (Right.is(tok::hashhash))
1019 return Left.is(tok::hash);
1020 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1021 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001022 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1023 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001024 if (Right.is(tok::less) &&
1025 (Left.is(tok::kw_template) ||
1026 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001027 return true;
1028 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1029 return false;
1030 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1031 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001032 if (Left.is(tok::at) &&
1033 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1034 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001035 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1036 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001037 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001038 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1039 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001040 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001041 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001042 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1043 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001044 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001045 return Right.FormatTok.Tok.isLiteral() ||
1046 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001047 if (Right.is(tok::star) && Left.is(tok::l_paren))
1048 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001049 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1050 Right.is(tok::r_square))
1051 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001052 if (Left.is(tok::coloncolon) ||
1053 (Right.is(tok::coloncolon) &&
1054 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001055 return false;
1056 if (Left.is(tok::period) || Right.is(tok::period))
1057 return false;
1058 if (Left.is(tok::colon) || Right.is(tok::colon))
1059 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001060 if (Left.is(tok::l_paren))
1061 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001062 if (Right.is(tok::l_paren)) {
Nico Webered91bba2013-01-10 19:19:14 +00001063 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1064 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001065 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001066 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1067 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001068 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001069 if (Left.is(tok::at) &&
1070 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001071 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001072 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1073 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001074 return true;
1075 }
1076
Daniel Jasper26f7e782013-01-08 14:56:18 +00001077 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperda927712013-01-07 15:36:15 +00001078 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001079 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1080 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001081 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001082 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001083 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001084 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Webercd52bda2013-01-10 23:11:41 +00001085 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1086 if (Tok.Type == TT_ObjCSelectorStart)
1087 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001088 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001089 // Don't space between ')' and <id>
1090 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001091 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001092 // Don't space between ':' and '('
1093 return false;
1094 }
Nico Weber70848232013-01-10 21:30:42 +00001095 if (CurrentLineType == LT_ObjCProperty &&
1096 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1097 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001098
Daniel Jasper46ef8522013-01-10 13:08:12 +00001099 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001100 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001101 if (Tok.Type == TT_OverloadedOperator)
1102 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001103 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001104 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001105 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001106 if (Tok.is(tok::colon))
1107 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001108 if (Tok.Parent->Type == TT_UnaryOperator ||
1109 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001110 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001111 if (Tok.Type == TT_UnaryOperator)
1112 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber81ed2f12013-01-10 19:36:35 +00001113 Tok.Parent->isNot(tok::l_square) &&
1114 Tok.Parent->isNot(tok::at);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001115 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1116 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001117 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1118 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001119 if (Tok.Type == TT_DirectorySeparator ||
1120 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperda927712013-01-07 15:36:15 +00001121 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001122 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001123 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001124 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001125 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001126 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001127 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001128 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001129 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001130 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001131 }
1132
Daniel Jasper26f7e782013-01-08 14:56:18 +00001133 bool canBreakBefore(const AnnotatedToken &Right) {
1134 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperda927712013-01-07 15:36:15 +00001135 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001136 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1137 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001138 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001139 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1140 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001141 // Don't break this identifier as ':' or identifier
1142 // before it will break.
1143 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001144 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1145 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001146 // Don't break at ':' if identifier before it can beak.
1147 return false;
1148 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001149 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001150 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001151 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001152 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001153 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001154 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001155 return false;
1156
Daniel Jasper043835a2013-01-09 09:33:39 +00001157 if (Right.is(tok::comment))
1158 return !Right.Children.empty();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001159 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasper043835a2013-01-09 09:33:39 +00001160 Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001161 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001162 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1163 Left.is(tok::comma) || Right.is(tok::lessless) ||
1164 Right.is(tok::arrow) || Right.is(tok::period) ||
1165 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper9c837d02013-01-09 07:06:56 +00001166 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimekc8c8a472013-01-10 15:58:26 +00001167 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001168 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1169 Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001170 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001171 }
1172
Daniel Jasperbac016b2012-12-03 18:12:45 +00001173 FormatStyle Style;
1174 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001175 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001176 LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001177 AnnotatedToken RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001178};
1179
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001180class LexerBasedFormatTokenSource : public FormatTokenSource {
1181public:
1182 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001183 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001184 IdentTable(Lex.getLangOpts()) {
1185 Lex.SetKeepWhitespaceMode(true);
1186 }
1187
1188 virtual FormatToken getNextToken() {
1189 if (GreaterStashed) {
1190 FormatTok.NewlinesBefore = 0;
1191 FormatTok.WhiteSpaceStart =
1192 FormatTok.Tok.getLocation().getLocWithOffset(1);
1193 FormatTok.WhiteSpaceLength = 0;
1194 GreaterStashed = false;
1195 return FormatTok;
1196 }
1197
1198 FormatTok = FormatToken();
1199 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001200 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001201 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001202 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1203 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001204
1205 // Consume and record whitespace until we find a significant token.
1206 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001207 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001208 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1209 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001210 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1211
1212 if (FormatTok.Tok.is(tok::eof))
1213 return FormatTok;
1214 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001215 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001216 }
Manuel Klimek95419382013-01-07 07:56:50 +00001217
1218 // Now FormatTok is the next non-whitespace token.
1219 FormatTok.TokenLength = Text.size();
1220
Manuel Klimekd4397b92013-01-04 23:34:14 +00001221 // In case the token starts with escaped newlines, we want to
1222 // take them into account as whitespace - this pattern is quite frequent
1223 // in macro definitions.
1224 // FIXME: What do we want to do with other escaped spaces, and escaped
1225 // spaces or newlines in the middle of tokens?
1226 // FIXME: Add a more explicit test.
1227 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001228 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001229 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001230 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001231 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001232 }
1233
1234 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001235 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001236 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001237 FormatTok.Tok.setKind(Info.getTokenID());
1238 }
1239
1240 if (FormatTok.Tok.is(tok::greatergreater)) {
1241 FormatTok.Tok.setKind(tok::greater);
1242 GreaterStashed = true;
1243 }
1244
1245 return FormatTok;
1246 }
1247
1248private:
1249 FormatToken FormatTok;
1250 bool GreaterStashed;
1251 Lexer &Lex;
1252 SourceManager &SourceMgr;
1253 IdentifierTable IdentTable;
1254
1255 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001256 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001257 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1258 Tok.getLength());
1259 }
1260};
1261
Daniel Jasperbac016b2012-12-03 18:12:45 +00001262class Formatter : public UnwrappedLineConsumer {
1263public:
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001264 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1265 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001266 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001267 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001268 Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001269
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001270 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001271
Daniel Jasperbac016b2012-12-03 18:12:45 +00001272 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001273 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001274 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001275 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001276 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001277 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1278 E = UnwrappedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001279 I != E; ++I) {
1280 const UnwrappedLine &TheLine = *I;
1281 if (touchesRanges(TheLine)) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001282 llvm::OwningPtr<TokenAnnotator> AnnotatedLine(
1283 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1284 if (!AnnotatedLine->annotate())
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001285 break;
Manuel Klimek517e8942013-01-11 17:54:10 +00001286 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001287 TheLine.Level, TheLine.InPPDirective,
1288 PreviousEndOfLineColumn);
Manuel Klimek517e8942013-01-11 17:54:10 +00001289
1290 UnwrappedLine Line(TheLine);
1291 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1292 I, E);
1293 UnwrappedLineFormatter Formatter(
1294 Style, SourceMgr, Line, Indent, FitsOnALine,
1295 AnnotatedLine->getLineType(), AnnotatedLine->getRootToken(),
1296 Replaces, StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001297 PreviousEndOfLineColumn = Formatter.format();
1298 } else {
1299 // If we did not reformat this unwrapped line, the column at the end of
1300 // the last token is unchanged - thus, we can calculate the end of the
1301 // last token, and return the result.
Manuel Klimek517e8942013-01-11 17:54:10 +00001302 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001303 PreviousEndOfLineColumn =
1304 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1305 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1306 Lex.getLangOpts()) -
1307 1;
1308 }
1309 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001310 return Replaces;
1311 }
1312
1313private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001314 /// \brief Tries to merge lines into one.
1315 ///
1316 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1317 /// if possible; note that \c I will be incremented when lines are merged.
1318 ///
1319 /// Returns whether the resulting \c Line can fit in a single line.
1320 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
1321 llvm::OwningPtr<TokenAnnotator> &AnnotatedLine,
1322 std::vector<UnwrappedLine>::iterator &I,
1323 std::vector<UnwrappedLine>::iterator E) {
1324 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1325
1326 // Check whether the UnwrappedLine can be put onto a single line. If
1327 // so, this is bound to be the optimal solution (by definition) and we
1328 // don't need to analyze the entire solution space.
1329 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1330 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1331 return FitsOnALine;
1332
1333 // Try to merge the next two lines if possible.
1334 UnwrappedLine Combined(Line);
1335
1336 // First, check that the current line allows merging. This is the case if
1337 // we're not in a control flow statement and the last token is an opening
1338 // brace.
1339 FormatToken *Last = &Combined.RootToken;
1340 bool AllowedTokens =
Manuel Klimekd5688cf2013-01-11 19:17:44 +00001341 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1342 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1343 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1344 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
1345 // This gets rid of all ObjC @ keywords and - based definitions.
1346 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus);
Manuel Klimek517e8942013-01-11 17:54:10 +00001347 while (!Last->Children.empty())
1348 Last = &Last->Children.back();
1349 if (!Last->Tok.is(tok::l_brace))
1350 return FitsOnALine;
1351
1352 // Second, check that the next line does not contain any braces - if it
1353 // does, readability declines when putting it into a single line.
1354 const FormatToken *Next = &(I + 1)->RootToken;
1355 while (Next) {
1356 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1357 !Next->Tok.is(tok::r_brace);
1358 Last->Children.push_back(*Next);
1359 Last = &Last->Children[0];
1360 Last->Children.clear();
1361 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1362 }
1363
1364 // Last, check that the third line contains a single closing brace.
1365 Next = &(I + 2)->RootToken;
1366 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1367 if (!Next->Children.empty() || !AllowedTokens)
1368 return FitsOnALine;
1369 Last->Children.push_back(*Next);
1370
1371 llvm::OwningPtr<TokenAnnotator> CombinedAnnotator(
1372 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1373 if (CombinedAnnotator->annotate() &&
1374 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1375 // If the merged line fits, we use that instead and skip the next two
1376 // lines.
1377 AnnotatedLine.reset(CombinedAnnotator.take());
1378 Line = Combined;
1379 I += 2;
1380 }
1381 return FitsOnALine;
1382 }
1383
1384 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001385 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001386 while (!Last->Children.empty())
1387 Last = &Last->Children.back();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001388 return Last;
1389 }
1390
1391 bool touchesRanges(const UnwrappedLine &TheLine) {
1392 const FormatToken *First = &TheLine.RootToken;
Manuel Klimek517e8942013-01-11 17:54:10 +00001393 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jaspercd162382013-01-07 13:26:07 +00001394 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001395 First->Tok.getLocation(),
1396 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001397 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001398 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1399 Ranges[i].getBegin()) &&
1400 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1401 LineRange.getBegin()))
1402 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001403 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001404 return false;
1405 }
1406
1407 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1408 UnwrappedLines.push_back(TheLine);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001409 }
1410
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001411 /// \brief Add a new line and the required indent before the first Token
1412 /// of the \c UnwrappedLine if there was no structural parsing error.
1413 /// Returns the indent level of the \c UnwrappedLine.
1414 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1415 bool InPPDirective,
1416 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001417 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001418 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1419 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1420
1421 unsigned Newlines = std::min(Tok.NewlinesBefore,
1422 Style.MaxEmptyLinesToKeep + 1);
1423 if (Newlines == 0 && !Tok.IsFirst)
1424 Newlines = 1;
1425 unsigned Indent = Level * 2;
1426
1427 bool IsAccessModifier = false;
1428 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1429 RootToken.is(tok::kw_private))
1430 IsAccessModifier = true;
1431 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1432 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1433 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1434 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1435 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1436 IsAccessModifier = true;
1437
1438 if (IsAccessModifier &&
1439 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1440 Indent += Style.AccessModifierOffset;
1441 if (!InPPDirective || Tok.HasUnescapedNewline) {
1442 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1443 } else {
1444 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1445 SourceMgr, Replaces);
1446 }
1447 return Indent;
1448 }
1449
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001450 clang::DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001451 FormatStyle Style;
1452 Lexer &Lex;
1453 SourceManager &SourceMgr;
1454 tooling::Replacements Replaces;
1455 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001456 std::vector<UnwrappedLine> UnwrappedLines;
1457 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001458};
1459
1460tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1461 SourceManager &SourceMgr,
1462 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001463 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1464 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1465 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1466 DiagnosticsEngine Diagnostics(
1467 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1468 &DiagnosticPrinter, false);
1469 Diagnostics.setSourceManager(&SourceMgr);
1470 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001471 return formatter.format();
1472}
1473
Daniel Jasper46ef8522013-01-10 13:08:12 +00001474LangOptions getFormattingLangOpts() {
1475 LangOptions LangOpts;
1476 LangOpts.CPlusPlus = 1;
1477 LangOpts.CPlusPlus11 = 1;
1478 LangOpts.Bool = 1;
1479 LangOpts.ObjC1 = 1;
1480 LangOpts.ObjC2 = 1;
1481 return LangOpts;
1482}
1483
Daniel Jaspercd162382013-01-07 13:26:07 +00001484} // namespace format
1485} // namespace clang