blob: f84d3c5bc7a68b5cc4dcd1782f4fb84a980a7e00 [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperbac016b2012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasper71607512013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasper71607512013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Weber70848232013-01-10 21:30:42 +000042 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000043 TT_OverloadedOperator,
44 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000045 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000046 TT_TemplateCloser,
47 TT_TemplateOpener,
48 TT_TrailingUnaryOperator,
49 TT_UnaryOperator,
50 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000051};
52
53enum LineType {
54 LT_Invalid,
55 LT_Other,
56 LT_PreprocessorDirective,
57 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000058 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000059 LT_ObjCMethodDecl,
60 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000061};
62
Daniel Jasper26f7e782013-01-08 14:56:18 +000063class AnnotatedToken {
64public:
65 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000066 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
67 CanBreakBefore(false), MustBreakBefore(false),
68 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000069
70 bool is(tok::TokenKind Kind) const {
71 return FormatTok.Tok.is(Kind);
72 }
73 bool isNot(tok::TokenKind Kind) const {
74 return FormatTok.Tok.isNot(Kind);
75 }
76 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
77 return FormatTok.Tok.isObjCAtKeyword(Kind);
78 }
79
80 FormatToken FormatTok;
81
Daniel Jasperbac016b2012-12-03 18:12:45 +000082 TokenType Type;
83
Daniel Jasperbac016b2012-12-03 18:12:45 +000084 bool SpaceRequiredBefore;
85 bool CanBreakBefore;
86 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000087
88 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000089
90 std::vector<AnnotatedToken> Children;
91 AnnotatedToken *Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +000092};
93
Daniel Jasper26f7e782013-01-08 14:56:18 +000094static prec::Level getPrecedence(const AnnotatedToken &Tok) {
95 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +000096}
97
Daniel Jasperbac016b2012-12-03 18:12:45 +000098using llvm::MutableArrayRef;
99
100FormatStyle 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 Kornienko15757312012-12-06 18:03:27 +0000107 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000108 LLVMStyle.SpacesBeforeTrailingComments = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000109 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000110 return LLVMStyle;
111}
112
113FormatStyle getGoogleStyle() {
114 FormatStyle GoogleStyle;
115 GoogleStyle.ColumnLimit = 80;
116 GoogleStyle.MaxEmptyLinesToKeep = 1;
117 GoogleStyle.PointerAndReferenceBindToType = true;
118 GoogleStyle.AccessModifierOffset = -1;
119 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000120 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000121 GoogleStyle.SpacesBeforeTrailingComments = 2;
Nico Weber5f500df2013-01-10 20:12:55 +0000122 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000123 return GoogleStyle;
124}
125
126struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000127 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000128 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000129 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000130};
131
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000132/// \brief Replaces the whitespace in front of \p Tok. Only call once for
133/// each \c FormatToken.
134static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
135 unsigned Spaces, const FormatStyle &Style,
136 SourceManager &SourceMgr,
137 tooling::Replacements &Replaces) {
138 Replaces.insert(tooling::Replacement(
139 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
140 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
141}
142
143/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
144/// backslashes to escape newlines inside a preprocessor directive.
145///
146/// This function and \c replaceWhitespace have the same behavior if
147/// \c Newlines == 0.
148static void replacePPWhitespace(
149 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
150 unsigned WhitespaceStartColumn, const FormatStyle &Style,
151 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
152 std::string NewLineText;
153 if (NewLines > 0) {
154 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
155 WhitespaceStartColumn);
156 for (unsigned i = 0; i < NewLines; ++i) {
157 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
158 NewLineText += "\\\n";
159 Offset = 0;
160 }
161 }
162 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
163 Tok.FormatTok.WhiteSpaceLength,
164 NewLineText + std::string(Spaces, ' ')));
165}
166
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167class UnwrappedLineFormatter {
168public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000169 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
170 const UnwrappedLine &Line, unsigned FirstIndent,
171 bool FitsOnALine, LineType CurrentLineType,
172 const AnnotatedToken &RootToken,
173 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000174 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000175 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper26f7e782013-01-08 14:56:18 +0000176 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000177 Replaces(Replaces) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000178 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000179 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000180 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000181 }
182
Manuel Klimekd4397b92013-01-04 23:34:14 +0000183 /// \brief Formats an \c UnwrappedLine.
184 ///
185 /// \returns The column after the last token in the last line of the
186 /// \c UnwrappedLine.
187 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000188 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000189 IndentState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000190 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000191 State.NextToken = &RootToken;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000192 State.Indent.push_back(FirstIndent + 4);
193 State.LastSpace.push_back(FirstIndent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000194 State.FirstLessLess.push_back(0);
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000195 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000196 State.ForLoopVariablePos = 0;
197 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000198 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000199
200 // The first token has already been indented and thus consumed.
201 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000202
203 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000204 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000205 if (FitsOnALine) {
206 addTokenToState(false, false, State);
207 } else {
208 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
209 unsigned Break = calcPenalty(State, true, NoBreak);
210 addTokenToState(Break < NoBreak, false, State);
211 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000213 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000214 }
215
216private:
217 /// \brief The current state when indenting a unwrapped line.
218 ///
219 /// As the indenting tries different combinations this is copied by value.
220 struct IndentState {
221 /// \brief The number of used columns in the current line.
222 unsigned Column;
223
Daniel Jasper26f7e782013-01-08 14:56:18 +0000224 const AnnotatedToken *NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000225
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000226 /// \brief The parenthesis level of the first token on the current line.
227 unsigned StartOfLineLevel;
228
Daniel Jasperbac016b2012-12-03 18:12:45 +0000229 /// \brief The position to which a specific parenthesis level needs to be
230 /// indented.
231 std::vector<unsigned> Indent;
232
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000233 /// \brief The position of the last space on each level.
234 ///
235 /// Used e.g. to break like:
236 /// functionCall(Parameter, otherCall(
237 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000238 std::vector<unsigned> LastSpace;
239
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000240 /// \brief The position the first "<<" operator encountered on each level.
241 ///
242 /// Used to align "<<" operators. 0 if no such operator has been encountered
243 /// on a level.
244 std::vector<unsigned> FirstLessLess;
245
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000246 /// \brief Whether a newline needs to be inserted before the block's closing
247 /// brace.
248 ///
249 /// We only want to insert a newline before the closing brace if there also
250 /// was a newline after the beginning left brace.
251 std::vector<bool> BreakBeforeClosingBrace;
252
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000253 /// \brief The column of the first variable in a for-loop declaration.
254 ///
255 /// Used to align the second variable if necessary.
256 unsigned ForLoopVariablePos;
257
258 /// \brief \c true if this line contains a continued for-loop section.
259 bool LineContainsContinuedForLoopSection;
260
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261 /// \brief Comparison operator to be able to used \c IndentState in \c map.
262 bool operator<(const IndentState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000263 if (Other.NextToken != NextToken)
264 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000265 if (Other.Column != Column)
266 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000267 if (Other.StartOfLineLevel != StartOfLineLevel)
268 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269 if (Other.Indent.size() != Indent.size())
270 return Other.Indent.size() > Indent.size();
271 for (int i = 0, e = Indent.size(); i != e; ++i) {
272 if (Other.Indent[i] != Indent[i])
273 return Other.Indent[i] > Indent[i];
274 }
275 if (Other.LastSpace.size() != LastSpace.size())
276 return Other.LastSpace.size() > LastSpace.size();
277 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
278 if (Other.LastSpace[i] != LastSpace[i])
279 return Other.LastSpace[i] > LastSpace[i];
280 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000281 if (Other.FirstLessLess.size() != FirstLessLess.size())
282 return Other.FirstLessLess.size() > FirstLessLess.size();
283 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
284 if (Other.FirstLessLess[i] != FirstLessLess[i])
285 return Other.FirstLessLess[i] > FirstLessLess[i];
286 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000287 if (Other.ForLoopVariablePos != ForLoopVariablePos)
288 return Other.ForLoopVariablePos < ForLoopVariablePos;
289 if (Other.LineContainsContinuedForLoopSection !=
290 LineContainsContinuedForLoopSection)
291 return LineContainsContinuedForLoopSection;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000292 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
293 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000294 return false;
295 }
296 };
297
Daniel Jasper20409152012-12-04 14:54:30 +0000298 /// \brief Appends the next token to \p State and updates information
299 /// necessary for indentation.
300 ///
301 /// Puts the token on the current line if \p Newline is \c true and adds a
302 /// line break and necessary indentation otherwise.
303 ///
304 /// If \p DryRun is \c false, also creates and stores the required
305 /// \c Replacement.
306 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000307 const AnnotatedToken &Current = *State.NextToken;
308 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weberb530fa32013-01-10 00:25:19 +0000309 assert(State.Indent.size());
Daniel Jasper20409152012-12-04 14:54:30 +0000310 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311
312 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000313 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000314 if (Current.is(tok::r_brace)) {
315 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000316 } else if (Current.is(tok::string_literal) &&
317 Previous.is(tok::string_literal)) {
318 State.Column = State.Column - Previous.FormatTok.TokenLength;
319 } else if (Current.is(tok::lessless) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000320 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000321 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000322 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000323 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
324 Current.is(tok::period) || Previous.is(tok::question) ||
325 Previous.Type == TT_ConditionalExpr)) {
326 // Indent and extra 4 spaces after if we know the current expression is
327 // continued. Don't do that on the top level, as we already indent 4
328 // there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000330 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000331 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000332 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000333 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000334 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000335 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000336 }
337
Manuel Klimek2851c162013-01-10 14:36:46 +0000338 // A line starting with a closing brace is assumed to be correct for the
339 // same level as before the opening brace.
340 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000341
Daniel Jasper26f7e782013-01-08 14:56:18 +0000342 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000343 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000344
Manuel Klimek060143e2013-01-02 18:33:23 +0000345 if (!DryRun) {
346 if (!Line.InPPDirective)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000347 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
348 SourceMgr, Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000349 else
Daniel Jasper9c837d02013-01-09 07:06:56 +0000350 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000351 WhitespaceStartColumn, Style, SourceMgr,
352 Replaces);
Manuel Klimek060143e2013-01-02 18:33:23 +0000353 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000354
Daniel Jasperd64f7382013-01-09 09:50:48 +0000355 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000356 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper26f7e782013-01-08 14:56:18 +0000357 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000358 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000359 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000360 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
361 State.ForLoopVariablePos = State.Column -
362 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000363
Daniel Jasper26f7e782013-01-08 14:56:18 +0000364 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
365 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000366 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000367
Daniel Jasperbac016b2012-12-03 18:12:45 +0000368 if (!DryRun)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000369 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000370
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000371 // FIXME: Do we need to do this for assignments nested in other
372 // expressions?
373 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000374 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000375 Previous.is(tok::kw_return)))
Daniel Jaspercf225b62012-12-24 13:43:52 +0000376 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000377 if (Previous.is(tok::l_paren) ||
Manuel Klimek2851c162013-01-10 14:36:46 +0000378 Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000379 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000380 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000381
Daniel Jasper9cda8002013-01-07 13:08:40 +0000382 // Top-level spaces that are not part of assignments are exempt as that
383 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000384 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000385 if (Spaces > 0 &&
386 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000387 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000388 }
Daniel Jasper20409152012-12-04 14:54:30 +0000389 moveStateToNextToken(State);
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000390 if (Newline && Previous.is(tok::l_brace)) {
391 State.BreakBeforeClosingBrace.back() = true;
392 }
Daniel Jasper20409152012-12-04 14:54:30 +0000393 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000394
Daniel Jasper20409152012-12-04 14:54:30 +0000395 /// \brief Mark the next token as consumed in \p State and modify its stacks
396 /// accordingly.
397 void moveStateToNextToken(IndentState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000398 const AnnotatedToken &Current = *State.NextToken;
Nico Weberb530fa32013-01-10 00:25:19 +0000399 assert(State.Indent.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000400 unsigned ParenLevel = State.Indent.size() - 1;
401
Daniel Jasper26f7e782013-01-08 14:56:18 +0000402 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000403 State.FirstLessLess[ParenLevel] = State.Column;
404
Daniel Jaspercf225b62012-12-24 13:43:52 +0000405 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000406 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000407 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
408 Current.is(tok::l_brace) ||
409 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek2851c162013-01-10 14:36:46 +0000410 if (Current.is(tok::l_brace)) {
411 // FIXME: This does not work with nested static initializers.
412 // Implement a better handling for static initializers and similar
413 // constructs.
414 State.Indent.push_back(Line.Level * 2 + 2);
415 } else {
416 State.Indent.push_back(4 + State.LastSpace.back());
417 }
Daniel Jasper20409152012-12-04 14:54:30 +0000418 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000419 State.FirstLessLess.push_back(0);
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000420 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper20409152012-12-04 14:54:30 +0000421 }
422
Daniel Jaspercf225b62012-12-24 13:43:52 +0000423 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000424 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000425 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
426 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
427 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 State.Indent.pop_back();
429 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000430 State.FirstLessLess.pop_back();
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000431 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000432 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000433
Daniel Jasper26f7e782013-01-08 14:56:18 +0000434 if (State.NextToken->Children.empty())
435 State.NextToken = NULL;
436 else
437 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000438
439 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000440 }
441
Nico Weberdecf7bc2013-01-07 15:15:29 +0000442 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000443 unsigned splitPenalty(const AnnotatedToken &Tok) {
444 const AnnotatedToken &Left = Tok;
445 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000446
447 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000448 if (RootToken.is(tok::kw_for) &&
449 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000450 return 20;
451
Daniel Jasper26f7e782013-01-08 14:56:18 +0000452 if (Left.is(tok::semi) || Left.is(tok::comma) ||
453 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000454 return 0;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000455 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000456 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000457
Daniel Jasper9c837d02013-01-09 07:06:56 +0000458 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
459 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000460 prec::Level Level = getPrecedence(Left);
461
462 // Breaking after an assignment leads to a bad result as the two sides of
463 // the assignment are visually very close together.
464 if (Level == prec::Assignment)
465 return 50;
466
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000467 if (Level != prec::Unknown)
468 return Level;
469
Daniel Jasper26f7e782013-01-08 14:56:18 +0000470 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000471 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000472
Daniel Jasperbac016b2012-12-03 18:12:45 +0000473 return 3;
474 }
475
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000476 unsigned getColumnLimit() {
477 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
478 }
479
Daniel Jasperbac016b2012-12-03 18:12:45 +0000480 /// \brief Calculate the number of lines needed to format the remaining part
481 /// of the unwrapped line.
482 ///
483 /// Assumes the formatting so far has led to
484 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
485 /// added after the previous token.
486 ///
487 /// \param StopAt is used for optimization. If we can determine that we'll
488 /// definitely need at least \p StopAt additional lines, we already know of a
489 /// better solution.
490 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
491 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000492 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000493 return 0;
494
Daniel Jasper26f7e782013-01-08 14:56:18 +0000495 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000496 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000497 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000498 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000499 if (!NewLine && State.NextToken->is(tok::r_brace) &&
500 State.BreakBeforeClosingBrace.back())
501 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000502 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000503 State.LineContainsContinuedForLoopSection)
504 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000505
Daniel Jasper33182dd2012-12-05 14:57:28 +0000506 unsigned CurrentPenalty = 0;
507 if (NewLine) {
508 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000509 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000510 } else {
511 if (State.Indent.size() < State.StartOfLineLevel)
512 CurrentPenalty += Parameters.PenaltyLevelDecrease *
513 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000514 }
515
Daniel Jasper20409152012-12-04 14:54:30 +0000516 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000517
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000518 // Exceeding column limit is bad, assign penalty.
519 if (State.Column > getColumnLimit()) {
520 unsigned ExcessCharacters = State.Column - getColumnLimit();
521 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
522 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523
Daniel Jasperbac016b2012-12-03 18:12:45 +0000524 if (StopAt <= CurrentPenalty)
525 return UINT_MAX;
526 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000527 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000528 if (I != Memory.end()) {
529 // If this state has already been examined, we can safely return the
530 // previous result if we
531 // - have not hit the optimatization (and thus returned UINT_MAX) OR
532 // - are now computing for a smaller or equal StopAt.
533 unsigned SavedResult = I->second.first;
534 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000535 if (SavedResult != UINT_MAX)
536 return SavedResult + CurrentPenalty;
537 else if (StopAt <= SavedStopAt)
538 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000539 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000540
541 unsigned NoBreak = calcPenalty(State, false, StopAt);
542 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
543 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000544
545 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
546 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000547 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000548
549 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000550 }
551
Daniel Jasperbac016b2012-12-03 18:12:45 +0000552 FormatStyle Style;
553 SourceManager &SourceMgr;
554 const UnwrappedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000555 const unsigned FirstIndent;
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000556 const bool FitsOnALine;
Daniel Jasper71607512013-01-07 10:48:50 +0000557 const LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000558 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000559 tooling::Replacements &Replaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560
Daniel Jasper33182dd2012-12-05 14:57:28 +0000561 // A map from an indent state to a pair (Result, Used-StopAt).
562 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
563 StateMap Memory;
564
Daniel Jasperbac016b2012-12-03 18:12:45 +0000565 OptimizationParameters Parameters;
566};
567
568/// \brief Determines extra information about the tokens comprising an
569/// \c UnwrappedLine.
570class TokenAnnotator {
571public:
572 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000573 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper26f7e782013-01-08 14:56:18 +0000574 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
575 RootToken(Line.RootToken) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000576 }
577
578 /// \brief A parser that gathers additional information about tokens.
579 ///
580 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
581 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
582 /// into template parameter lists.
583 class AnnotatingParser {
584 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000585 AnnotatingParser(AnnotatedToken &RootToken)
586 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000587 }
588
Daniel Jasper20409152012-12-04 14:54:30 +0000589 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000590 while (CurrentToken != NULL) {
591 if (CurrentToken->is(tok::greater)) {
592 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000593 next();
594 return true;
595 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000596 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
597 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000598 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000599 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
600 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000602 if (!consumeToken())
603 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000604 }
605 return false;
606 }
607
Daniel Jasper20409152012-12-04 14:54:30 +0000608 bool parseParens() {
Daniel Jasper46ef8522013-01-10 13:08:12 +0000609 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
610 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000611 while (CurrentToken != NULL) {
612 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000613 next();
614 return true;
615 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000616 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000617 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000618 if (!consumeToken())
619 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000620 }
621 return false;
622 }
623
Daniel Jasper20409152012-12-04 14:54:30 +0000624 bool parseSquare() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000625 while (CurrentToken != NULL) {
626 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 next();
628 return true;
629 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000630 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000631 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000632 if (!consumeToken())
633 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 }
635 return false;
636 }
637
Daniel Jasper700e7102013-01-10 09:26:47 +0000638 bool parseBrace() {
639 while (CurrentToken != NULL) {
640 if (CurrentToken->is(tok::r_brace)) {
641 next();
642 return true;
643 }
644 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
645 return false;
646 if (!consumeToken())
647 return false;
648 }
649 // Lines can currently end with '{'.
650 return true;
651 }
652
Daniel Jasper20409152012-12-04 14:54:30 +0000653 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000654 while (CurrentToken != NULL) {
655 if (CurrentToken->is(tok::colon)) {
656 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000657 next();
658 return true;
659 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000660 if (!consumeToken())
661 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000662 }
663 return false;
664 }
665
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000666 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000667 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
668 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000669 next();
670 if (!parseAngle())
671 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000672 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000673 parseLine();
674 return true;
675 }
676 return false;
677 }
678
Daniel Jasper1f42f112013-01-04 18:52:56 +0000679 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000680 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000681 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000682 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000683 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000684 if (!parseParens())
685 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000686 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
687 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000688 next();
689 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000690 break;
691 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000692 if (!parseSquare())
693 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000694 break;
Daniel Jasper700e7102013-01-10 09:26:47 +0000695 case tok::l_brace:
696 if (!parseBrace())
697 return false;
698 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000699 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000700 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000701 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000702 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000703 Tok->Type = TT_BinaryOperator;
704 CurrentToken = Tok;
705 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000706 }
707 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000708 case tok::r_paren:
709 case tok::r_square:
710 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +0000711 case tok::r_brace:
712 // Lines can start with '}'.
713 if (Tok->Parent != NULL)
714 return false;
715 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000716 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000717 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000718 break;
719 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000720 if (CurrentToken->is(tok::l_paren)) {
721 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000722 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000723 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
724 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000725 next();
726 }
727 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000728 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
729 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000730 next();
731 }
732 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000733 break;
734 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000735 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000736 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000737 case tok::kw_template:
738 parseTemplateDeclaration();
739 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000740 default:
741 break;
742 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000743 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000744 }
745
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000746 void parseIncludeDirective() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000747 while (CurrentToken != NULL) {
748 if (CurrentToken->is(tok::slash))
749 CurrentToken->Type = TT_DirectorySeparator;
750 else if (CurrentToken->is(tok::less))
751 CurrentToken->Type = TT_TemplateOpener;
752 else if (CurrentToken->is(tok::greater))
753 CurrentToken->Type = TT_TemplateCloser;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000754 next();
755 }
756 }
757
758 void parsePreprocessorDirective() {
759 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000760 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000761 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000762 // Hashes in the middle of a line can lead to any strange token
763 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000764 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000765 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000766 switch (
767 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000768 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000769 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000770 parseIncludeDirective();
771 break;
772 default:
773 break;
774 }
775 }
776
Daniel Jasper71607512013-01-07 10:48:50 +0000777 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000778 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000779 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000780 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000781 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000782 while (CurrentToken != NULL) {
783 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000784 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000785 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000786 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000787 }
Daniel Jasper71607512013-01-07 10:48:50 +0000788 if (KeywordVirtualFound)
789 return LT_VirtualFunctionDecl;
790 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000791 }
792
793 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000794 if (CurrentToken != NULL && !CurrentToken->Children.empty())
795 CurrentToken = &CurrentToken->Children[0];
796 else
797 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000798 }
799
800 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000801 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000802 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 };
804
Daniel Jasper26f7e782013-01-08 14:56:18 +0000805 void createAnnotatedTokens(AnnotatedToken &Current) {
806 if (!Current.FormatTok.Children.empty()) {
807 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
808 Current.Children.back().Parent = &Current;
809 createAnnotatedTokens(Current.Children.back());
810 }
811 }
Daniel Jasper71607512013-01-07 10:48:50 +0000812
Daniel Jasper26f7e782013-01-08 14:56:18 +0000813 void calculateExtraInformation(AnnotatedToken &Current) {
814 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
815
Manuel Klimek526ed112013-01-09 15:25:02 +0000816 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000817 Current.MustBreakBefore = true;
818 } else {
Manuel Klimek526ed112013-01-09 15:25:02 +0000819 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
820 TT_LineComment || (Current.is(tok::string_literal) &&
821 Current.Parent->is(tok::string_literal))) {
822 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +0000823 } else {
824 Current.MustBreakBefore = false;
825 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000826 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000827 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000828 if (!Current.Children.empty())
829 calculateExtraInformation(Current.Children[0]);
830 }
831
832 bool annotate() {
833 createAnnotatedTokens(RootToken);
834
835 AnnotatingParser Parser(RootToken);
Daniel Jasper71607512013-01-07 10:48:50 +0000836 CurrentLineType = Parser.parseLine();
837 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000838 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000839
Daniel Jasper26f7e782013-01-08 14:56:18 +0000840 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000841
Daniel Jasper26f7e782013-01-08 14:56:18 +0000842 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasper71607512013-01-07 10:48:50 +0000843 CurrentLineType = LT_ObjCMethodDecl;
Nico Webered91bba2013-01-10 19:19:14 +0000844 else if (RootToken.Type == TT_ObjCDecl)
845 CurrentLineType = LT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +0000846 else if (RootToken.Type == TT_ObjCProperty)
847 CurrentLineType = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +0000848
Daniel Jasper26f7e782013-01-08 14:56:18 +0000849 if (!RootToken.Children.empty())
850 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000851 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000852 }
853
Daniel Jasper71607512013-01-07 10:48:50 +0000854 LineType getLineType() {
855 return CurrentLineType;
856 }
857
Daniel Jasper26f7e782013-01-08 14:56:18 +0000858 const AnnotatedToken &getRootToken() {
859 return RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000860 }
861
862private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000863 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
864 if (getPrecedence(Current) == prec::Assignment ||
865 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
866 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000867
Daniel Jasper26f7e782013-01-08 14:56:18 +0000868 if (Current.Type == TT_Unknown) {
869 if (Current.is(tok::star) || Current.is(tok::amp)) {
870 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +0000871 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
872 Current.is(tok::caret)) {
873 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000874 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
875 Current.Type = determineIncrementUsage(Current);
876 } else if (Current.is(tok::exclaim)) {
877 Current.Type = TT_UnaryOperator;
878 } else if (isBinaryOperator(Current)) {
879 Current.Type = TT_BinaryOperator;
880 } else if (Current.is(tok::comment)) {
881 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
882 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +0000883 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000884 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000885 else
Daniel Jasper26f7e782013-01-08 14:56:18 +0000886 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +0000887 } else if (Current.is(tok::r_paren) &&
888 (Current.Parent->Type == TT_PointerOrReference ||
889 Current.Parent->Type == TT_TemplateCloser)) {
890 // FIXME: We need to get smarter and understand more cases of casts.
891 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +0000892 } else if (Current.is(tok::at) && Current.Children.size()) {
893 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
894 case tok::objc_interface:
895 case tok::objc_implementation:
896 case tok::objc_protocol:
897 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +0000898 break;
899 case tok::objc_property:
900 Current.Type = TT_ObjCProperty;
901 break;
Nico Webered91bba2013-01-10 19:19:14 +0000902 default:
903 break;
904 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000905 }
906 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000907
908 if (!Current.Children.empty())
909 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000910 }
911
Daniel Jasper26f7e782013-01-08 14:56:18 +0000912 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000913 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000914 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000915 }
916
Daniel Jasper26f7e782013-01-08 14:56:18 +0000917 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
918 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000919 return TT_UnaryOperator;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000920 if (Tok.Children.size() == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000921 return TT_Unknown;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000922 const FormatToken &PrevToken = Tok.Parent->FormatTok;
923 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000924
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000925 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
926 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper5cf7cf32013-01-10 11:14:08 +0000927 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
928 Tok.Parent->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +0000929 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000930
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000931 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000932 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
933 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
934 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
935 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000936 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000937
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000938 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
939 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000940 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000941
Daniel Jasper112fb272012-12-05 07:51:39 +0000942 // It is very unlikely that we are going to find a pointer or reference type
943 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000944 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000945 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000946
Daniel Jasper71607512013-01-07 10:48:50 +0000947 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000948 }
949
Daniel Jasper886568d2013-01-09 08:36:49 +0000950 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000951 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000952 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000953 return TT_ObjCMethodSpecifier;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000954
955 // Use heuristics to recognize unary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000956 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
957 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
958 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Weber81ed2f12013-01-10 19:36:35 +0000959 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
960 Tok.Parent->is(tok::at))
Daniel Jasper71607512013-01-07 10:48:50 +0000961 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000962
963 // There can't be to consecutive binary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000964 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +0000965 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000966
967 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +0000968 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000969 }
970
971 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000972 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
973 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +0000974 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000975
Daniel Jasper71607512013-01-07 10:48:50 +0000976 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000977 }
978
Daniel Jasper26f7e782013-01-08 14:56:18 +0000979 bool spaceRequiredBetween(const AnnotatedToken &Left,
980 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +0000981 if (Right.is(tok::hashhash))
982 return Left.is(tok::hash);
983 if (Left.is(tok::hashhash) || Left.is(tok::hash))
984 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +0000985 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
986 return false;
Nico Weber5f500df2013-01-10 20:12:55 +0000987 if (Right.is(tok::less) &&
988 (Left.is(tok::kw_template) ||
989 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000990 return true;
991 if (Left.is(tok::arrow) || Right.is(tok::arrow))
992 return false;
993 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
994 return false;
Nico Webercb4d6902013-01-08 19:40:21 +0000995 if (Left.is(tok::at) &&
996 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
997 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +0000998 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
999 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001000 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001001 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1002 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001003 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001004 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001005 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1006 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001007 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001008 return Right.FormatTok.Tok.isLiteral() ||
1009 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001010 if (Right.is(tok::star) && Left.is(tok::l_paren))
1011 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001012 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1013 Right.is(tok::r_square))
1014 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001015 if (Left.is(tok::coloncolon) ||
1016 (Right.is(tok::coloncolon) &&
1017 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001018 return false;
1019 if (Left.is(tok::period) || Right.is(tok::period))
1020 return false;
1021 if (Left.is(tok::colon) || Right.is(tok::colon))
1022 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001023 if (Left.is(tok::l_paren))
1024 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001025 if (Right.is(tok::l_paren)) {
Nico Webered91bba2013-01-10 19:19:14 +00001026 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1027 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1028 Left.is(tok::kw_switch) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001029 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001030 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001031 if (Left.is(tok::at) &&
1032 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001033 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001034 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1035 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001036 return true;
1037 }
1038
Daniel Jasper26f7e782013-01-08 14:56:18 +00001039 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperda927712013-01-07 15:36:15 +00001040 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001041 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1042 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001043 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001044 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001045 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001046 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperda927712013-01-07 15:36:15 +00001047 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001048 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001049 // Don't space between ')' and <id>
1050 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001051 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001052 // Don't space between ':' and '('
1053 return false;
1054 }
Nico Weber70848232013-01-10 21:30:42 +00001055 if (CurrentLineType == LT_ObjCProperty &&
1056 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1057 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001058
Daniel Jasper46ef8522013-01-10 13:08:12 +00001059 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001060 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001061 if (Tok.Type == TT_OverloadedOperator)
1062 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001063 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001064 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001065 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001066 if (Tok.is(tok::colon))
1067 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001068 if (Tok.Parent->Type == TT_UnaryOperator ||
1069 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001070 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001071 if (Tok.Type == TT_UnaryOperator)
1072 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber81ed2f12013-01-10 19:36:35 +00001073 Tok.Parent->isNot(tok::l_square) &&
1074 Tok.Parent->isNot(tok::at);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001075 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1076 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001077 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1078 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001079 if (Tok.Type == TT_DirectorySeparator ||
1080 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperda927712013-01-07 15:36:15 +00001081 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001082 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001083 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001084 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001085 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001086 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001087 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001088 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001089 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001090 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001091 }
1092
Daniel Jasper26f7e782013-01-08 14:56:18 +00001093 bool canBreakBefore(const AnnotatedToken &Right) {
1094 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperda927712013-01-07 15:36:15 +00001095 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001096 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1097 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001098 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001099 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1100 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001101 // Don't break this identifier as ':' or identifier
1102 // before it will break.
1103 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001104 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1105 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001106 // Don't break at ':' if identifier before it can beak.
1107 return false;
1108 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001109 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001110 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001111 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001112 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001113 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001114 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001115 return false;
1116
Daniel Jasper043835a2013-01-09 09:33:39 +00001117 if (Right.is(tok::comment))
1118 return !Right.Children.empty();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001119 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasper043835a2013-01-09 09:33:39 +00001120 Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001121 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001122 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1123 Left.is(tok::comma) || Right.is(tok::lessless) ||
1124 Right.is(tok::arrow) || Right.is(tok::period) ||
1125 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper9c837d02013-01-09 07:06:56 +00001126 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimekc8c8a472013-01-10 15:58:26 +00001127 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001128 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001129 }
1130
Daniel Jasperbac016b2012-12-03 18:12:45 +00001131 FormatStyle Style;
1132 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001133 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001134 LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001135 AnnotatedToken RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001136};
1137
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001138class LexerBasedFormatTokenSource : public FormatTokenSource {
1139public:
1140 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001141 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001142 IdentTable(Lex.getLangOpts()) {
1143 Lex.SetKeepWhitespaceMode(true);
1144 }
1145
1146 virtual FormatToken getNextToken() {
1147 if (GreaterStashed) {
1148 FormatTok.NewlinesBefore = 0;
1149 FormatTok.WhiteSpaceStart =
1150 FormatTok.Tok.getLocation().getLocWithOffset(1);
1151 FormatTok.WhiteSpaceLength = 0;
1152 GreaterStashed = false;
1153 return FormatTok;
1154 }
1155
1156 FormatTok = FormatToken();
1157 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001158 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001159 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001160 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1161 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001162
1163 // Consume and record whitespace until we find a significant token.
1164 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001165 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001166 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1167 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001168 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1169
1170 if (FormatTok.Tok.is(tok::eof))
1171 return FormatTok;
1172 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001173 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001174 }
Manuel Klimek95419382013-01-07 07:56:50 +00001175
1176 // Now FormatTok is the next non-whitespace token.
1177 FormatTok.TokenLength = Text.size();
1178
Manuel Klimekd4397b92013-01-04 23:34:14 +00001179 // In case the token starts with escaped newlines, we want to
1180 // take them into account as whitespace - this pattern is quite frequent
1181 // in macro definitions.
1182 // FIXME: What do we want to do with other escaped spaces, and escaped
1183 // spaces or newlines in the middle of tokens?
1184 // FIXME: Add a more explicit test.
1185 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001186 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001187 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001188 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001189 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001190 }
1191
1192 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001193 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001194 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001195 FormatTok.Tok.setKind(Info.getTokenID());
1196 }
1197
1198 if (FormatTok.Tok.is(tok::greatergreater)) {
1199 FormatTok.Tok.setKind(tok::greater);
1200 GreaterStashed = true;
1201 }
1202
1203 return FormatTok;
1204 }
1205
1206private:
1207 FormatToken FormatTok;
1208 bool GreaterStashed;
1209 Lexer &Lex;
1210 SourceManager &SourceMgr;
1211 IdentifierTable IdentTable;
1212
1213 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001214 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001215 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1216 Tok.getLength());
1217 }
1218};
1219
Daniel Jasperbac016b2012-12-03 18:12:45 +00001220class Formatter : public UnwrappedLineConsumer {
1221public:
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001222 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1223 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001224 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001225 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001226 Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001227
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001228 virtual ~Formatter() {
1229 }
1230
Daniel Jasperbac016b2012-12-03 18:12:45 +00001231 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001232 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001233 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001234 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001235 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001236 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1237 E = UnwrappedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001238 I != E; ++I) {
1239 const UnwrappedLine &TheLine = *I;
1240 if (touchesRanges(TheLine)) {
1241 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
1242 if (!Annotator.annotate())
1243 break;
1244 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1245 TheLine.Level, TheLine.InPPDirective,
1246 PreviousEndOfLineColumn);
1247 bool FitsOnALine = fitsOnALine(Annotator.getRootToken(), Indent,
1248 TheLine.InPPDirective);
1249 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1250 FitsOnALine, Annotator.getLineType(),
1251 Annotator.getRootToken(), Replaces,
1252 StructuralError);
1253 PreviousEndOfLineColumn = Formatter.format();
1254 } else {
1255 // If we did not reformat this unwrapped line, the column at the end of
1256 // the last token is unchanged - thus, we can calculate the end of the
1257 // last token, and return the result.
1258 const FormatToken *Last = getLastLine(TheLine);
1259 PreviousEndOfLineColumn =
1260 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1261 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1262 Lex.getLangOpts()) -
1263 1;
1264 }
1265 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001266 return Replaces;
1267 }
1268
1269private:
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001270 const FormatToken *getLastLine(const UnwrappedLine &TheLine) {
1271 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001272 while (!Last->Children.empty())
1273 Last = &Last->Children.back();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001274 return Last;
1275 }
1276
1277 bool touchesRanges(const UnwrappedLine &TheLine) {
1278 const FormatToken *First = &TheLine.RootToken;
1279 const FormatToken *Last = getLastLine(TheLine);
Daniel Jaspercd162382013-01-07 13:26:07 +00001280 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001281 First->Tok.getLocation(),
1282 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001283 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001284 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1285 Ranges[i].getBegin()) &&
1286 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1287 LineRange.getBegin()))
1288 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001289 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001290 return false;
1291 }
1292
1293 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1294 UnwrappedLines.push_back(TheLine);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001295 }
1296
Manuel Klimek94fc6f12013-01-10 19:17:33 +00001297 bool fitsOnALine(const AnnotatedToken &RootToken, unsigned Indent,
1298 bool InPPDirective) {
1299 // Check whether the UnwrappedLine can be put onto a single line. If so,
1300 // this is bound to be the optimal solution (by definition) and we don't
1301 // need to analyze the entire solution space.
1302 unsigned Columns = Indent + RootToken.FormatTok.TokenLength;
1303 bool FitsOnALine = true;
1304 const AnnotatedToken *Tok = &RootToken;
1305 while (Tok != NULL) {
1306 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
1307 Tok->FormatTok.TokenLength;
1308 // A special case for the colon of a constructor initializer as this only
1309 // needs to be put on a new line if the line needs to be split.
1310 if (Columns > Style.ColumnLimit - (InPPDirective ? 1 : 0) ||
1311 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
1312 FitsOnALine = false;
1313 break;
1314 }
1315 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
1316 }
1317 return FitsOnALine;
1318 }
1319
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001320 /// \brief Add a new line and the required indent before the first Token
1321 /// of the \c UnwrappedLine if there was no structural parsing error.
1322 /// Returns the indent level of the \c UnwrappedLine.
1323 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1324 bool InPPDirective,
1325 unsigned PreviousEndOfLineColumn) {
1326 const FormatToken& Tok = RootToken.FormatTok;
1327 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1328 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1329
1330 unsigned Newlines = std::min(Tok.NewlinesBefore,
1331 Style.MaxEmptyLinesToKeep + 1);
1332 if (Newlines == 0 && !Tok.IsFirst)
1333 Newlines = 1;
1334 unsigned Indent = Level * 2;
1335
1336 bool IsAccessModifier = false;
1337 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1338 RootToken.is(tok::kw_private))
1339 IsAccessModifier = true;
1340 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1341 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1342 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1343 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1344 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1345 IsAccessModifier = true;
1346
1347 if (IsAccessModifier &&
1348 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1349 Indent += Style.AccessModifierOffset;
1350 if (!InPPDirective || Tok.HasUnescapedNewline) {
1351 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1352 } else {
1353 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1354 SourceMgr, Replaces);
1355 }
1356 return Indent;
1357 }
1358
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001359 clang::DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001360 FormatStyle Style;
1361 Lexer &Lex;
1362 SourceManager &SourceMgr;
1363 tooling::Replacements Replaces;
1364 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001365 std::vector<UnwrappedLine> UnwrappedLines;
1366 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001367};
1368
1369tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1370 SourceManager &SourceMgr,
1371 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001372 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1373 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1374 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1375 DiagnosticsEngine Diagnostics(
1376 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1377 &DiagnosticPrinter, false);
1378 Diagnostics.setSourceManager(&SourceMgr);
1379 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001380 return formatter.format();
1381}
1382
Daniel Jasper46ef8522013-01-10 13:08:12 +00001383LangOptions getFormattingLangOpts() {
1384 LangOptions LangOpts;
1385 LangOpts.CPlusPlus = 1;
1386 LangOpts.CPlusPlus11 = 1;
1387 LangOpts.Bool = 1;
1388 LangOpts.ObjC1 = 1;
1389 LangOpts.ObjC2 = 1;
1390 return LangOpts;
1391}
1392
Daniel Jaspercd162382013-01-07 13:26:07 +00001393} // namespace format
1394} // namespace clang