blob: 61d2f7fb63feb5c589b8ca47aee2588b7d85a14e [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.
173bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit) {
174 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
Daniel Jasperf7935112012-12-03 18:12:45 +0000191class UnwrappedLineFormatter {
192public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000193 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
194 const UnwrappedLine &Line, unsigned FirstIndent,
195 bool FitsOnALine, LineType CurrentLineType,
196 const AnnotatedToken &RootToken,
197 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000198 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000199 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000200 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000201 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000202 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000203 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000204 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000205 }
206
Manuel Klimek1abf7892013-01-04 23:34:14 +0000207 /// \brief Formats an \c UnwrappedLine.
208 ///
209 /// \returns The column after the last token in the last line of the
210 /// \c UnwrappedLine.
211 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000212 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000213 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000214 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000215 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000216 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000217 State.ForLoopVariablePos = 0;
218 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000219 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000220
221 // The first token has already been indented and thus consumed.
222 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000223
224 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000225 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000226 if (FitsOnALine) {
227 addTokenToState(false, false, State);
228 } else {
229 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
230 unsigned Break = calcPenalty(State, true, NoBreak);
231 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000232 if (State.NextToken != NULL &&
233 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
234 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
235 !fitsIntoLimit(*State.NextToken,
236 getColumnLimit() - State.Column - 1))
237 State.Stack.back().BreakAfterComma = true;
238 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000239 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000240 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000241 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 }
243
244private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000245 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000246 ParenState(unsigned Indent, unsigned LastSpace)
247 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
248 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000249
Daniel Jasperf7935112012-12-03 18:12:45 +0000250 /// \brief The position to which a specific parenthesis level needs to be
251 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000252 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000253
Daniel Jaspere9de2602012-12-06 09:56:08 +0000254 /// \brief The position of the last space on each level.
255 ///
256 /// Used e.g. to break like:
257 /// functionCall(Parameter, otherCall(
258 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000259 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000260
Daniel Jaspere9de2602012-12-06 09:56:08 +0000261 /// \brief The position the first "<<" operator encountered on each level.
262 ///
263 /// Used to align "<<" operators. 0 if no such operator has been encountered
264 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000265 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000266
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000267 /// \brief Whether a newline needs to be inserted before the block's closing
268 /// brace.
269 ///
270 /// We only want to insert a newline before the closing brace if there also
271 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000272 bool BreakBeforeClosingBrace;
273
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000274 bool BreakAfterComma;
275
Daniel Jasper337816e2013-01-11 10:22:12 +0000276 bool operator<(const ParenState &Other) const {
277 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000278 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000279 if (LastSpace != Other.LastSpace)
280 return LastSpace < Other.LastSpace;
281 if (FirstLessLess != Other.FirstLessLess)
282 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000283 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
284 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000285 if (BreakAfterComma != Other.BreakAfterComma)
286 return BreakAfterComma;
287 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000288 }
289 };
290
291 /// \brief The current state when indenting a unwrapped line.
292 ///
293 /// As the indenting tries different combinations this is copied by value.
294 struct LineState {
295 /// \brief The number of used columns in the current line.
296 unsigned Column;
297
298 /// \brief The token that needs to be next formatted.
299 const AnnotatedToken *NextToken;
300
301 /// \brief The parenthesis level of the first token on the current line.
302 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000303
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000304 /// \brief The column of the first variable in a for-loop declaration.
305 ///
306 /// Used to align the second variable if necessary.
307 unsigned ForLoopVariablePos;
308
309 /// \brief \c true if this line contains a continued for-loop section.
310 bool LineContainsContinuedForLoopSection;
311
Daniel Jasper337816e2013-01-11 10:22:12 +0000312 /// \brief A stack keeping track of properties applying to parenthesis
313 /// levels.
314 std::vector<ParenState> Stack;
315
316 /// \brief Comparison operator to be able to used \c LineState in \c map.
317 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000318 if (Other.NextToken != NextToken)
319 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000320 if (Other.Column != Column)
321 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000322 if (Other.StartOfLineLevel != StartOfLineLevel)
323 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000324 if (Other.ForLoopVariablePos != ForLoopVariablePos)
325 return Other.ForLoopVariablePos < ForLoopVariablePos;
326 if (Other.LineContainsContinuedForLoopSection !=
327 LineContainsContinuedForLoopSection)
328 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000329 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000330 }
331 };
332
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000333 /// \brief Appends the next token to \p State and updates information
334 /// necessary for indentation.
335 ///
336 /// Puts the token on the current line if \p Newline is \c true and adds a
337 /// line break and necessary indentation otherwise.
338 ///
339 /// If \p DryRun is \c false, also creates and stores the required
340 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000342 const AnnotatedToken &Current = *State.NextToken;
343 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000344 assert(State.Stack.size());
345 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000346
347 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000348 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000349 if (Current.is(tok::r_brace)) {
350 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000351 } else if (Current.is(tok::string_literal) &&
352 Previous.is(tok::string_literal)) {
353 State.Column = State.Column - Previous.FormatTok.TokenLength;
354 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000355 State.Stack[ParenLevel].FirstLessLess != 0) {
356 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000358 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
359 Current.is(tok::period) || Previous.is(tok::question) ||
360 Previous.Type == TT_ConditionalExpr)) {
361 // Indent and extra 4 spaces after if we know the current expression is
362 // continued. Don't do that on the top level, as we already indent 4
363 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000364 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000365 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000367 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000368 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000369 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000370 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000371 }
372
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000373 // A line starting with a closing brace is assumed to be correct for the
374 // same level as before the opening brace.
375 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000376
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000377 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000378 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000379
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000380 if (!DryRun) {
381 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000382 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
383 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000384 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000385 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000386 WhitespaceStartColumn, Style, SourceMgr,
387 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000388 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000389
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000391 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000392 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000393 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000394 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
395 State.ForLoopVariablePos = State.Column -
396 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000397
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000398 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
399 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000400 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000401
Daniel Jasperf7935112012-12-03 18:12:45 +0000402 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000403 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000404
Daniel Jasperbcab4302013-01-09 10:40:23 +0000405 // FIXME: Do we need to do this for assignments nested in other
406 // expressions?
407 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000408 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000409 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000410 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000411 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000412 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000413 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000414
Daniel Jasper206df732013-01-07 13:08:40 +0000415 // Top-level spaces that are not part of assignments are exempt as that
416 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000417 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000418 if (Spaces > 0 &&
419 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000420 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000421 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000422 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000423 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000425 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000426 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000427
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000428 /// \brief Mark the next token as consumed in \p State and modify its stacks
429 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000430 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000431 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000432 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000433
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
435 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000436
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000437 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000438 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000439 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
440 Current.is(tok::l_brace) ||
441 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000442 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000443 if (Current.is(tok::l_brace)) {
444 // FIXME: This does not work with nested static initializers.
445 // Implement a better handling for static initializers and similar
446 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000447 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000448 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000450 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000451 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000452 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000453 }
454
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000455 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000456 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000457 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
458 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
459 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000460 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000461 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000462
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000463 if (State.NextToken->Children.empty())
464 State.NextToken = NULL;
465 else
466 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000467
468 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000469 }
470
Nico Weber49cbc2c2013-01-07 15:15:29 +0000471 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000472 unsigned splitPenalty(const AnnotatedToken &Tok) {
473 const AnnotatedToken &Left = Tok;
474 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000475
476 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000477 if (RootToken.is(tok::kw_for) &&
478 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000479 return 20;
480
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000481 if (Left.is(tok::semi) || Left.is(tok::comma) ||
482 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000483 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000484 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000485 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000486
Daniel Jasper399d24b2013-01-09 07:06:56 +0000487 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
488 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000489 prec::Level Level = getPrecedence(Left);
490
491 // Breaking after an assignment leads to a bad result as the two sides of
492 // the assignment are visually very close together.
493 if (Level == prec::Assignment)
494 return 50;
495
Daniel Jasperde5c2072012-12-24 00:13:23 +0000496 if (Level != prec::Unknown)
497 return Level;
498
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000499 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000500 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000501
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 return 3;
503 }
504
Daniel Jasper2df93312013-01-09 10:16:05 +0000505 unsigned getColumnLimit() {
506 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
507 }
508
Daniel Jasperf7935112012-12-03 18:12:45 +0000509 /// \brief Calculate the number of lines needed to format the remaining part
510 /// of the unwrapped line.
511 ///
512 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000513 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000514 /// added after the previous token.
515 ///
516 /// \param StopAt is used for optimization. If we can determine that we'll
517 /// definitely need at least \p StopAt additional lines, we already know of a
518 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000520 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000521 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 return 0;
523
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000524 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000526 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000528 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000529 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000530 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000531 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000532 State.LineContainsContinuedForLoopSection)
533 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000534 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
535 State.NextToken->Type != TT_LineComment &&
536 State.Stack.back().BreakAfterComma)
537 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000538
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000539 unsigned CurrentPenalty = 0;
540 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000541 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000542 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000543 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000545 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000546 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000547 }
548
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000549 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000550
Daniel Jasper2df93312013-01-09 10:16:05 +0000551 // Exceeding column limit is bad, assign penalty.
552 if (State.Column > getColumnLimit()) {
553 unsigned ExcessCharacters = State.Column - getColumnLimit();
554 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
555 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000556
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 if (StopAt <= CurrentPenalty)
558 return UINT_MAX;
559 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000561 if (I != Memory.end()) {
562 // If this state has already been examined, we can safely return the
563 // previous result if we
564 // - have not hit the optimatization (and thus returned UINT_MAX) OR
565 // - are now computing for a smaller or equal StopAt.
566 unsigned SavedResult = I->second.first;
567 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000568 if (SavedResult != UINT_MAX)
569 return SavedResult + CurrentPenalty;
570 else if (StopAt <= SavedStopAt)
571 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000572 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000573
574 unsigned NoBreak = calcPenalty(State, false, StopAt);
575 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
576 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000577
578 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
579 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000580 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000581
582 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 }
584
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 FormatStyle Style;
586 SourceManager &SourceMgr;
587 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000588 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000589 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000590 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000591 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000593
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000594 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000595 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000596 StateMap Memory;
597
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 OptimizationParameters Parameters;
599};
600
601/// \brief Determines extra information about the tokens comprising an
602/// \c UnwrappedLine.
603class TokenAnnotator {
604public:
605 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000606 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000607 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000608 RootToken(Line.RootToken) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000609
610 /// \brief A parser that gathers additional information about tokens.
611 ///
612 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
613 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
614 /// into template parameter lists.
615 class AnnotatingParser {
616 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000617 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000618 : CurrentToken(&RootToken), KeywordVirtualFound(false),
619 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000620
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000621 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000622 while (CurrentToken != NULL) {
623 if (CurrentToken->is(tok::greater)) {
624 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000625 next();
626 return true;
627 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
629 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000631 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
632 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000633 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000634 if (!consumeToken())
635 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 }
637 return false;
638 }
639
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000640 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000641 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
642 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000643 while (CurrentToken != NULL) {
644 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000645 next();
646 return true;
647 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000648 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000649 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000650 if (!consumeToken())
651 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 }
653 return false;
654 }
655
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000656 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000657 if (!CurrentToken)
658 return false;
659
660 // A '[' could be an index subscript (after an indentifier or after
661 // ')' or ']'), or it could be the start of an Objective-C method
662 // expression.
663 AnnotatedToken *LSquare = CurrentToken->Parent;
664 bool StartsObjCMethodExpr =
665 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
666 LSquare->Parent->is(tok::l_square) ||
667 LSquare->Parent->is(tok::l_paren) ||
668 LSquare->Parent->is(tok::kw_return) ||
669 LSquare->Parent->is(tok::kw_throw) ||
670 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
671 true, true) > prec::Unknown;
672
673 bool ColonWasObjCMethodExpr = ColonIsObjCMethodExpr;
674 if (StartsObjCMethodExpr) {
675 ColonIsObjCMethodExpr = true;
676 LSquare->Type = TT_ObjCMethodExpr;
677 }
678
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000679 while (CurrentToken != NULL) {
680 if (CurrentToken->is(tok::r_square)) {
Nico Webera7252d82013-01-12 06:18:40 +0000681 if (StartsObjCMethodExpr) {
682 ColonIsObjCMethodExpr = ColonWasObjCMethodExpr;
683 CurrentToken->Type = TT_ObjCMethodExpr;
684 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000685 next();
686 return true;
687 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000688 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000689 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000690 if (!consumeToken())
691 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 }
693 return false;
694 }
695
Daniel Jasper83a54d22013-01-10 09:26:47 +0000696 bool parseBrace() {
697 while (CurrentToken != NULL) {
698 if (CurrentToken->is(tok::r_brace)) {
699 next();
700 return true;
701 }
702 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
703 return false;
704 if (!consumeToken())
705 return false;
706 }
707 // Lines can currently end with '{'.
708 return true;
709 }
710
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000711 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000712 while (CurrentToken != NULL) {
713 if (CurrentToken->is(tok::colon)) {
714 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 next();
716 return true;
717 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000718 if (!consumeToken())
719 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000720 }
721 return false;
722 }
723
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000724 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000725 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
726 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000727 next();
728 if (!parseAngle())
729 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000730 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000731 parseLine();
732 return true;
733 }
734 return false;
735 }
736
Daniel Jasperc0880a92013-01-04 18:52:56 +0000737 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000738 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000740 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000741 case tok::plus:
742 case tok::minus:
743 // At the start of the line, +/- specific ObjectiveC method
744 // declarations.
745 if (Tok->Parent == NULL)
746 Tok->Type = TT_ObjCMethodSpecifier;
747 break;
Nico Webera7252d82013-01-12 06:18:40 +0000748 case tok::colon:
749 // Colons from ?: are handled in parseConditional().
750 if (ColonIsObjCMethodExpr)
751 Tok->Type = TT_ObjCMethodExpr;
752 break;
Nico Weber9efe2912013-01-10 23:11:41 +0000753 case tok::l_paren: {
754 bool ParensWereObjCReturnType =
755 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000756 if (!parseParens())
757 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
759 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000760 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000761 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
762 CurrentToken->Type = TT_ObjCSelectorStart;
763 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000764 }
Nico Weber9efe2912013-01-10 23:11:41 +0000765 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000766 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000767 if (!parseSquare())
768 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000769 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000770 case tok::l_brace:
771 if (!parseBrace())
772 return false;
773 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000775 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000777 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000778 Tok->Type = TT_BinaryOperator;
779 CurrentToken = Tok;
780 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 }
782 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000783 case tok::r_paren:
784 case tok::r_square:
785 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000786 case tok::r_brace:
787 // Lines can start with '}'.
788 if (Tok->Parent != NULL)
789 return false;
790 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000791 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000792 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000793 break;
794 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000795 if (CurrentToken->is(tok::l_paren)) {
796 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000797 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000798 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
799 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000800 next();
801 }
802 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000803 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
804 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000805 next();
806 }
807 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 break;
809 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000810 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000811 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000812 case tok::kw_template:
813 parseTemplateDeclaration();
814 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000815 default:
816 break;
817 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000818 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000819 }
820
Daniel Jasper050948a52012-12-21 17:58:39 +0000821 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000822 while (CurrentToken != NULL) {
823 if (CurrentToken->is(tok::slash))
824 CurrentToken->Type = TT_DirectorySeparator;
825 else if (CurrentToken->is(tok::less))
826 CurrentToken->Type = TT_TemplateOpener;
827 else if (CurrentToken->is(tok::greater))
828 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000829 next();
830 }
831 }
832
833 void parsePreprocessorDirective() {
834 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000835 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000836 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000837 // Hashes in the middle of a line can lead to any strange token
838 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000840 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000841 switch (
842 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000843 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000844 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000845 parseIncludeDirective();
846 break;
847 default:
848 break;
849 }
850 }
851
Daniel Jasperda16db32013-01-07 10:48:50 +0000852 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000853 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000854 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000855 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000856 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000857 while (CurrentToken != NULL) {
858 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000859 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000860 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000861 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000862 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000863 if (KeywordVirtualFound)
864 return LT_VirtualFunctionDecl;
865 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 }
867
868 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000869 if (CurrentToken != NULL && !CurrentToken->Children.empty())
870 CurrentToken = &CurrentToken->Children[0];
871 else
872 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000873 }
874
875 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000877 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +0000878 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000879 };
880
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000881 void createAnnotatedTokens(AnnotatedToken &Current) {
882 if (!Current.FormatTok.Children.empty()) {
883 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
884 Current.Children.back().Parent = &Current;
885 createAnnotatedTokens(Current.Children.back());
886 }
887 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000888
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000889 void calculateExtraInformation(AnnotatedToken &Current) {
890 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
891
Manuel Klimek52b15152013-01-09 15:25:02 +0000892 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000893 Current.MustBreakBefore = true;
894 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000895 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
896 TT_LineComment || (Current.is(tok::string_literal) &&
897 Current.Parent->is(tok::string_literal))) {
898 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000899 } else {
900 Current.MustBreakBefore = false;
901 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000902 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000904 if (!Current.Children.empty())
905 calculateExtraInformation(Current.Children[0]);
906 }
907
908 bool annotate() {
909 createAnnotatedTokens(RootToken);
910
911 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000912 CurrentLineType = Parser.parseLine();
913 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000914 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000916 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000917
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000919 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000920 else if (RootToken.Type == TT_ObjCDecl)
921 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000922 else if (RootToken.Type == TT_ObjCProperty)
923 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000924
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000925 if (!RootToken.Children.empty())
926 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000927 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 }
929
Daniel Jasperda16db32013-01-07 10:48:50 +0000930 LineType getLineType() {
931 return CurrentLineType;
932 }
933
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000934 const AnnotatedToken &getRootToken() {
935 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000936 }
937
938private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000939 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
940 if (getPrecedence(Current) == prec::Assignment ||
941 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
942 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000943
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000944 if (Current.Type == TT_Unknown) {
945 if (Current.is(tok::star) || Current.is(tok::amp)) {
946 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000947 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
948 Current.is(tok::caret)) {
949 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000950 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
951 Current.Type = determineIncrementUsage(Current);
952 } else if (Current.is(tok::exclaim)) {
953 Current.Type = TT_UnaryOperator;
954 } else if (isBinaryOperator(Current)) {
955 Current.Type = TT_BinaryOperator;
956 } else if (Current.is(tok::comment)) {
957 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
958 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000959 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000960 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000962 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000963 } else if (Current.is(tok::r_paren) &&
964 (Current.Parent->Type == TT_PointerOrReference ||
965 Current.Parent->Type == TT_TemplateCloser)) {
966 // FIXME: We need to get smarter and understand more cases of casts.
967 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000968 } else if (Current.is(tok::at) && Current.Children.size()) {
969 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
970 case tok::objc_interface:
971 case tok::objc_implementation:
972 case tok::objc_protocol:
973 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000974 break;
975 case tok::objc_property:
976 Current.Type = TT_ObjCProperty;
977 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000978 default:
979 break;
980 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 }
982 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000983
984 if (!Current.Children.empty())
985 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000986 }
987
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000988 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000989 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000990 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000991 }
992
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000993 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
994 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000995 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000996 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000997 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000998 const FormatToken &PrevToken = Tok.Parent->FormatTok;
999 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +00001000
Daniel Jasper3c2557d2013-01-04 20:46:38 +00001001 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
1002 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +00001003 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
1004 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001005 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006
Nico Weber5dafd4a2013-01-12 05:47:16 +00001007 if (PrevToken.Tok.isLiteral() || PrevToken.Tok.is(tok::r_paren) ||
1008 PrevToken.Tok.is(tok::r_square) || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001009 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
1010 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
1011 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
Nico Webereee7b812013-01-12 05:50:48 +00001012 NextToken.Tok.is(tok::l_paren) || NextToken.Tok.is(tok::l_square) ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001013 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001014 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001015
Daniel Jasper542de162013-01-02 15:46:59 +00001016 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
1017 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001018 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001019
Daniel Jasper426702d2012-12-05 07:51:39 +00001020 // It is very unlikely that we are going to find a pointer or reference type
1021 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001022 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001023 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001024
Daniel Jasperda16db32013-01-07 10:48:50 +00001025 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001026 }
1027
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001028 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001029 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001030 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
1031 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
1032 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +00001033 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
Nico Weber63a54eb2013-01-12 05:41:23 +00001034 Tok.Parent->is(tok::at) || Tok.Parent->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001035 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001036
1037 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001038 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001039 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001040
1041 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001042 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001043 }
1044
1045 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001046 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1047 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001048 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001049
Daniel Jasperda16db32013-01-07 10:48:50 +00001050 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001051 }
1052
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 bool spaceRequiredBetween(const AnnotatedToken &Left,
1054 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001055 if (Right.is(tok::hashhash))
1056 return Left.is(tok::hash);
1057 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1058 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001059 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1060 return false;
Nico Webera6087752013-01-10 20:12:55 +00001061 if (Right.is(tok::less) &&
1062 (Left.is(tok::kw_template) ||
1063 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001064 return true;
1065 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1066 return false;
1067 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1068 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001069 if (Left.is(tok::at) &&
1070 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1071 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001072 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1073 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001074 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001075 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1076 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001077 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001079 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1080 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001081 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001082 return Right.FormatTok.Tok.isLiteral() ||
1083 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001084 if (Right.is(tok::star) && Left.is(tok::l_paren))
1085 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001086 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1087 return false;
1088 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001089 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001090 if (Left.is(tok::coloncolon) ||
1091 (Right.is(tok::coloncolon) &&
1092 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 return false;
1094 if (Left.is(tok::period) || Right.is(tok::period))
1095 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001096 if (Left.is(tok::colon))
1097 return Left.Type != TT_ObjCMethodExpr;
1098 if (Right.is(tok::colon))
1099 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 if (Left.is(tok::l_paren))
1101 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001102 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001103 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1104 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001105 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001106 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1107 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001108 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001109 if (Left.is(tok::at) &&
1110 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001111 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001112 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1113 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001114 return true;
1115 }
1116
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001118 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001119 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1120 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001121 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001123 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001125 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1126 if (Tok.Type == TT_ObjCSelectorStart)
1127 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001128 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001129 // Don't space between ')' and <id>
1130 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001131 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001132 // Don't space between ':' and '('
1133 return false;
1134 }
Nico Webera2a84952013-01-10 21:30:42 +00001135 if (CurrentLineType == LT_ObjCProperty &&
1136 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1137 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001138
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001139 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001140 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 if (Tok.Type == TT_OverloadedOperator)
1142 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001143 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001144 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001145 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001146 if (Tok.is(tok::colon))
Nico Webera7252d82013-01-12 06:18:40 +00001147 return RootToken.isNot(tok::kw_case) && !Tok.Children.empty() &&
1148 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001149 if (Tok.Parent->Type == TT_UnaryOperator ||
1150 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001151 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001152 if (Tok.Type == TT_UnaryOperator)
1153 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001154 Tok.Parent->isNot(tok::l_square) &&
1155 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001156 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1157 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001158 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1159 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001160 if (Tok.Type == TT_DirectorySeparator ||
1161 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001162 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001163 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001164 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001165 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001166 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001167 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001168 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001169 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001170 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001171 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001172 }
1173
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001174 bool canBreakBefore(const AnnotatedToken &Right) {
1175 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001176 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001177 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1178 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001179 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001180 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1181 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001182 // Don't break this identifier as ':' or identifier
1183 // before it will break.
1184 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001185 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1186 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001187 // Don't break at ':' if identifier before it can beak.
1188 return false;
1189 }
Nico Webera7252d82013-01-12 06:18:40 +00001190 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1191 return false;
1192 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1193 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001194 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001195 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001196 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001197 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001198 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001199 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001200 return false;
1201
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001202 if (Right.is(tok::comment))
1203 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001204 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001205 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001206 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001207 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1208 Left.is(tok::comma) || Right.is(tok::lessless) ||
1209 Right.is(tok::arrow) || Right.is(tok::period) ||
1210 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001211 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001212 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001213 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1214 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001215 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001216 }
1217
Daniel Jasperf7935112012-12-03 18:12:45 +00001218 FormatStyle Style;
1219 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001220 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001221 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001222 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001223};
1224
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001225class LexerBasedFormatTokenSource : public FormatTokenSource {
1226public:
1227 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001228 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001229 IdentTable(Lex.getLangOpts()) {
1230 Lex.SetKeepWhitespaceMode(true);
1231 }
1232
1233 virtual FormatToken getNextToken() {
1234 if (GreaterStashed) {
1235 FormatTok.NewlinesBefore = 0;
1236 FormatTok.WhiteSpaceStart =
1237 FormatTok.Tok.getLocation().getLocWithOffset(1);
1238 FormatTok.WhiteSpaceLength = 0;
1239 GreaterStashed = false;
1240 return FormatTok;
1241 }
1242
1243 FormatTok = FormatToken();
1244 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001245 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001246 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001247 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1248 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001249
1250 // Consume and record whitespace until we find a significant token.
1251 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001252 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001253 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1254 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001255 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1256
1257 if (FormatTok.Tok.is(tok::eof))
1258 return FormatTok;
1259 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001260 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001261 }
Manuel Klimekef920692013-01-07 07:56:50 +00001262
1263 // Now FormatTok is the next non-whitespace token.
1264 FormatTok.TokenLength = Text.size();
1265
Manuel Klimek1abf7892013-01-04 23:34:14 +00001266 // In case the token starts with escaped newlines, we want to
1267 // take them into account as whitespace - this pattern is quite frequent
1268 // in macro definitions.
1269 // FIXME: What do we want to do with other escaped spaces, and escaped
1270 // spaces or newlines in the middle of tokens?
1271 // FIXME: Add a more explicit test.
1272 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001273 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001274 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001275 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001276 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001277 }
1278
1279 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001280 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001281 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001282 FormatTok.Tok.setKind(Info.getTokenID());
1283 }
1284
1285 if (FormatTok.Tok.is(tok::greatergreater)) {
1286 FormatTok.Tok.setKind(tok::greater);
1287 GreaterStashed = true;
1288 }
1289
1290 return FormatTok;
1291 }
1292
1293private:
1294 FormatToken FormatTok;
1295 bool GreaterStashed;
1296 Lexer &Lex;
1297 SourceManager &SourceMgr;
1298 IdentifierTable IdentTable;
1299
1300 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001301 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001302 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1303 Tok.getLength());
1304 }
1305};
1306
Daniel Jasperf7935112012-12-03 18:12:45 +00001307class Formatter : public UnwrappedLineConsumer {
1308public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001309 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1310 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001311 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001312 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001313 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001314
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001315 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001316
Daniel Jasperf7935112012-12-03 18:12:45 +00001317 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001318 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001319 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001320 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001321 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001322 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1323 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001324 I != E; ++I) {
1325 const UnwrappedLine &TheLine = *I;
1326 if (touchesRanges(TheLine)) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001327 llvm::OwningPtr<TokenAnnotator> AnnotatedLine(
1328 new TokenAnnotator(TheLine, Style, SourceMgr, Lex));
1329 if (!AnnotatedLine->annotate())
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001330 break;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001331 unsigned Indent = formatFirstToken(AnnotatedLine->getRootToken(),
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001332 TheLine.Level, TheLine.InPPDirective,
1333 PreviousEndOfLineColumn);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001334
1335 UnwrappedLine Line(TheLine);
1336 bool FitsOnALine = tryFitMultipleLinesInOne(Indent, Line, AnnotatedLine,
1337 I, E);
1338 UnwrappedLineFormatter Formatter(
1339 Style, SourceMgr, Line, Indent, FitsOnALine,
1340 AnnotatedLine->getLineType(), AnnotatedLine->getRootToken(),
1341 Replaces, StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001342 PreviousEndOfLineColumn = Formatter.format();
1343 } else {
1344 // If we did not reformat this unwrapped line, the column at the end of
1345 // the last token is unchanged - thus, we can calculate the end of the
1346 // last token, and return the result.
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001347 const FormatToken *Last = getLastInLine(TheLine);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001348 PreviousEndOfLineColumn =
1349 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1350 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1351 Lex.getLangOpts()) -
1352 1;
1353 }
1354 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001355 return Replaces;
1356 }
1357
1358private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001359 /// \brief Tries to merge lines into one.
1360 ///
1361 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1362 /// if possible; note that \c I will be incremented when lines are merged.
1363 ///
1364 /// Returns whether the resulting \c Line can fit in a single line.
1365 bool tryFitMultipleLinesInOne(unsigned Indent, UnwrappedLine &Line,
1366 llvm::OwningPtr<TokenAnnotator> &AnnotatedLine,
1367 std::vector<UnwrappedLine>::iterator &I,
1368 std::vector<UnwrappedLine>::iterator E) {
1369 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1370
1371 // Check whether the UnwrappedLine can be put onto a single line. If
1372 // so, this is bound to be the optimal solution (by definition) and we
1373 // don't need to analyze the entire solution space.
1374 bool FitsOnALine = fitsIntoLimit(AnnotatedLine->getRootToken(), Limit);
1375 if (!FitsOnALine || I + 1 == E || I + 2 == E)
1376 return FitsOnALine;
1377
1378 // Try to merge the next two lines if possible.
1379 UnwrappedLine Combined(Line);
1380
1381 // First, check that the current line allows merging. This is the case if
1382 // we're not in a control flow statement and the last token is an opening
1383 // brace.
1384 FormatToken *Last = &Combined.RootToken;
1385 bool AllowedTokens =
Manuel Klimek2acb7b72013-01-11 19:17:44 +00001386 Last->Tok.isNot(tok::kw_if) && Last->Tok.isNot(tok::kw_while) &&
1387 Last->Tok.isNot(tok::kw_do) && Last->Tok.isNot(tok::r_brace) &&
1388 Last->Tok.isNot(tok::kw_else) && Last->Tok.isNot(tok::kw_try) &&
1389 Last->Tok.isNot(tok::kw_catch) && Last->Tok.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001390 // This gets rid of all ObjC @ keywords and methods.
1391 Last->Tok.isNot(tok::at) && Last->Tok.isNot(tok::minus) &&
1392 Last->Tok.isNot(tok::plus);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001393 while (!Last->Children.empty())
1394 Last = &Last->Children.back();
1395 if (!Last->Tok.is(tok::l_brace))
1396 return FitsOnALine;
1397
1398 // Second, check that the next line does not contain any braces - if it
1399 // does, readability declines when putting it into a single line.
1400 const FormatToken *Next = &(I + 1)->RootToken;
1401 while (Next) {
1402 AllowedTokens = AllowedTokens && !Next->Tok.is(tok::l_brace) &&
1403 !Next->Tok.is(tok::r_brace);
1404 Last->Children.push_back(*Next);
1405 Last = &Last->Children[0];
1406 Last->Children.clear();
1407 Next = Next->Children.empty() ? NULL : &Next->Children.back();
1408 }
1409
1410 // Last, check that the third line contains a single closing brace.
1411 Next = &(I + 2)->RootToken;
1412 AllowedTokens = AllowedTokens && Next->Tok.is(tok::r_brace);
1413 if (!Next->Children.empty() || !AllowedTokens)
1414 return FitsOnALine;
1415 Last->Children.push_back(*Next);
1416
1417 llvm::OwningPtr<TokenAnnotator> CombinedAnnotator(
1418 new TokenAnnotator(Combined, Style, SourceMgr, Lex));
1419 if (CombinedAnnotator->annotate() &&
1420 fitsIntoLimit(CombinedAnnotator->getRootToken(), Limit)) {
1421 // If the merged line fits, we use that instead and skip the next two
1422 // lines.
1423 AnnotatedLine.reset(CombinedAnnotator.take());
1424 Line = Combined;
1425 I += 2;
1426 }
1427 return FitsOnALine;
1428 }
1429
1430 const FormatToken *getLastInLine(const UnwrappedLine &TheLine) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001431 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001432 while (!Last->Children.empty())
1433 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001434 return Last;
1435 }
1436
1437 bool touchesRanges(const UnwrappedLine &TheLine) {
1438 const FormatToken *First = &TheLine.RootToken;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001439 const FormatToken *Last = getLastInLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001440 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001441 First->Tok.getLocation(),
1442 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001443 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001444 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1445 Ranges[i].getBegin()) &&
1446 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1447 LineRange.getBegin()))
1448 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001449 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001450 return false;
1451 }
1452
1453 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1454 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001455 }
1456
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001457 /// \brief Add a new line and the required indent before the first Token
1458 /// of the \c UnwrappedLine if there was no structural parsing error.
1459 /// Returns the indent level of the \c UnwrappedLine.
1460 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1461 bool InPPDirective,
1462 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001463 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001464 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1465 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1466
1467 unsigned Newlines = std::min(Tok.NewlinesBefore,
1468 Style.MaxEmptyLinesToKeep + 1);
1469 if (Newlines == 0 && !Tok.IsFirst)
1470 Newlines = 1;
1471 unsigned Indent = Level * 2;
1472
1473 bool IsAccessModifier = false;
1474 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1475 RootToken.is(tok::kw_private))
1476 IsAccessModifier = true;
1477 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1478 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1479 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1480 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1481 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1482 IsAccessModifier = true;
1483
1484 if (IsAccessModifier &&
1485 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1486 Indent += Style.AccessModifierOffset;
1487 if (!InPPDirective || Tok.HasUnescapedNewline) {
1488 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1489 } else {
1490 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1491 SourceMgr, Replaces);
1492 }
1493 return Indent;
1494 }
1495
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001496 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001497 FormatStyle Style;
1498 Lexer &Lex;
1499 SourceManager &SourceMgr;
1500 tooling::Replacements Replaces;
1501 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001502 std::vector<UnwrappedLine> UnwrappedLines;
1503 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001504};
1505
1506tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1507 SourceManager &SourceMgr,
1508 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001509 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1510 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1511 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1512 DiagnosticsEngine Diagnostics(
1513 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1514 &DiagnosticPrinter, false);
1515 Diagnostics.setSourceManager(&SourceMgr);
1516 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001517 return formatter.format();
1518}
1519
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001520LangOptions getFormattingLangOpts() {
1521 LangOptions LangOpts;
1522 LangOpts.CPlusPlus = 1;
1523 LangOpts.CPlusPlus11 = 1;
1524 LangOpts.Bool = 1;
1525 LangOpts.ObjC1 = 1;
1526 LangOpts.ObjC2 = 1;
1527 return LangOpts;
1528}
1529
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001530} // namespace format
1531} // namespace clang