blob: 29debe58b6b1e44d66243309fd51ed876fb0ca45 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperf7935112012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasperda16db32013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasperda16db32013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper7194e182013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000042 TT_ObjCMethodExpr,
Nico Weber9efe2912013-01-10 23:11:41 +000043 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000044 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000045 TT_OverloadedOperator,
46 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000047 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000048 TT_TemplateCloser,
49 TT_TemplateOpener,
50 TT_TrailingUnaryOperator,
51 TT_UnaryOperator,
52 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000053};
54
55enum LineType {
56 LT_Invalid,
57 LT_Other,
58 LT_PreprocessorDirective,
59 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000060 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000061 LT_ObjCMethodDecl,
62 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000063};
64
Daniel Jasper7c85fde2013-01-08 14:56:18 +000065class AnnotatedToken {
66public:
67 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000068 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
69 CanBreakBefore(false), MustBreakBefore(false),
70 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071
72 bool is(tok::TokenKind Kind) const {
73 return FormatTok.Tok.is(Kind);
74 }
75 bool isNot(tok::TokenKind Kind) const {
76 return FormatTok.Tok.isNot(Kind);
77 }
78 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
79 return FormatTok.Tok.isObjCAtKeyword(Kind);
80 }
81
82 FormatToken FormatTok;
83
Daniel Jasperf7935112012-12-03 18:12:45 +000084 TokenType Type;
85
Daniel Jasperf7935112012-12-03 18:12:45 +000086 bool SpaceRequiredBefore;
87 bool CanBreakBefore;
88 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000089
90 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000091
92 std::vector<AnnotatedToken> Children;
93 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000094};
95
Daniel Jasper7c85fde2013-01-08 14:56:18 +000096static prec::Level getPrecedence(const AnnotatedToken &Tok) {
97 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000098}
99
Daniel Jasperf7935112012-12-03 18:12:45 +0000100FormatStyle getLLVMStyle() {
101 FormatStyle LLVMStyle;
102 LLVMStyle.ColumnLimit = 80;
103 LLVMStyle.MaxEmptyLinesToKeep = 1;
104 LLVMStyle.PointerAndReferenceBindToType = false;
105 LLVMStyle.AccessModifierOffset = -2;
106 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000107 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000108 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000109 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000110 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000111 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000112 return LLVMStyle;
113}
114
115FormatStyle getGoogleStyle() {
116 FormatStyle GoogleStyle;
117 GoogleStyle.ColumnLimit = 80;
118 GoogleStyle.MaxEmptyLinesToKeep = 1;
119 GoogleStyle.PointerAndReferenceBindToType = true;
120 GoogleStyle.AccessModifierOffset = -1;
121 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000122 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000123 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000124 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000125 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000126 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000127 return GoogleStyle;
128}
129
130struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000131 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000132 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000133 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000134};
135
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000136/// \brief Replaces the whitespace in front of \p Tok. Only call once for
137/// each \c FormatToken.
138static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
139 unsigned Spaces, const FormatStyle &Style,
140 SourceManager &SourceMgr,
141 tooling::Replacements &Replaces) {
142 Replaces.insert(tooling::Replacement(
143 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
144 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
145}
146
147/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
148/// backslashes to escape newlines inside a preprocessor directive.
149///
150/// This function and \c replaceWhitespace have the same behavior if
151/// \c Newlines == 0.
152static void replacePPWhitespace(
153 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
154 unsigned WhitespaceStartColumn, const FormatStyle &Style,
155 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
156 std::string NewLineText;
157 if (NewLines > 0) {
158 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
159 WhitespaceStartColumn);
160 for (unsigned i = 0; i < NewLines; ++i) {
161 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
162 NewLineText += "\\\n";
163 Offset = 0;
164 }
165 }
166 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
167 Tok.FormatTok.WhiteSpaceLength,
168 NewLineText + std::string(Spaces, ' ')));
169}
170
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000171/// \brief Checks whether the (remaining) \c UnwrappedLine starting with
172/// \p RootToken fits into \p Limit columns.
Nico Weberc9d73612013-01-12 22:48:47 +0000173static bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit) {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000174 unsigned Columns = RootToken.FormatTok.TokenLength;
175 bool FitsOnALine = true;
176 const AnnotatedToken *Tok = &RootToken;
177 while (!Tok->Children.empty()) {
178 Tok = &Tok->Children[0];
179 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
180 // A special case for the colon of a constructor initializer as this only
181 // needs to be put on a new line if the line needs to be split.
182 if (Columns > Limit ||
183 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
184 FitsOnALine = false;
185 break;
186 }
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000187 }
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000188 return FitsOnALine;
189}
190
Nico Weberc9d73612013-01-12 22:48:47 +0000191/// \brief Returns if a token is an Objective-C selector name.
192///
Nico Weber92c05392013-01-12 22:51:13 +0000193/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000194static bool isObjCSelectorName(const AnnotatedToken &Tok) {
195 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
196 Tok.Children[0].is(tok::colon) &&
197 Tok.Children[0].Type == TT_ObjCMethodExpr;
198}
199
Daniel Jasperf7935112012-12-03 18:12:45 +0000200class UnwrappedLineFormatter {
201public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000202 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
203 const UnwrappedLine &Line, unsigned FirstIndent,
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000204 bool FitsOnALine, const AnnotatedToken &RootToken,
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000205 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000206 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000207 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Rafael Espindola8f1187a2013-01-12 14:22:42 +0000208 RootToken(RootToken), Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000209 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000210 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000211 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000212 }
213
Manuel Klimek1abf7892013-01-04 23:34:14 +0000214 /// \brief Formats an \c UnwrappedLine.
215 ///
216 /// \returns The column after the last token in the last line of the
217 /// \c UnwrappedLine.
218 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000219 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000220 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000221 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000222 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000223 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000224 State.ForLoopVariablePos = 0;
225 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000226 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000227
228 // The first token has already been indented and thus consumed.
229 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000230
231 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000232 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000233 if (FitsOnALine) {
234 addTokenToState(false, false, State);
235 } else {
236 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
237 unsigned Break = calcPenalty(State, true, NoBreak);
238 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000239 if (State.NextToken != NULL &&
240 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
241 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
242 !fitsIntoLimit(*State.NextToken,
243 getColumnLimit() - State.Column - 1))
244 State.Stack.back().BreakAfterComma = true;
245 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000246 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000247 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000248 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000249 }
250
251private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000252 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000253 ParenState(unsigned Indent, unsigned LastSpace)
254 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
255 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000256
Daniel Jasperf7935112012-12-03 18:12:45 +0000257 /// \brief The position to which a specific parenthesis level needs to be
258 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000259 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000260
Daniel Jaspere9de2602012-12-06 09:56:08 +0000261 /// \brief The position of the last space on each level.
262 ///
263 /// Used e.g. to break like:
264 /// functionCall(Parameter, otherCall(
265 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000266 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000267
Daniel Jaspere9de2602012-12-06 09:56:08 +0000268 /// \brief The position the first "<<" operator encountered on each level.
269 ///
270 /// Used to align "<<" operators. 0 if no such operator has been encountered
271 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000272 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000273
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000274 /// \brief Whether a newline needs to be inserted before the block's closing
275 /// brace.
276 ///
277 /// We only want to insert a newline before the closing brace if there also
278 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000279 bool BreakBeforeClosingBrace;
280
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000281 bool BreakAfterComma;
282
Daniel Jasper337816e2013-01-11 10:22:12 +0000283 bool operator<(const ParenState &Other) const {
284 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000285 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000286 if (LastSpace != Other.LastSpace)
287 return LastSpace < Other.LastSpace;
288 if (FirstLessLess != Other.FirstLessLess)
289 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000290 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
291 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000292 if (BreakAfterComma != Other.BreakAfterComma)
293 return BreakAfterComma;
294 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000295 }
296 };
297
298 /// \brief The current state when indenting a unwrapped line.
299 ///
300 /// As the indenting tries different combinations this is copied by value.
301 struct LineState {
302 /// \brief The number of used columns in the current line.
303 unsigned Column;
304
305 /// \brief The token that needs to be next formatted.
306 const AnnotatedToken *NextToken;
307
308 /// \brief The parenthesis level of the first token on the current line.
309 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000310
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000311 /// \brief The column of the first variable in a for-loop declaration.
312 ///
313 /// Used to align the second variable if necessary.
314 unsigned ForLoopVariablePos;
315
316 /// \brief \c true if this line contains a continued for-loop section.
317 bool LineContainsContinuedForLoopSection;
318
Daniel Jasper337816e2013-01-11 10:22:12 +0000319 /// \brief A stack keeping track of properties applying to parenthesis
320 /// levels.
321 std::vector<ParenState> Stack;
322
323 /// \brief Comparison operator to be able to used \c LineState in \c map.
324 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000325 if (Other.NextToken != NextToken)
326 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 if (Other.Column != Column)
328 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000329 if (Other.StartOfLineLevel != StartOfLineLevel)
330 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000331 if (Other.ForLoopVariablePos != ForLoopVariablePos)
332 return Other.ForLoopVariablePos < ForLoopVariablePos;
333 if (Other.LineContainsContinuedForLoopSection !=
334 LineContainsContinuedForLoopSection)
335 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000336 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000337 }
338 };
339
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000340 /// \brief Appends the next token to \p State and updates information
341 /// necessary for indentation.
342 ///
343 /// Puts the token on the current line if \p Newline is \c true and adds a
344 /// line break and necessary indentation otherwise.
345 ///
346 /// If \p DryRun is \c false, also creates and stores the required
347 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000348 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000349 const AnnotatedToken &Current = *State.NextToken;
350 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000351 assert(State.Stack.size());
352 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000353
354 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000355 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000356 if (Current.is(tok::r_brace)) {
357 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000358 } else if (Current.is(tok::string_literal) &&
359 Previous.is(tok::string_literal)) {
360 State.Column = State.Column - Previous.FormatTok.TokenLength;
361 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 State.Stack[ParenLevel].FirstLessLess != 0) {
363 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000364 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000365 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
366 Current.is(tok::period) || Previous.is(tok::question) ||
367 Previous.Type == TT_ConditionalExpr)) {
368 // Indent and extra 4 spaces after if we know the current expression is
369 // continued. Don't do that on the top level, as we already indent 4
370 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000371 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000372 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000373 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000374 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000375 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000376 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000377 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000378 }
379
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000380 // A line starting with a closing brace is assumed to be correct for the
381 // same level as before the opening brace.
382 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000383
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000384 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000385 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000386
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000387 if (!DryRun) {
388 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000389 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
390 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000391 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000392 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000393 WhitespaceStartColumn, Style, SourceMgr,
394 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000395 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000396
Daniel Jasper337816e2013-01-11 10:22:12 +0000397 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000398 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000399 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000401 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
402 State.ForLoopVariablePos = State.Column -
403 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000404
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000405 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
406 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000407 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000408
Daniel Jasperf7935112012-12-03 18:12:45 +0000409 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000410 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000411
Daniel Jasperbcab4302013-01-09 10:40:23 +0000412 // FIXME: Do we need to do this for assignments nested in other
413 // expressions?
414 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000415 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000416 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000417 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000418 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000419 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000420 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000421
Daniel Jasper206df732013-01-07 13:08:40 +0000422 // Top-level spaces that are not part of assignments are exempt as that
423 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000424 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000425 if (Spaces > 0 &&
426 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000428 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000429 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000430 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000432 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000433 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000434
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000435 /// \brief Mark the next token as consumed in \p State and modify its stacks
436 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000438 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000439 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000440
Daniel Jasper337816e2013-01-11 10:22:12 +0000441 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
442 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000443
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000444 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000445 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000446 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
447 Current.is(tok::l_brace) ||
448 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000450 if (Current.is(tok::l_brace)) {
451 // FIXME: This does not work with nested static initializers.
452 // Implement a better handling for static initializers and similar
453 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000454 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000455 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000456 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000457 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000459 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000460 }
461
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000462 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000463 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000464 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
465 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
466 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000468 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000469
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000470 if (State.NextToken->Children.empty())
471 State.NextToken = NULL;
472 else
473 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000474
475 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000476 }
477
Nico Weber49cbc2c2013-01-07 15:15:29 +0000478 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000479 unsigned splitPenalty(const AnnotatedToken &Tok) {
480 const AnnotatedToken &Left = Tok;
481 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000482
483 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000484 if (RootToken.is(tok::kw_for) &&
485 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000486 return 20;
487
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000488 if (Left.is(tok::semi) || Left.is(tok::comma) ||
489 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000490 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000491
492 // In Objective-C method expressions, prefer breaking before "param:" over
493 // breaking after it.
494 if (isObjCSelectorName(Right))
495 return 0;
496 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
497 return 20;
498
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000499 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000500 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000501
Daniel Jasper399d24b2013-01-09 07:06:56 +0000502 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
503 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000504 prec::Level Level = getPrecedence(Left);
505
506 // Breaking after an assignment leads to a bad result as the two sides of
507 // the assignment are visually very close together.
508 if (Level == prec::Assignment)
509 return 50;
510
Daniel Jasperde5c2072012-12-24 00:13:23 +0000511 if (Level != prec::Unknown)
512 return Level;
513
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000514 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000515 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000516
Daniel Jasperf7935112012-12-03 18:12:45 +0000517 return 3;
518 }
519
Daniel Jasper2df93312013-01-09 10:16:05 +0000520 unsigned getColumnLimit() {
521 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
522 }
523
Daniel Jasperf7935112012-12-03 18:12:45 +0000524 /// \brief Calculate the number of lines needed to format the remaining part
525 /// of the unwrapped line.
526 ///
527 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000529 /// added after the previous token.
530 ///
531 /// \param StopAt is used for optimization. If we can determine that we'll
532 /// definitely need at least \p StopAt additional lines, we already know of a
533 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000534 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000535 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000536 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000537 return 0;
538
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000539 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000540 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000541 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000542 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000543 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000545 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000546 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000547 State.LineContainsContinuedForLoopSection)
548 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000549 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
550 State.NextToken->Type != TT_LineComment &&
551 State.Stack.back().BreakAfterComma)
552 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000553
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000554 unsigned CurrentPenalty = 0;
555 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000557 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000558 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000560 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000562 }
563
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000564 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000565
Daniel Jasper2df93312013-01-09 10:16:05 +0000566 // Exceeding column limit is bad, assign penalty.
567 if (State.Column > getColumnLimit()) {
568 unsigned ExcessCharacters = State.Column - getColumnLimit();
569 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
570 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000571
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 if (StopAt <= CurrentPenalty)
573 return UINT_MAX;
574 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000575 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000576 if (I != Memory.end()) {
577 // If this state has already been examined, we can safely return the
578 // previous result if we
579 // - have not hit the optimatization (and thus returned UINT_MAX) OR
580 // - are now computing for a smaller or equal StopAt.
581 unsigned SavedResult = I->second.first;
582 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000583 if (SavedResult != UINT_MAX)
584 return SavedResult + CurrentPenalty;
585 else if (StopAt <= SavedStopAt)
586 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000587 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000588
589 unsigned NoBreak = calcPenalty(State, false, StopAt);
590 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
591 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000592
593 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
594 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000595 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000596
597 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 }
599
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 FormatStyle Style;
601 SourceManager &SourceMgr;
602 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000603 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000604 const bool FitsOnALine;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000605 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000606 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000607
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000608 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000609 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000610 StateMap Memory;
611
Daniel Jasperf7935112012-12-03 18:12:45 +0000612 OptimizationParameters Parameters;
613};
614
615/// \brief Determines extra information about the tokens comprising an
616/// \c UnwrappedLine.
617class TokenAnnotator {
618public:
619 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000620 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000621 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000622 RootToken(Line.RootToken) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000623
624 /// \brief A parser that gathers additional information about tokens.
625 ///
626 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
627 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
628 /// into template parameter lists.
629 class AnnotatingParser {
630 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000631 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000632 : CurrentToken(&RootToken), KeywordVirtualFound(false),
633 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000634
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000635 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000636 while (CurrentToken != NULL) {
637 if (CurrentToken->is(tok::greater)) {
638 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000639 next();
640 return true;
641 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000642 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
643 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000644 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000645 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
646 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000648 if (!consumeToken())
649 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000650 }
651 return false;
652 }
653
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000655 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
656 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000657 while (CurrentToken != NULL) {
658 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 next();
660 return true;
661 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000662 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000663 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000664 if (!consumeToken())
665 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000666 }
667 return false;
668 }
669
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000670 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000671 if (!CurrentToken)
672 return false;
673
674 // A '[' could be an index subscript (after an indentifier or after
675 // ')' or ']'), or it could be the start of an Objective-C method
676 // expression.
677 AnnotatedToken *LSquare = CurrentToken->Parent;
678 bool StartsObjCMethodExpr =
679 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
680 LSquare->Parent->is(tok::l_square) ||
681 LSquare->Parent->is(tok::l_paren) ||
682 LSquare->Parent->is(tok::kw_return) ||
683 LSquare->Parent->is(tok::kw_throw) ||
684 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
685 true, true) > prec::Unknown;
686
687 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
688 if (StartsObjCMethodExpr) {
689 ColonIsObjCMethodExpr = true;
690 LSquare->Type = TT_ObjCMethodExpr;
691 }
692
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000693 while (CurrentToken != NULL) {
694 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000695 if (StartsObjCMethodExpr) {
696 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
697 CurrentToken->Type = TT_ObjCMethodExpr;
698 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000699 next();
700 return true;
701 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000702 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000703 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000704 if (!consumeToken())
705 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 }
707 return false;
708 }
709
Daniel Jasper83a54d22013-01-10 09:26:47 +0000710 bool parseBrace() {
711 while (CurrentToken != NULL) {
712 if (CurrentToken->is(tok::r_brace)) {
713 next();
714 return true;
715 }
716 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
717 return false;
718 if (!consumeToken())
719 return false;
720 }
721 // Lines can currently end with '{'.
722 return true;
723 }
724
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000725 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000726 while (CurrentToken != NULL) {
727 if (CurrentToken->is(tok::colon)) {
728 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000729 next();
730 return true;
731 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000732 if (!consumeToken())
733 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000734 }
735 return false;
736 }
737
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000738 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000739 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
740 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000741 next();
742 if (!parseAngle())
743 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000744 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000745 parseLine();
746 return true;
747 }
748 return false;
749 }
750
Daniel Jasperc0880a92013-01-04 18:52:56 +0000751 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000752 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000753 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000754 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000755 case tok::plus:
756 case tok::minus:
757 // At the start of the line, +/- specific ObjectiveC method
758 // declarations.
759 if (Tok->Parent == NULL)
760 Tok->Type = TT_ObjCMethodSpecifier;
761 break;
Nico Webera7252d82013-01-12 06:18:40 +0000762 case tok::colon:
763 // Colons from ?: are handled in parseConditional().
764 if (ColonIsObjCMethodExpr)
765 Tok->Type = TT_ObjCMethodExpr;
766 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000767 case tok::l_paren: {
768 bool ParensWereObjCReturnType =
769 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000770 if (!parseParens())
771 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
773 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000774 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000775 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
776 CurrentToken->Type = TT_ObjCSelectorStart;
777 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000778 }
Nico Weber9efe2912013-01-10 23:11:41 +0000779 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000781 if (!parseSquare())
782 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000783 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000784 case tok::l_brace:
785 if (!parseBrace())
786 return false;
787 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000788 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000789 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000790 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000791 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000792 Tok->Type = TT_BinaryOperator;
793 CurrentToken = Tok;
794 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000795 }
796 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000797 case tok::r_paren:
798 case tok::r_square:
799 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000800 case tok::r_brace:
801 // Lines can start with '}'.
802 if (Tok->Parent != NULL)
803 return false;
804 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000805 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000806 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000807 break;
808 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000809 if (CurrentToken->is(tok::l_paren)) {
810 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000811 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000812 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
813 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000814 next();
815 }
816 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000817 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
818 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000819 next();
820 }
821 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000822 break;
823 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000824 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000825 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000826 case tok::kw_template:
827 parseTemplateDeclaration();
828 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000829 default:
830 break;
831 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000832 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000833 }
834
Daniel Jasper050948a52012-12-21 17:58:39 +0000835 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000836 while (CurrentToken != NULL) {
837 if (CurrentToken->is(tok::slash))
838 CurrentToken->Type = TT_DirectorySeparator;
839 else if (CurrentToken->is(tok::less))
840 CurrentToken->Type = TT_TemplateOpener;
841 else if (CurrentToken->is(tok::greater))
842 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000843 next();
844 }
845 }
846
847 void parsePreprocessorDirective() {
848 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000849 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000850 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000851 // Hashes in the middle of a line can lead to any strange token
852 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000853 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000854 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000855 switch (
856 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000857 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000858 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000859 parseIncludeDirective();
860 break;
861 default:
862 break;
863 }
864 }
865
Daniel Jasperda16db32013-01-07 10:48:50 +0000866 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000867 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000868 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000869 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000870 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000871 while (CurrentToken != NULL) {
872 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000873 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000874 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000875 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000876 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000877 if (KeywordVirtualFound)
878 return LT_VirtualFunctionDecl;
879 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000880 }
881
882 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000883 if (CurrentToken != NULL && !CurrentToken->Children.empty())
884 CurrentToken = &CurrentToken->Children[0];
885 else
886 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000887 }
888
889 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000890 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000891 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000892 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000893 };
894
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000895 void createAnnotatedTokens(AnnotatedToken &Current) {
896 if (!Current.FormatTok.Children.empty()) {
897 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
898 Current.Children.back().Parent = &Current;
899 createAnnotatedTokens(Current.Children.back());
900 }
901 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000902
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 void calculateExtraInformation(AnnotatedToken &Current) {
904 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
905
Manuel Klimek52b15152013-01-09 15:25:02 +0000906 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000907 Current.MustBreakBefore = true;
908 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000909 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
910 TT_LineComment || (Current.is(tok::string_literal) &&
911 Current.Parent->is(tok::string_literal))) {
912 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000913 } else {
914 Current.MustBreakBefore = false;
915 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000916 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 if (!Current.Children.empty())
919 calculateExtraInformation(Current.Children[0]);
920 }
921
922 bool annotate() {
923 createAnnotatedTokens(RootToken);
924
925 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000926 CurrentLineType = Parser.parseLine();
927 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000928 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000929
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000930 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000931
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000933 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000934 else if (RootToken.Type == TT_ObjCDecl)
935 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000936 else if (RootToken.Type == TT_ObjCProperty)
937 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000938
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000939 if (!RootToken.Children.empty())
940 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000941 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000942 }
943
Daniel Jasperda16db32013-01-07 10:48:50 +0000944 LineType getLineType() {
945 return CurrentLineType;
946 }
947
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948 const AnnotatedToken &getRootToken() {
949 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000950 }
951
952private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000953 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
954 if (getPrecedence(Current) == prec::Assignment ||
955 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
956 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000957
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000958 if (Current.Type == TT_Unknown) {
959 if (Current.is(tok::star) || Current.is(tok::amp)) {
960 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000961 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
962 Current.is(tok::caret)) {
963 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
965 Current.Type = determineIncrementUsage(Current);
966 } else if (Current.is(tok::exclaim)) {
967 Current.Type = TT_UnaryOperator;
968 } else if (isBinaryOperator(Current)) {
969 Current.Type = TT_BinaryOperator;
970 } else if (Current.is(tok::comment)) {
971 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
972 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000973 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000974 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000975 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000976 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000977 } else if (Current.is(tok::r_paren) &&
978 (Current.Parent->Type == TT_PointerOrReference ||
979 Current.Parent->Type == TT_TemplateCloser)) {
980 // FIXME: We need to get smarter and understand more cases of casts.
981 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000982 } else if (Current.is(tok::at) && Current.Children.size()) {
983 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
984 case tok::objc_interface:
985 case tok::objc_implementation:
986 case tok::objc_protocol:
987 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000988 break;
989 case tok::objc_property:
990 Current.Type = TT_ObjCProperty;
991 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000992 default:
993 break;
994 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000995 }
996 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000997
998 if (!Current.Children.empty())
999 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001000 }
1001
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001002 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001003 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001004 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001005 }
1006
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001007 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
1008 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001009 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +00001011 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001012 const FormatToken &PrevToken = Tok.Parent->FormatTok;
1013 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +00001014
Daniel Jasper3c2557d2013-01-04 20:46:38 +00001015 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
1016 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +00001017 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
1018 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001019 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001020
Nico Weber5dafd4a2013-01-12 05:47:16 +00001021 if (PrevToken.Tok.isLiteral() || PrevToken.Tok.is(tok::r_paren) ||
1022 PrevToken.Tok.is(tok::r_square) || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001023 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
1024 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
1025 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
Nico Webereee7b812013-01-12 05:50:48 +00001026 NextToken.Tok.is(tok::l_paren) || NextToken.Tok.is(tok::l_square) ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001027 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001028 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001029
Daniel Jasper542de162013-01-02 15:46:59 +00001030 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
1031 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001032 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001033
Daniel Jasper426702d2012-12-05 07:51:39 +00001034 // It is very unlikely that we are going to find a pointer or reference type
1035 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001036 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001037 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001038
Daniel Jasperda16db32013-01-07 10:48:50 +00001039 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040 }
1041
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001042 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001043 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001044 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
1045 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
1046 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +00001047 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
Nico Weber63a54eb2013-01-12 05:41:23 +00001048 Tok.Parent->is(tok::at) || Tok.Parent->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001049 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001050
1051 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001052 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001053 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001054
1055 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001056 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001057 }
1058
1059 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001060 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1061 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001062 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001063
Daniel Jasperda16db32013-01-07 10:48:50 +00001064 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001065 }
1066
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001067 bool spaceRequiredBetween(const AnnotatedToken &Left,
1068 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001069 if (Right.is(tok::hashhash))
1070 return Left.is(tok::hash);
1071 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1072 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001073 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1074 return false;
Nico Webera6087752013-01-10 20:12:55 +00001075 if (Right.is(tok::less) &&
1076 (Left.is(tok::kw_template) ||
1077 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001078 return true;
1079 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1080 return false;
1081 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1082 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001083 if (Left.is(tok::at) &&
1084 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1085 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001086 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1087 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001088 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001089 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1090 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001091 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001092 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001093 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1094 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001095 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001096 return Right.FormatTok.Tok.isLiteral() ||
1097 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001098 if (Right.is(tok::star) && Left.is(tok::l_paren))
1099 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001100 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1101 return false;
1102 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001103 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001104 if (Left.is(tok::coloncolon) ||
1105 (Right.is(tok::coloncolon) &&
1106 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001107 return false;
1108 if (Left.is(tok::period) || Right.is(tok::period))
1109 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001110 if (Left.is(tok::colon))
1111 return Left.Type != TT_ObjCMethodExpr;
1112 if (Right.is(tok::colon))
1113 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001114 if (Left.is(tok::l_paren))
1115 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001116 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001117 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1118 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001119 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001120 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1121 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001122 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001123 if (Left.is(tok::at) &&
1124 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001125 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001126 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1127 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001128 return true;
1129 }
1130
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001131 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001132 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001133 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1134 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001135 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001136 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001137 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001138 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001139 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1140 if (Tok.Type == TT_ObjCSelectorStart)
1141 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001143 // Don't space between ')' and <id>
1144 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001145 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001146 // Don't space between ':' and '('
1147 return false;
1148 }
Nico Webera2a84952013-01-10 21:30:42 +00001149 if (CurrentLineType == LT_ObjCProperty &&
1150 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1151 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001152
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001153 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001154 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001155 if (Tok.Type == TT_OverloadedOperator)
1156 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001157 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001158 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001159 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001160 if (Tok.is(tok::colon))
Nico Webera7252d82013-01-12 06:18:40 +00001161 return RootToken.isNot(tok::kw_case) && !Tok.Children.empty() &&
1162 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001163 if (Tok.Parent->Type == TT_UnaryOperator ||
1164 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001165 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001166 if (Tok.Type == TT_UnaryOperator)
1167 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001168 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1169 (Tok.Parent->isNot(tok::colon) ||
1170 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001171 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1172 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001173 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1174 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001175 if (Tok.Type == TT_DirectorySeparator ||
1176 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001177 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001178 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001179 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001180 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001181 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001182 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001183 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001184 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001185 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001186 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001187 }
1188
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001189 bool canBreakBefore(const AnnotatedToken &Right) {
1190 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001191 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001192 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1193 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001194 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001195 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1196 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001197 // Don't break this identifier as ':' or identifier
1198 // before it will break.
1199 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001200 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1201 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001202 // Don't break at ':' if identifier before it can beak.
1203 return false;
1204 }
Nico Webera7252d82013-01-12 06:18:40 +00001205 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1206 return false;
1207 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1208 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001209 if (isObjCSelectorName(Right))
1210 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001211 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001212 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001213 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001214 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001215 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001216 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001217 return false;
1218
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001219 if (Right.is(tok::comment))
1220 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001222 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001223 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001224 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1225 Left.is(tok::comma) || Right.is(tok::lessless) ||
1226 Right.is(tok::arrow) || Right.is(tok::period) ||
1227 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001228 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001229 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001230 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1231 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001232 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001233 }
1234
Daniel Jasperf7935112012-12-03 18:12:45 +00001235 FormatStyle Style;
1236 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001237 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001238 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001239 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001240};
1241
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001242class LexerBasedFormatTokenSource : public FormatTokenSource {
1243public:
1244 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001245 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001246 IdentTable(Lex.getLangOpts()) {
1247 Lex.SetKeepWhitespaceMode(true);
1248 }
1249
1250 virtual FormatToken getNextToken() {
1251 if (GreaterStashed) {
1252 FormatTok.NewlinesBefore = 0;
1253 FormatTok.WhiteSpaceStart =
1254 FormatTok.Tok.getLocation().getLocWithOffset(1);
1255 FormatTok.WhiteSpaceLength = 0;
1256 GreaterStashed = false;
1257 return FormatTok;
1258 }
1259
1260 FormatTok = FormatToken();
1261 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001262 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001263 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001264 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1265 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001266
1267 // Consume and record whitespace until we find a significant token.
1268 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001269 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001270 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1271 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001272 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1273
1274 if (FormatTok.Tok.is(tok::eof))
1275 return FormatTok;
1276 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001277 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001278 }
Manuel Klimekef920692013-01-07 07:56:50 +00001279
1280 // Now FormatTok is the next non-whitespace token.
1281 FormatTok.TokenLength = Text.size();
1282
Manuel Klimek1abf7892013-01-04 23:34:14 +00001283 // In case the token starts with escaped newlines, we want to
1284 // take them into account as whitespace - this pattern is quite frequent
1285 // in macro definitions.
1286 // FIXME: What do we want to do with other escaped spaces, and escaped
1287 // spaces or newlines in the middle of tokens?
1288 // FIXME: Add a more explicit test.
1289 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001290 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001291 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001292 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001293 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001294 }
1295
1296 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001297 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001298 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001299 FormatTok.Tok.setKind(Info.getTokenID());
1300 }
1301
1302 if (FormatTok.Tok.is(tok::greatergreater)) {
1303 FormatTok.Tok.setKind(tok::greater);
1304 GreaterStashed = true;
1305 }
1306
1307 return FormatTok;
1308 }
1309
1310private:
1311 FormatToken FormatTok;
1312 bool GreaterStashed;
1313 Lexer &Lex;
1314 SourceManager &SourceMgr;
1315 IdentifierTable IdentTable;
1316
1317 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001318 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001319 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1320 Tok.getLength());
1321 }
1322};
1323
Daniel Jasperf7935112012-12-03 18:12:45 +00001324class Formatter : public UnwrappedLineConsumer {
1325public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001326 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1327 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001328 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001329 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001330 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001331
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001332 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001333
Daniel Jasperf7935112012-12-03 18:12:45 +00001334 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001335 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001336 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001337 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001338 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001339 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1340 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001341 I != E; ++I) {
1342 const UnwrappedLine &TheLine = *I;
1343 if (touchesRanges(TheLine)) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001344 OwningPtr<TokenAnnotator> AnnotatedLine(
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001345 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1346 if (!AnnotatedLine->annotate())
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001347 break;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001348 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001349 TheLine.Level, TheLine.InPPDirective,
1350 PreviousEndOfLineColumn);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001351
1352 UnwrappedLine Line(TheLine);
1353 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1354 I, E);
1355 UnwrappedLineFormatter Formatter(
1356 Style, SourceMgr, Line, Indent, FitsOnALine,
Rafael Espindola8f1187a2013-01-12 14:22:42 +00001357 AnnotatedLine->getRootToken(), Replaces, StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001358 PreviousEndOfLineColumn = Formatter.format();
1359 } else {
1360 // If we did not reformat this unwrapped line, the column at the end of
1361 // the last token is unchanged - thus, we can calculate the end of the
1362 // last token, and return the result.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001363 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001364 PreviousEndOfLineColumn =
1365 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1366 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1367 Lex.getLangOpts()) -
1368 1;
1369 }
1370 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001371 return Replaces;
1372 }
1373
1374private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001375 /// \brief Tries to merge lines into one.
1376 ///
1377 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1378 /// if possible; note that \c I will be incremented when lines are merged.
1379 ///
1380 /// Returns whether the resulting \c Line can fit in a single line.
1381 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001382 OwningPtr<TokenAnnotator> &AnnotatedLine,
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001383 std::vector<UnwrappedLine>::iterator &I,
1384 std::vector<UnwrappedLine>::iterator E) {
1385 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1386
1387 // Check whether the UnwrappedLine can be put onto a single line. If
1388 // so, this is bound to be the optimal solution (by definition) and we
1389 // don't need to analyze the entire solution space.
1390 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1391 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1392 return FitsOnALine;
1393
1394 // Try to merge the next two lines if possible.
1395 UnwrappedLine Combined(Line);
1396
1397 // First, check that the current line allows merging. This is the case if
1398 // we're not in a control flow statement and the last token is an opening
1399 // brace.
1400 FormatToken *Last = &Combined.RootToken;
1401 bool AllowedTokens =
Manuel Klimek2acb7b72013-01-11 19:17:44 +00001402 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1403 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1404 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1405 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001406 // This gets rid of all ObjC @ keywords and methods.
1407 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus) &&
1408 Last->Tok.isNot(tok::plus);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001409 while (!Last->Children.empty())
1410 Last = &Last->Children.back();
1411 if (!Last->Tok.is(tok::l_brace))
1412 return FitsOnALine;
1413
1414 // Second, check that the next line does not contain any braces - if it
1415 // does, readability declines when putting it into a single line.
1416 const FormatToken *Next = &(I + 1)->RootToken;
1417 while (Next) {
1418 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1419 !Next->Tok.is(tok::r_brace);
1420 Last->Children.push_back(*Next);
1421 Last = &Last->Children[0];
1422 Last->Children.clear();
1423 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1424 }
1425
1426 // Last, check that the third line contains a single closing brace.
1427 Next = &(I + 2)->RootToken;
1428 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1429 if (!Next->Children.empty() || !AllowedTokens)
1430 return FitsOnALine;
1431 Last->Children.push_back(*Next);
1432
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001433 OwningPtr<TokenAnnotator> CombinedAnnotator(
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001434 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1435 if (CombinedAnnotator->annotate() &&
1436 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1437 // If the merged line fits, we use that instead and skip the next two
1438 // lines.
1439 AnnotatedLine.reset(CombinedAnnotator.take());
1440 Line = Combined;
1441 I += 2;
1442 }
1443 return FitsOnALine;
1444 }
1445
1446 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001447 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001448 while (!Last->Children.empty())
1449 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001450 return Last;
1451 }
1452
1453 bool touchesRanges(const UnwrappedLine &TheLine) {
1454 const FormatToken *First = &TheLine.RootToken;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001455 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001456 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001457 First->Tok.getLocation(),
1458 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001459 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001460 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1461 Ranges[i].getBegin()) &&
1462 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1463 LineRange.getBegin()))
1464 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001465 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001466 return false;
1467 }
1468
1469 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1470 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001471 }
1472
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001473 /// \brief Add a new line and the required indent before the first Token
1474 /// of the \c UnwrappedLine if there was no structural parsing error.
1475 /// Returns the indent level of the \c UnwrappedLine.
1476 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1477 bool InPPDirective,
1478 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001479 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001480 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1481 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1482
1483 unsigned Newlines = std::min(Tok.NewlinesBefore,
1484 Style.MaxEmptyLinesToKeep + 1);
1485 if (Newlines == 0 && !Tok.IsFirst)
1486 Newlines = 1;
1487 unsigned Indent = Level * 2;
1488
1489 bool IsAccessModifier = false;
1490 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1491 RootToken.is(tok::kw_private))
1492 IsAccessModifier = true;
1493 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1494 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1495 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1496 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1497 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1498 IsAccessModifier = true;
1499
1500 if (IsAccessModifier &&
1501 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1502 Indent += Style.AccessModifierOffset;
1503 if (!InPPDirective || Tok.HasUnescapedNewline) {
1504 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1505 } else {
1506 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1507 SourceMgr, Replaces);
1508 }
1509 return Indent;
1510 }
1511
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001512 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001513 FormatStyle Style;
1514 Lexer &Lex;
1515 SourceManager &SourceMgr;
1516 tooling::Replacements Replaces;
1517 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001518 std::vector<UnwrappedLine> UnwrappedLines;
1519 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001520};
1521
1522tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1523 SourceManager &SourceMgr,
1524 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001525 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1526 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1527 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1528 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001529 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001530 &DiagnosticPrinter, false);
1531 Diagnostics.setSourceManager(&SourceMgr);
1532 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 return formatter.format();
1534}
1535
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001536LangOptions getFormattingLangOpts() {
1537 LangOptions LangOpts;
1538 LangOpts.CPlusPlus = 1;
1539 LangOpts.CPlusPlus11 = 1;
1540 LangOpts.Bool = 1;
1541 LangOpts.ObjC1 = 1;
1542 LangOpts.ObjC2 = 1;
1543 return LangOpts;
1544}
1545
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001546} // namespace format
1547} // namespace clang