blob: 4a2e16b112d38a5d8cbc83652185160bb8bb794a [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperbac016b2012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasper71607512013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasper71607512013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Webercd52bda2013-01-10 23:11:41 +000042 TT_ObjCSelectorStart,
Nico Weber70848232013-01-10 21:30:42 +000043 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000044 TT_OverloadedOperator,
45 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000046 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000047 TT_TemplateCloser,
48 TT_TemplateOpener,
49 TT_TrailingUnaryOperator,
50 TT_UnaryOperator,
51 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000052};
53
54enum LineType {
55 LT_Invalid,
56 LT_Other,
57 LT_PreprocessorDirective,
58 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000059 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000060 LT_ObjCMethodDecl,
61 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000062};
63
Daniel Jasper26f7e782013-01-08 14:56:18 +000064class AnnotatedToken {
65public:
66 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000067 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
68 CanBreakBefore(false), MustBreakBefore(false),
69 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000070
71 bool is(tok::TokenKind Kind) const {
72 return FormatTok.Tok.is(Kind);
73 }
74 bool isNot(tok::TokenKind Kind) const {
75 return FormatTok.Tok.isNot(Kind);
76 }
77 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
78 return FormatTok.Tok.isObjCAtKeyword(Kind);
79 }
80
81 FormatToken FormatTok;
82
Daniel Jasperbac016b2012-12-03 18:12:45 +000083 TokenType Type;
84
Daniel Jasperbac016b2012-12-03 18:12:45 +000085 bool SpaceRequiredBefore;
86 bool CanBreakBefore;
87 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000088
89 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000090
91 std::vector<AnnotatedToken> Children;
92 AnnotatedToken *Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +000093};
94
Daniel Jasper26f7e782013-01-08 14:56:18 +000095static prec::Level getPrecedence(const AnnotatedToken &Tok) {
96 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +000097}
98
Daniel Jasperbac016b2012-12-03 18:12:45 +000099FormatStyle getLLVMStyle() {
100 FormatStyle LLVMStyle;
101 LLVMStyle.ColumnLimit = 80;
102 LLVMStyle.MaxEmptyLinesToKeep = 1;
103 LLVMStyle.PointerAndReferenceBindToType = false;
104 LLVMStyle.AccessModifierOffset = -2;
105 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000106 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000107 LLVMStyle.SpacesBeforeTrailingComments = 1;
Nico Weber5f500df2013-01-10 20:12:55 +0000108 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Webercd52bda2013-01-10 23:11:41 +0000109 LLVMStyle.ObjCSpaceBeforeReturnType = 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;
Nico Webercd52bda2013-01-10 23:11:41 +0000123 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000124 return GoogleStyle;
125}
126
127struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000128 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000129 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000130 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000131};
132
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000133/// \brief Replaces the whitespace in front of \p Tok. Only call once for
134/// each \c FormatToken.
135static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
136 unsigned Spaces, const FormatStyle &Style,
137 SourceManager &SourceMgr,
138 tooling::Replacements &Replaces) {
139 Replaces.insert(tooling::Replacement(
140 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
141 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
142}
143
144/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
145/// backslashes to escape newlines inside a preprocessor directive.
146///
147/// This function and \c replaceWhitespace have the same behavior if
148/// \c Newlines == 0.
149static void replacePPWhitespace(
150 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
151 unsigned WhitespaceStartColumn, const FormatStyle &Style,
152 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
153 std::string NewLineText;
154 if (NewLines > 0) {
155 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
156 WhitespaceStartColumn);
157 for (unsigned i = 0; i < NewLines; ++i) {
158 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
159 NewLineText += "\\\n";
160 Offset = 0;
161 }
162 }
163 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
164 Tok.FormatTok.WhiteSpaceLength,
165 NewLineText + std::string(Spaces, ' ')));
166}
167
Daniel Jasperbac016b2012-12-03 18:12:45 +0000168class UnwrappedLineFormatter {
169public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000170 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
171 const UnwrappedLine &Line, unsigned FirstIndent,
172 bool FitsOnALine, LineType CurrentLineType,
173 const AnnotatedToken &RootToken,
174 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000175 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000176 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper26f7e782013-01-08 14:56:18 +0000177 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000178 Replaces(Replaces) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000179 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000180 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000181 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000182 }
183
Manuel Klimekd4397b92013-01-04 23:34:14 +0000184 /// \brief Formats an \c UnwrappedLine.
185 ///
186 /// \returns The column after the last token in the last line of the
187 /// \c UnwrappedLine.
188 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000189 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000190 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000191 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000192 State.NextToken = &RootToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000193 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent, 0, false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000194 State.ForLoopVariablePos = 0;
195 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000196 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000197
198 // The first token has already been indented and thus consumed.
199 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000200
201 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000202 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000203 if (FitsOnALine) {
204 addTokenToState(false, false, State);
205 } else {
206 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
207 unsigned Break = calcPenalty(State, true, NoBreak);
208 addTokenToState(Break < NoBreak, false, State);
209 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000210 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000211 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212 }
213
214private:
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000215 struct ParenState {
216 ParenState(unsigned Indent, unsigned LastSpace, unsigned FirstLessLess,
217 bool BreakBeforeClosingBrace)
218 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(FirstLessLess),
219 BreakBeforeClosingBrace(BreakBeforeClosingBrace) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000220
Daniel Jasperbac016b2012-12-03 18:12:45 +0000221 /// \brief The position to which a specific parenthesis level needs to be
222 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000223 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000224
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000225 /// \brief The position of the last space on each level.
226 ///
227 /// Used e.g. to break like:
228 /// functionCall(Parameter, otherCall(
229 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000230 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000231
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000232 /// \brief The position the first "<<" operator encountered on each level.
233 ///
234 /// Used to align "<<" operators. 0 if no such operator has been encountered
235 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000236 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000237
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000238 /// \brief Whether a newline needs to be inserted before the block's closing
239 /// brace.
240 ///
241 /// We only want to insert a newline before the closing brace if there also
242 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000243 bool BreakBeforeClosingBrace;
244
245 bool operator<(const ParenState &Other) const {
246 if (Indent != Other.Indent)
247 return Indent < Other.Indent;
248 if (LastSpace != Other.LastSpace)
249 return LastSpace < Other.LastSpace;
250 if (FirstLessLess != Other.FirstLessLess)
251 return FirstLessLess < Other.FirstLessLess;
252 return BreakBeforeClosingBrace;
253 }
254 };
255
256 /// \brief The current state when indenting a unwrapped line.
257 ///
258 /// As the indenting tries different combinations this is copied by value.
259 struct LineState {
260 /// \brief The number of used columns in the current line.
261 unsigned Column;
262
263 /// \brief The token that needs to be next formatted.
264 const AnnotatedToken *NextToken;
265
266 /// \brief The parenthesis level of the first token on the current line.
267 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000268
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000269 /// \brief The column of the first variable in a for-loop declaration.
270 ///
271 /// Used to align the second variable if necessary.
272 unsigned ForLoopVariablePos;
273
274 /// \brief \c true if this line contains a continued for-loop section.
275 bool LineContainsContinuedForLoopSection;
276
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000277 /// \brief A stack keeping track of properties applying to parenthesis
278 /// levels.
279 std::vector<ParenState> Stack;
280
281 /// \brief Comparison operator to be able to used \c LineState in \c map.
282 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000283 if (Other.NextToken != NextToken)
284 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000285 if (Other.Column != Column)
286 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000287 if (Other.StartOfLineLevel != StartOfLineLevel)
288 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000289 if (Other.ForLoopVariablePos != ForLoopVariablePos)
290 return Other.ForLoopVariablePos < ForLoopVariablePos;
291 if (Other.LineContainsContinuedForLoopSection !=
292 LineContainsContinuedForLoopSection)
293 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000294 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000295 }
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.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000306 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000307 const AnnotatedToken &Current = *State.NextToken;
308 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000309 assert(State.Stack.size());
310 unsigned ParenLevel = State.Stack.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 Jasper604eb4c2013-01-11 10:22:12 +0000320 State.Stack[ParenLevel].FirstLessLess != 0) {
321 State.Column = State.Stack[ParenLevel].FirstLessLess;
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 Jasper604eb4c2013-01-11 10:22:12 +0000329 State.Column = State.Stack[ParenLevel].Indent + 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 Jasper604eb4c2013-01-11 10:22:12 +0000333 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000334 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000335 State.Column = State.Stack[ParenLevel].Indent;
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 Jasper604eb4c2013-01-11 10:22:12 +0000355 State.Stack[ParenLevel].LastSpace = 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 Jasper604eb4c2013-01-11 10:22:12 +0000358 State.Stack[ParenLevel].Indent += 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 Jasper604eb4c2013-01-11 10:22:12 +0000376 State.Stack[ParenLevel].Indent = 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)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000380 State.Stack[ParenLevel].Indent = 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 Jasper604eb4c2013-01-11 10:22:12 +0000387 State.Stack[ParenLevel].LastSpace = 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)) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000391 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000392 }
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.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000397 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000398 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000399 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000400
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000401 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
402 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000403
Daniel Jaspercf225b62012-12-24 13:43:52 +0000404 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000405 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000406 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
407 Current.is(tok::l_brace) ||
408 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000409 unsigned NewIndent;
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.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000414 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000415 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000416 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000417 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000418 State.Stack.push_back(
419 ParenState(NewIndent, State.Stack.back().LastSpace, 0, false));
Daniel Jasper20409152012-12-04 14:54:30 +0000420 }
421
Daniel Jaspercf225b62012-12-24 13:43:52 +0000422 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000423 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000424 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
425 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
426 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000427 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000429
Daniel Jasper26f7e782013-01-08 14:56:18 +0000430 if (State.NextToken->Children.empty())
431 State.NextToken = NULL;
432 else
433 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000434
435 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000436 }
437
Nico Weberdecf7bc2013-01-07 15:15:29 +0000438 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000439 unsigned splitPenalty(const AnnotatedToken &Tok) {
440 const AnnotatedToken &Left = Tok;
441 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000442
443 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000444 if (RootToken.is(tok::kw_for) &&
445 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000446 return 20;
447
Daniel Jasper26f7e782013-01-08 14:56:18 +0000448 if (Left.is(tok::semi) || Left.is(tok::comma) ||
449 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000450 return 0;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000451 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000452 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000453
Daniel Jasper9c837d02013-01-09 07:06:56 +0000454 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
455 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000456 prec::Level Level = getPrecedence(Left);
457
458 // Breaking after an assignment leads to a bad result as the two sides of
459 // the assignment are visually very close together.
460 if (Level == prec::Assignment)
461 return 50;
462
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000463 if (Level != prec::Unknown)
464 return Level;
465
Daniel Jasper26f7e782013-01-08 14:56:18 +0000466 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000467 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000468
Daniel Jasperbac016b2012-12-03 18:12:45 +0000469 return 3;
470 }
471
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000472 unsigned getColumnLimit() {
473 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
474 }
475
Daniel Jasperbac016b2012-12-03 18:12:45 +0000476 /// \brief Calculate the number of lines needed to format the remaining part
477 /// of the unwrapped line.
478 ///
479 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000480 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000481 /// added after the previous token.
482 ///
483 /// \param StopAt is used for optimization. If we can determine that we'll
484 /// definitely need at least \p StopAt additional lines, we already know of a
485 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000486 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000487 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000488 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000489 return 0;
490
Daniel Jasper26f7e782013-01-08 14:56:18 +0000491 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000492 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000493 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000494 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000495 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000496 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000497 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000498 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000499 State.LineContainsContinuedForLoopSection)
500 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501
Daniel Jasper33182dd2012-12-05 14:57:28 +0000502 unsigned CurrentPenalty = 0;
503 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000504 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000505 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000506 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000507 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000508 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000509 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000510 }
511
Daniel Jasper20409152012-12-04 14:54:30 +0000512 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000513
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000514 // Exceeding column limit is bad, assign penalty.
515 if (State.Column > getColumnLimit()) {
516 unsigned ExcessCharacters = State.Column - getColumnLimit();
517 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
518 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000519
Daniel Jasperbac016b2012-12-03 18:12:45 +0000520 if (StopAt <= CurrentPenalty)
521 return UINT_MAX;
522 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000524 if (I != Memory.end()) {
525 // If this state has already been examined, we can safely return the
526 // previous result if we
527 // - have not hit the optimatization (and thus returned UINT_MAX) OR
528 // - are now computing for a smaller or equal StopAt.
529 unsigned SavedResult = I->second.first;
530 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000531 if (SavedResult != UINT_MAX)
532 return SavedResult + CurrentPenalty;
533 else if (StopAt <= SavedStopAt)
534 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000535 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000536
537 unsigned NoBreak = calcPenalty(State, false, StopAt);
538 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
539 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000540
541 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
542 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000543 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000544
545 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000546 }
547
Daniel Jasperbac016b2012-12-03 18:12:45 +0000548 FormatStyle Style;
549 SourceManager &SourceMgr;
550 const UnwrappedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000551 const unsigned FirstIndent;
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000552 const bool FitsOnALine;
Daniel Jasper71607512013-01-07 10:48:50 +0000553 const LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000554 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000555 tooling::Replacements &Replaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000556
Daniel Jasper33182dd2012-12-05 14:57:28 +0000557 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000558 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000559 StateMap Memory;
560
Daniel Jasperbac016b2012-12-03 18:12:45 +0000561 OptimizationParameters Parameters;
562};
563
564/// \brief Determines extra information about the tokens comprising an
565/// \c UnwrappedLine.
566class TokenAnnotator {
567public:
568 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000569 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper26f7e782013-01-08 14:56:18 +0000570 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
571 RootToken(Line.RootToken) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 }
573
574 /// \brief A parser that gathers additional information about tokens.
575 ///
576 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
577 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
578 /// into template parameter lists.
579 class AnnotatingParser {
580 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000581 AnnotatingParser(AnnotatedToken &RootToken)
582 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000583 }
584
Daniel Jasper20409152012-12-04 14:54:30 +0000585 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000586 while (CurrentToken != NULL) {
587 if (CurrentToken->is(tok::greater)) {
588 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000589 next();
590 return true;
591 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000592 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
593 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000594 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000595 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
596 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000597 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000598 if (!consumeToken())
599 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000600 }
601 return false;
602 }
603
Daniel Jasper20409152012-12-04 14:54:30 +0000604 bool parseParens() {
Daniel Jasper46ef8522013-01-10 13:08:12 +0000605 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
606 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000607 while (CurrentToken != NULL) {
608 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000609 next();
610 return true;
611 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000612 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000613 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000614 if (!consumeToken())
615 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616 }
617 return false;
618 }
619
Daniel Jasper20409152012-12-04 14:54:30 +0000620 bool parseSquare() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000621 while (CurrentToken != NULL) {
622 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000623 next();
624 return true;
625 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000626 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000628 if (!consumeToken())
629 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000630 }
631 return false;
632 }
633
Daniel Jasper700e7102013-01-10 09:26:47 +0000634 bool parseBrace() {
635 while (CurrentToken != NULL) {
636 if (CurrentToken->is(tok::r_brace)) {
637 next();
638 return true;
639 }
640 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
641 return false;
642 if (!consumeToken())
643 return false;
644 }
645 // Lines can currently end with '{'.
646 return true;
647 }
648
Daniel Jasper20409152012-12-04 14:54:30 +0000649 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000650 while (CurrentToken != NULL) {
651 if (CurrentToken->is(tok::colon)) {
652 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000653 next();
654 return true;
655 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000656 if (!consumeToken())
657 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000658 }
659 return false;
660 }
661
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000662 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000663 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
664 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000665 next();
666 if (!parseAngle())
667 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000668 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000669 parseLine();
670 return true;
671 }
672 return false;
673 }
674
Daniel Jasper1f42f112013-01-04 18:52:56 +0000675 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000676 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000677 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000678 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +0000679 case tok::plus:
680 case tok::minus:
681 // At the start of the line, +/- specific ObjectiveC method
682 // declarations.
683 if (Tok->Parent == NULL)
684 Tok->Type = TT_ObjCMethodSpecifier;
685 break;
686 case tok::l_paren: {
687 bool ParensWereObjCReturnType =
688 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000689 if (!parseParens())
690 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000691 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
692 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000693 next();
Nico Webercd52bda2013-01-10 23:11:41 +0000694 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
695 CurrentToken->Type = TT_ObjCSelectorStart;
696 next();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000697 }
Nico Webercd52bda2013-01-10 23:11:41 +0000698 } break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000699 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000700 if (!parseSquare())
701 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000702 break;
Daniel Jasper700e7102013-01-10 09:26:47 +0000703 case tok::l_brace:
704 if (!parseBrace())
705 return false;
706 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000708 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000709 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000710 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000711 Tok->Type = TT_BinaryOperator;
712 CurrentToken = Tok;
713 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714 }
715 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000716 case tok::r_paren:
717 case tok::r_square:
718 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +0000719 case tok::r_brace:
720 // Lines can start with '}'.
721 if (Tok->Parent != NULL)
722 return false;
723 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000724 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000725 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 break;
727 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000728 if (CurrentToken->is(tok::l_paren)) {
729 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000730 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000731 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
732 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000733 next();
734 }
735 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000736 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
737 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000738 next();
739 }
740 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 break;
742 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000743 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000744 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000745 case tok::kw_template:
746 parseTemplateDeclaration();
747 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000748 default:
749 break;
750 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000751 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000752 }
753
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000754 void parseIncludeDirective() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000755 while (CurrentToken != NULL) {
756 if (CurrentToken->is(tok::slash))
757 CurrentToken->Type = TT_DirectorySeparator;
758 else if (CurrentToken->is(tok::less))
759 CurrentToken->Type = TT_TemplateOpener;
760 else if (CurrentToken->is(tok::greater))
761 CurrentToken->Type = TT_TemplateCloser;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000762 next();
763 }
764 }
765
766 void parsePreprocessorDirective() {
767 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000768 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000769 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000770 // Hashes in the middle of a line can lead to any strange token
771 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000772 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000773 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000774 switch (
775 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000776 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000777 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000778 parseIncludeDirective();
779 break;
780 default:
781 break;
782 }
783 }
784
Daniel Jasper71607512013-01-07 10:48:50 +0000785 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000786 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000787 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000788 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000789 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000790 while (CurrentToken != NULL) {
791 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000792 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000793 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000794 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000795 }
Daniel Jasper71607512013-01-07 10:48:50 +0000796 if (KeywordVirtualFound)
797 return LT_VirtualFunctionDecl;
798 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000799 }
800
801 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000802 if (CurrentToken != NULL && !CurrentToken->Children.empty())
803 CurrentToken = &CurrentToken->Children[0];
804 else
805 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000806 }
807
808 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000809 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000810 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000811 };
812
Daniel Jasper26f7e782013-01-08 14:56:18 +0000813 void createAnnotatedTokens(AnnotatedToken &Current) {
814 if (!Current.FormatTok.Children.empty()) {
815 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
816 Current.Children.back().Parent = &Current;
817 createAnnotatedTokens(Current.Children.back());
818 }
819 }
Daniel Jasper71607512013-01-07 10:48:50 +0000820
Daniel Jasper26f7e782013-01-08 14:56:18 +0000821 void calculateExtraInformation(AnnotatedToken &Current) {
822 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
823
Manuel Klimek526ed112013-01-09 15:25:02 +0000824 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000825 Current.MustBreakBefore = true;
826 } else {
Manuel Klimek526ed112013-01-09 15:25:02 +0000827 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
828 TT_LineComment || (Current.is(tok::string_literal) &&
829 Current.Parent->is(tok::string_literal))) {
830 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +0000831 } else {
832 Current.MustBreakBefore = false;
833 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000834 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000835 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000836 if (!Current.Children.empty())
837 calculateExtraInformation(Current.Children[0]);
838 }
839
840 bool annotate() {
841 createAnnotatedTokens(RootToken);
842
843 AnnotatingParser Parser(RootToken);
Daniel Jasper71607512013-01-07 10:48:50 +0000844 CurrentLineType = Parser.parseLine();
845 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000846 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000847
Daniel Jasper26f7e782013-01-08 14:56:18 +0000848 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000849
Daniel Jasper26f7e782013-01-08 14:56:18 +0000850 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasper71607512013-01-07 10:48:50 +0000851 CurrentLineType = LT_ObjCMethodDecl;
Nico Webered91bba2013-01-10 19:19:14 +0000852 else if (RootToken.Type == TT_ObjCDecl)
853 CurrentLineType = LT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +0000854 else if (RootToken.Type == TT_ObjCProperty)
855 CurrentLineType = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +0000856
Daniel Jasper26f7e782013-01-08 14:56:18 +0000857 if (!RootToken.Children.empty())
858 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000859 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000860 }
861
Daniel Jasper71607512013-01-07 10:48:50 +0000862 LineType getLineType() {
863 return CurrentLineType;
864 }
865
Daniel Jasper26f7e782013-01-08 14:56:18 +0000866 const AnnotatedToken &getRootToken() {
867 return RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000868 }
869
870private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000871 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
872 if (getPrecedence(Current) == prec::Assignment ||
873 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
874 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875
Daniel Jasper26f7e782013-01-08 14:56:18 +0000876 if (Current.Type == TT_Unknown) {
877 if (Current.is(tok::star) || Current.is(tok::amp)) {
878 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +0000879 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
880 Current.is(tok::caret)) {
881 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000882 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
883 Current.Type = determineIncrementUsage(Current);
884 } else if (Current.is(tok::exclaim)) {
885 Current.Type = TT_UnaryOperator;
886 } else if (isBinaryOperator(Current)) {
887 Current.Type = TT_BinaryOperator;
888 } else if (Current.is(tok::comment)) {
889 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
890 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +0000891 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000892 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000893 else
Daniel Jasper26f7e782013-01-08 14:56:18 +0000894 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +0000895 } else if (Current.is(tok::r_paren) &&
896 (Current.Parent->Type == TT_PointerOrReference ||
897 Current.Parent->Type == TT_TemplateCloser)) {
898 // FIXME: We need to get smarter and understand more cases of casts.
899 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +0000900 } else if (Current.is(tok::at) && Current.Children.size()) {
901 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
902 case tok::objc_interface:
903 case tok::objc_implementation:
904 case tok::objc_protocol:
905 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +0000906 break;
907 case tok::objc_property:
908 Current.Type = TT_ObjCProperty;
909 break;
Nico Webered91bba2013-01-10 19:19:14 +0000910 default:
911 break;
912 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000913 }
914 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000915
916 if (!Current.Children.empty())
917 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000918 }
919
Daniel Jasper26f7e782013-01-08 14:56:18 +0000920 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000921 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000922 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000923 }
924
Daniel Jasper26f7e782013-01-08 14:56:18 +0000925 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
926 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000927 return TT_UnaryOperator;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000928 if (Tok.Children.size() == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000929 return TT_Unknown;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000930 const FormatToken &PrevToken = Tok.Parent->FormatTok;
931 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000932
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000933 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
934 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper5cf7cf32013-01-10 11:14:08 +0000935 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
936 Tok.Parent->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +0000937 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000938
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000939 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000940 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
941 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
942 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
943 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000944 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000945
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000946 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
947 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000948 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000949
Daniel Jasper112fb272012-12-05 07:51:39 +0000950 // It is very unlikely that we are going to find a pointer or reference type
951 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000952 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000953 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000954
Daniel Jasper71607512013-01-07 10:48:50 +0000955 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 }
957
Daniel Jasper886568d2013-01-09 08:36:49 +0000958 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000959 // Use heuristics to recognize unary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000960 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
961 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
962 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Weber81ed2f12013-01-10 19:36:35 +0000963 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
964 Tok.Parent->is(tok::at))
Daniel Jasper71607512013-01-07 10:48:50 +0000965 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000966
967 // There can't be to consecutive binary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000968 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +0000969 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000970
971 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +0000972 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000973 }
974
975 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000976 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
977 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +0000978 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000979
Daniel Jasper71607512013-01-07 10:48:50 +0000980 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000981 }
982
Daniel Jasper26f7e782013-01-08 14:56:18 +0000983 bool spaceRequiredBetween(const AnnotatedToken &Left,
984 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +0000985 if (Right.is(tok::hashhash))
986 return Left.is(tok::hash);
987 if (Left.is(tok::hashhash) || Left.is(tok::hash))
988 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +0000989 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
990 return false;
Nico Weber5f500df2013-01-10 20:12:55 +0000991 if (Right.is(tok::less) &&
992 (Left.is(tok::kw_template) ||
993 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000994 return true;
995 if (Left.is(tok::arrow) || Right.is(tok::arrow))
996 return false;
997 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
998 return false;
Nico Webercb4d6902013-01-08 19:40:21 +0000999 if (Left.is(tok::at) &&
1000 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1001 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001002 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1003 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001004 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001005 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1006 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001007 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001008 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001009 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1010 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001012 return Right.FormatTok.Tok.isLiteral() ||
1013 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001014 if (Right.is(tok::star) && Left.is(tok::l_paren))
1015 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001016 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1017 Right.is(tok::r_square))
1018 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001019 if (Left.is(tok::coloncolon) ||
1020 (Right.is(tok::coloncolon) &&
1021 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001022 return false;
1023 if (Left.is(tok::period) || Right.is(tok::period))
1024 return false;
1025 if (Left.is(tok::colon) || Right.is(tok::colon))
1026 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001027 if (Left.is(tok::l_paren))
1028 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001029 if (Right.is(tok::l_paren)) {
Nico Webered91bba2013-01-10 19:19:14 +00001030 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1031 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1032 Left.is(tok::kw_switch) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001033 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001034 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001035 if (Left.is(tok::at) &&
1036 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001037 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001038 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1039 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001040 return true;
1041 }
1042
Daniel Jasper26f7e782013-01-08 14:56:18 +00001043 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperda927712013-01-07 15:36:15 +00001044 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001045 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1046 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001047 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001048 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001049 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001050 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Webercd52bda2013-01-10 23:11:41 +00001051 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1052 if (Tok.Type == TT_ObjCSelectorStart)
1053 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001054 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001055 // Don't space between ')' and <id>
1056 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001057 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001058 // Don't space between ':' and '('
1059 return false;
1060 }
Nico Weber70848232013-01-10 21:30:42 +00001061 if (CurrentLineType == LT_ObjCProperty &&
1062 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1063 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001064
Daniel Jasper46ef8522013-01-10 13:08:12 +00001065 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001066 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001067 if (Tok.Type == TT_OverloadedOperator)
1068 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001069 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001070 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001071 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001072 if (Tok.is(tok::colon))
1073 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001074 if (Tok.Parent->Type == TT_UnaryOperator ||
1075 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001076 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001077 if (Tok.Type == TT_UnaryOperator)
1078 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber81ed2f12013-01-10 19:36:35 +00001079 Tok.Parent->isNot(tok::l_square) &&
1080 Tok.Parent->isNot(tok::at);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001081 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1082 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001083 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1084 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001085 if (Tok.Type == TT_DirectorySeparator ||
1086 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperda927712013-01-07 15:36:15 +00001087 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001088 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001089 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001090 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001091 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001092 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001093 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001094 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001095 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001096 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001097 }
1098
Daniel Jasper26f7e782013-01-08 14:56:18 +00001099 bool canBreakBefore(const AnnotatedToken &Right) {
1100 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperda927712013-01-07 15:36:15 +00001101 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001102 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1103 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001104 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001105 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1106 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001107 // Don't break this identifier as ':' or identifier
1108 // before it will break.
1109 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001110 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1111 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001112 // Don't break at ':' if identifier before it can beak.
1113 return false;
1114 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001115 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001116 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001117 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001118 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001119 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001120 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001121 return false;
1122
Daniel Jasper043835a2013-01-09 09:33:39 +00001123 if (Right.is(tok::comment))
1124 return !Right.Children.empty();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001125 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasper043835a2013-01-09 09:33:39 +00001126 Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001127 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001128 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1129 Left.is(tok::comma) || Right.is(tok::lessless) ||
1130 Right.is(tok::arrow) || Right.is(tok::period) ||
1131 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper9c837d02013-01-09 07:06:56 +00001132 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimekc8c8a472013-01-10 15:58:26 +00001133 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001134 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001135 }
1136
Daniel Jasperbac016b2012-12-03 18:12:45 +00001137 FormatStyle Style;
1138 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001139 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001140 LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001141 AnnotatedToken RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001142};
1143
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001144class LexerBasedFormatTokenSource : public FormatTokenSource {
1145public:
1146 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001147 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001148 IdentTable(Lex.getLangOpts()) {
1149 Lex.SetKeepWhitespaceMode(true);
1150 }
1151
1152 virtual FormatToken getNextToken() {
1153 if (GreaterStashed) {
1154 FormatTok.NewlinesBefore = 0;
1155 FormatTok.WhiteSpaceStart =
1156 FormatTok.Tok.getLocation().getLocWithOffset(1);
1157 FormatTok.WhiteSpaceLength = 0;
1158 GreaterStashed = false;
1159 return FormatTok;
1160 }
1161
1162 FormatTok = FormatToken();
1163 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001164 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001165 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001166 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1167 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001168
1169 // Consume and record whitespace until we find a significant token.
1170 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001171 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001172 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1173 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001174 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1175
1176 if (FormatTok.Tok.is(tok::eof))
1177 return FormatTok;
1178 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001179 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001180 }
Manuel Klimek95419382013-01-07 07:56:50 +00001181
1182 // Now FormatTok is the next non-whitespace token.
1183 FormatTok.TokenLength = Text.size();
1184
Manuel Klimekd4397b92013-01-04 23:34:14 +00001185 // In case the token starts with escaped newlines, we want to
1186 // take them into account as whitespace - this pattern is quite frequent
1187 // in macro definitions.
1188 // FIXME: What do we want to do with other escaped spaces, and escaped
1189 // spaces or newlines in the middle of tokens?
1190 // FIXME: Add a more explicit test.
1191 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001192 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001193 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001194 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001195 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001196 }
1197
1198 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001199 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001200 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001201 FormatTok.Tok.setKind(Info.getTokenID());
1202 }
1203
1204 if (FormatTok.Tok.is(tok::greatergreater)) {
1205 FormatTok.Tok.setKind(tok::greater);
1206 GreaterStashed = true;
1207 }
1208
1209 return FormatTok;
1210 }
1211
1212private:
1213 FormatToken FormatTok;
1214 bool GreaterStashed;
1215 Lexer &Lex;
1216 SourceManager &SourceMgr;
1217 IdentifierTable IdentTable;
1218
1219 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001220 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001221 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1222 Tok.getLength());
1223 }
1224};
1225
Daniel Jasperbac016b2012-12-03 18:12:45 +00001226class Formatter : public UnwrappedLineConsumer {
1227public:
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001228 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1229 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001230 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001231 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001232 Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001233
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001234 virtual ~Formatter() {
1235 }
1236
Daniel Jasperbac016b2012-12-03 18:12:45 +00001237 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001238 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001239 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001240 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001241 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001242 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1243 E = UnwrappedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001244 I != E; ++I) {
1245 const UnwrappedLine &TheLine = *I;
1246 if (touchesRanges(TheLine)) {
1247 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
1248 if (!Annotator.annotate())
1249 break;
1250 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1251 TheLine.Level, TheLine.InPPDirective,
1252 PreviousEndOfLineColumn);
1253 bool FitsOnALine = fitsOnALine(Annotator.getRootToken(), Indent,
1254 TheLine.InPPDirective);
1255 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1256 FitsOnALine, Annotator.getLineType(),
1257 Annotator.getRootToken(), Replaces,
1258 StructuralError);
1259 PreviousEndOfLineColumn = Formatter.format();
1260 } else {
1261 // If we did not reformat this unwrapped line, the column at the end of
1262 // the last token is unchanged - thus, we can calculate the end of the
1263 // last token, and return the result.
1264 const FormatToken *Last = getLastLine(TheLine);
1265 PreviousEndOfLineColumn =
1266 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1267 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1268 Lex.getLangOpts()) -
1269 1;
1270 }
1271 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001272 return Replaces;
1273 }
1274
1275private:
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001276 const FormatToken *getLastLine(const UnwrappedLine &TheLine) {
1277 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001278 while (!Last->Children.empty())
1279 Last = &Last->Children.back();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001280 return Last;
1281 }
1282
1283 bool touchesRanges(const UnwrappedLine &TheLine) {
1284 const FormatToken *First = &TheLine.RootToken;
1285 const FormatToken *Last = getLastLine(TheLine);
Daniel Jaspercd162382013-01-07 13:26:07 +00001286 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001287 First->Tok.getLocation(),
1288 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001289 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001290 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1291 Ranges[i].getBegin()) &&
1292 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1293 LineRange.getBegin()))
1294 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001295 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001296 return false;
1297 }
1298
1299 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1300 UnwrappedLines.push_back(TheLine);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001301 }
1302
Manuel Klimek94fc6f12013-01-10 19:17:33 +00001303 bool fitsOnALine(const AnnotatedToken &RootToken, unsigned Indent,
1304 bool InPPDirective) {
1305 // Check whether the UnwrappedLine can be put onto a single line. If so,
1306 // this is bound to be the optimal solution (by definition) and we don't
1307 // need to analyze the entire solution space.
1308 unsigned Columns = Indent + RootToken.FormatTok.TokenLength;
1309 bool FitsOnALine = true;
1310 const AnnotatedToken *Tok = &RootToken;
1311 while (Tok != NULL) {
1312 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
1313 Tok->FormatTok.TokenLength;
1314 // A special case for the colon of a constructor initializer as this only
1315 // needs to be put on a new line if the line needs to be split.
1316 if (Columns > Style.ColumnLimit - (InPPDirective ? 1 : 0) ||
1317 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
1318 FitsOnALine = false;
1319 break;
1320 }
1321 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
1322 }
1323 return FitsOnALine;
1324 }
1325
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001326 /// \brief Add a new line and the required indent before the first Token
1327 /// of the \c UnwrappedLine if there was no structural parsing error.
1328 /// Returns the indent level of the \c UnwrappedLine.
1329 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1330 bool InPPDirective,
1331 unsigned PreviousEndOfLineColumn) {
1332 const FormatToken& Tok = RootToken.FormatTok;
1333 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1334 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1335
1336 unsigned Newlines = std::min(Tok.NewlinesBefore,
1337 Style.MaxEmptyLinesToKeep + 1);
1338 if (Newlines == 0 && !Tok.IsFirst)
1339 Newlines = 1;
1340 unsigned Indent = Level * 2;
1341
1342 bool IsAccessModifier = false;
1343 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1344 RootToken.is(tok::kw_private))
1345 IsAccessModifier = true;
1346 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1347 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1348 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1349 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1350 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1351 IsAccessModifier = true;
1352
1353 if (IsAccessModifier &&
1354 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1355 Indent += Style.AccessModifierOffset;
1356 if (!InPPDirective || Tok.HasUnescapedNewline) {
1357 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1358 } else {
1359 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1360 SourceMgr, Replaces);
1361 }
1362 return Indent;
1363 }
1364
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001365 clang::DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001366 FormatStyle Style;
1367 Lexer &Lex;
1368 SourceManager &SourceMgr;
1369 tooling::Replacements Replaces;
1370 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001371 std::vector<UnwrappedLine> UnwrappedLines;
1372 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001373};
1374
1375tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1376 SourceManager &SourceMgr,
1377 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001378 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1379 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1380 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1381 DiagnosticsEngine Diagnostics(
1382 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1383 &DiagnosticPrinter, false);
1384 Diagnostics.setSourceManager(&SourceMgr);
1385 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001386 return formatter.format();
1387}
1388
Daniel Jasper46ef8522013-01-10 13:08:12 +00001389LangOptions getFormattingLangOpts() {
1390 LangOptions LangOpts;
1391 LangOpts.CPlusPlus = 1;
1392 LangOpts.CPlusPlus11 = 1;
1393 LangOpts.Bool = 1;
1394 LangOpts.ObjC1 = 1;
1395 LangOpts.ObjC2 = 1;
1396 return LangOpts;
1397}
1398
Daniel Jaspercd162382013-01-07 13:26:07 +00001399} // namespace format
1400} // namespace clang