blob: e271ba2e13abb581ffdc2246f80b09e887d2068a [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"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperbac016b2012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
Daniel Jasper71607512013-01-07 10:48:50 +000029enum TokenType {
30 TT_Unknown,
31 TT_TemplateOpener,
32 TT_TemplateCloser,
33 TT_BinaryOperator,
34 TT_UnaryOperator,
35 TT_TrailingUnaryOperator,
36 TT_OverloadedOperator,
37 TT_PointerOrReference,
38 TT_ConditionalExpr,
39 TT_CtorInitializerColon,
40 TT_LineComment,
41 TT_BlockComment,
42 TT_DirectorySeparator,
43 TT_PureVirtualSpecifier,
44 TT_ObjCMethodSpecifier
45};
46
47enum LineType {
48 LT_Invalid,
49 LT_Other,
50 LT_PreprocessorDirective,
51 LT_VirtualFunctionDecl,
52 LT_ObjCMethodDecl
53};
54
Daniel Jasper26f7e782013-01-08 14:56:18 +000055class AnnotatedToken {
56public:
57 AnnotatedToken(const FormatToken &FormatTok)
58 : FormatTok(FormatTok), Type(TT_Unknown),
59 ClosesTemplateDeclaration(false), Parent(NULL) {
60 }
61
62 bool is(tok::TokenKind Kind) const {
63 return FormatTok.Tok.is(Kind);
64 }
65 bool isNot(tok::TokenKind Kind) const {
66 return FormatTok.Tok.isNot(Kind);
67 }
68 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
69 return FormatTok.Tok.isObjCAtKeyword(Kind);
70 }
71
72 FormatToken FormatTok;
73
Daniel Jasperbac016b2012-12-03 18:12:45 +000074 TokenType Type;
75
Daniel Jasperbac016b2012-12-03 18:12:45 +000076 bool SpaceRequiredBefore;
77 bool CanBreakBefore;
78 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000079
80 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000081
82 std::vector<AnnotatedToken> Children;
83 AnnotatedToken *Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +000084};
85
Daniel Jasper26f7e782013-01-08 14:56:18 +000086static prec::Level getPrecedence(const AnnotatedToken &Tok) {
87 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +000088}
89
Daniel Jasperbac016b2012-12-03 18:12:45 +000090using llvm::MutableArrayRef;
91
92FormatStyle getLLVMStyle() {
93 FormatStyle LLVMStyle;
94 LLVMStyle.ColumnLimit = 80;
95 LLVMStyle.MaxEmptyLinesToKeep = 1;
96 LLVMStyle.PointerAndReferenceBindToType = false;
97 LLVMStyle.AccessModifierOffset = -2;
98 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000099 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000100 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000101 return LLVMStyle;
102}
103
104FormatStyle getGoogleStyle() {
105 FormatStyle GoogleStyle;
106 GoogleStyle.ColumnLimit = 80;
107 GoogleStyle.MaxEmptyLinesToKeep = 1;
108 GoogleStyle.PointerAndReferenceBindToType = true;
109 GoogleStyle.AccessModifierOffset = -1;
110 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000111 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000112 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000113 return GoogleStyle;
114}
115
116struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000117 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000118 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000119 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000120};
121
122class UnwrappedLineFormatter {
123public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000124 UnwrappedLineFormatter(
125 const FormatStyle &Style, SourceManager &SourceMgr,
126 const UnwrappedLine &Line, unsigned PreviousEndOfLineColumn,
127 LineType CurrentLineType, const AnnotatedToken &RootToken,
128 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000129 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekd4397b92013-01-04 23:34:14 +0000130 PreviousEndOfLineColumn(PreviousEndOfLineColumn),
Daniel Jasper26f7e782013-01-08 14:56:18 +0000131 CurrentLineType(CurrentLineType), RootToken(RootToken),
Daniel Jasper71607512013-01-07 10:48:50 +0000132 Replaces(Replaces), StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000133 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000134 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000135 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000136 }
137
Manuel Klimekd4397b92013-01-04 23:34:14 +0000138 /// \brief Formats an \c UnwrappedLine.
139 ///
140 /// \returns The column after the last token in the last line of the
141 /// \c UnwrappedLine.
142 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000143 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000144 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000145
146 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000147 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000148 State.Column = Indent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000149 State.NextToken = &RootToken;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000150 State.Indent.push_back(Indent + 4);
151 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000152 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000153 State.ForLoopVariablePos = 0;
154 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000155 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000156
157 // The first token has already been indented and thus consumed.
158 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000159
Daniel Jasper1321eb52012-12-18 21:05:13 +0000160 // Check whether the UnwrappedLine can be put onto a single line. If so,
161 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasper1f42f112013-01-04 18:52:56 +0000162 // need to analyze the entire solution space.
Daniel Jasper1321eb52012-12-18 21:05:13 +0000163 unsigned Columns = State.Column;
164 bool FitsOnALine = true;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000165 const AnnotatedToken *Tok = State.NextToken;
166 while (Tok != NULL) {
167 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
168 Tok->FormatTok.TokenLength;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000169 // A special case for the colon of a constructor initializer as this only
170 // needs to be put on a new line if the line needs to be split.
Manuel Klimekd544c572013-01-07 09:24:17 +0000171 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000172 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000173 FitsOnALine = false;
174 break;
175 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000176 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
Daniel Jasper1321eb52012-12-18 21:05:13 +0000177 }
178
Daniel Jasperbac016b2012-12-03 18:12:45 +0000179 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000180 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000181 if (FitsOnALine) {
182 addTokenToState(false, false, State);
183 } else {
184 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
185 unsigned Break = calcPenalty(State, true, NoBreak);
186 addTokenToState(Break < NoBreak, false, State);
187 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000188 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000189 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000190 }
191
192private:
193 /// \brief The current state when indenting a unwrapped line.
194 ///
195 /// As the indenting tries different combinations this is copied by value.
196 struct IndentState {
197 /// \brief The number of used columns in the current line.
198 unsigned Column;
199
Daniel Jasper26f7e782013-01-08 14:56:18 +0000200 const AnnotatedToken *NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000201
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000202 /// \brief The parenthesis level of the first token on the current line.
203 unsigned StartOfLineLevel;
204
Daniel Jasperbac016b2012-12-03 18:12:45 +0000205 /// \brief The position to which a specific parenthesis level needs to be
206 /// indented.
207 std::vector<unsigned> Indent;
208
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000209 /// \brief The position of the last space on each level.
210 ///
211 /// Used e.g. to break like:
212 /// functionCall(Parameter, otherCall(
213 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000214 std::vector<unsigned> LastSpace;
215
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000216 /// \brief The position the first "<<" operator encountered on each level.
217 ///
218 /// Used to align "<<" operators. 0 if no such operator has been encountered
219 /// on a level.
220 std::vector<unsigned> FirstLessLess;
221
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000222 /// \brief The column of the first variable in a for-loop declaration.
223 ///
224 /// Used to align the second variable if necessary.
225 unsigned ForLoopVariablePos;
226
227 /// \brief \c true if this line contains a continued for-loop section.
228 bool LineContainsContinuedForLoopSection;
229
Daniel Jasperbac016b2012-12-03 18:12:45 +0000230 /// \brief Comparison operator to be able to used \c IndentState in \c map.
231 bool operator<(const IndentState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000232 if (Other.NextToken != NextToken)
233 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000234 if (Other.Column != Column)
235 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000236 if (Other.StartOfLineLevel != StartOfLineLevel)
237 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000238 if (Other.Indent.size() != Indent.size())
239 return Other.Indent.size() > Indent.size();
240 for (int i = 0, e = Indent.size(); i != e; ++i) {
241 if (Other.Indent[i] != Indent[i])
242 return Other.Indent[i] > Indent[i];
243 }
244 if (Other.LastSpace.size() != LastSpace.size())
245 return Other.LastSpace.size() > LastSpace.size();
246 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
247 if (Other.LastSpace[i] != LastSpace[i])
248 return Other.LastSpace[i] > LastSpace[i];
249 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000250 if (Other.FirstLessLess.size() != FirstLessLess.size())
251 return Other.FirstLessLess.size() > FirstLessLess.size();
252 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
253 if (Other.FirstLessLess[i] != FirstLessLess[i])
254 return Other.FirstLessLess[i] > FirstLessLess[i];
255 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000256 if (Other.ForLoopVariablePos != ForLoopVariablePos)
257 return Other.ForLoopVariablePos < ForLoopVariablePos;
258 if (Other.LineContainsContinuedForLoopSection !=
259 LineContainsContinuedForLoopSection)
260 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261 return false;
262 }
263 };
264
Daniel Jasper20409152012-12-04 14:54:30 +0000265 /// \brief Appends the next token to \p State and updates information
266 /// necessary for indentation.
267 ///
268 /// Puts the token on the current line if \p Newline is \c true and adds a
269 /// line break and necessary indentation otherwise.
270 ///
271 /// If \p DryRun is \c false, also creates and stores the required
272 /// \c Replacement.
273 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000274 const AnnotatedToken &Current = *State.NextToken;
275 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper20409152012-12-04 14:54:30 +0000276 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000277
278 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000279 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000280 if (Previous.is(tok::l_brace)) {
Daniel Jasper9cda8002013-01-07 13:08:40 +0000281 // FIXME: This does not work with nested static initializers.
282 // Implement a better handling for static initializers and similar
283 // constructs.
284 State.Column = Line.Level * 2 + 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000285 } else if (Current.is(tok::string_literal) &&
286 Previous.is(tok::string_literal)) {
287 State.Column = State.Column - Previous.FormatTok.TokenLength;
288 } else if (Current.is(tok::lessless) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000289 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000290 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000291 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000292 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
293 Current.is(tok::period) || Previous.is(tok::question) ||
294 Previous.Type == TT_ConditionalExpr)) {
295 // Indent and extra 4 spaces after if we know the current expression is
296 // continued. Don't do that on the top level, as we already indent 4
297 // there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000298 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000299 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000300 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000301 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000302 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000303 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000304 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000305 }
306
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000307 State.StartOfLineLevel = ParenLevel + 1;
308
Daniel Jasper26f7e782013-01-08 14:56:18 +0000309 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000310 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000311
Manuel Klimek060143e2013-01-02 18:33:23 +0000312 if (!DryRun) {
313 if (!Line.InPPDirective)
Daniel Jasper9c837d02013-01-09 07:06:56 +0000314 replaceWhitespace(Current.FormatTok, 1, State.Column);
Manuel Klimek060143e2013-01-02 18:33:23 +0000315 else
Daniel Jasper9c837d02013-01-09 07:06:56 +0000316 replacePPWhitespace(Current.FormatTok, 1, State.Column,
317 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000318 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000319
Daniel Jasperd64f7382013-01-09 09:50:48 +0000320 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000321 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper26f7e782013-01-08 14:56:18 +0000322 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000323 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000324 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000325 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
326 State.ForLoopVariablePos = State.Column -
327 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000328
Daniel Jasper26f7e782013-01-08 14:56:18 +0000329 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
330 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000331 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000332
Daniel Jasperbac016b2012-12-03 18:12:45 +0000333 if (!DryRun)
334 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000335
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000336 // FIXME: Do we need to do this for assignments nested in other
337 // expressions?
338 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000339 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000340 Previous.is(tok::kw_return)))
Daniel Jaspercf225b62012-12-24 13:43:52 +0000341 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000342 if (Previous.is(tok::l_paren) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000343 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000344 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000345
Daniel Jasper9cda8002013-01-07 13:08:40 +0000346 // Top-level spaces that are not part of assignments are exempt as that
347 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000348 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000349 if (Spaces > 0 &&
350 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000351 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000352 }
Daniel Jasper20409152012-12-04 14:54:30 +0000353 moveStateToNextToken(State);
354 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000355
Daniel Jasper20409152012-12-04 14:54:30 +0000356 /// \brief Mark the next token as consumed in \p State and modify its stacks
357 /// accordingly.
358 void moveStateToNextToken(IndentState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000359 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000360 unsigned ParenLevel = State.Indent.size() - 1;
361
Daniel Jasper26f7e782013-01-08 14:56:18 +0000362 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000363 State.FirstLessLess[ParenLevel] = State.Column;
364
Daniel Jasper26f7e782013-01-08 14:56:18 +0000365 State.Column += Current.FormatTok.TokenLength;
Daniel Jasper20409152012-12-04 14:54:30 +0000366
Daniel Jaspercf225b62012-12-24 13:43:52 +0000367 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000368 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000369 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
370 Current.is(tok::l_brace) ||
371 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper20409152012-12-04 14:54:30 +0000372 State.Indent.push_back(4 + State.LastSpace.back());
373 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000374 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000375 }
376
Daniel Jaspercf225b62012-12-24 13:43:52 +0000377 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000378 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000379 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
380 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
381 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000382 State.Indent.pop_back();
383 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000384 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000385 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000386 if (State.NextToken->Children.empty())
387 State.NextToken = NULL;
388 else
389 State.NextToken = &State.NextToken->Children[0];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390 }
391
Nico Weberdecf7bc2013-01-07 15:15:29 +0000392 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000393 unsigned splitPenalty(const AnnotatedToken &Tok) {
394 const AnnotatedToken &Left = Tok;
395 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000396
397 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000398 if (RootToken.is(tok::kw_for) &&
399 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000400 return 20;
401
Daniel Jasper26f7e782013-01-08 14:56:18 +0000402 if (Left.is(tok::semi) || Left.is(tok::comma) ||
403 Left.ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000404 return 0;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000405 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000406 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000407
Daniel Jasper9c837d02013-01-09 07:06:56 +0000408 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
409 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000410 prec::Level Level = getPrecedence(Left);
411
412 // Breaking after an assignment leads to a bad result as the two sides of
413 // the assignment are visually very close together.
414 if (Level == prec::Assignment)
415 return 50;
416
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000417 if (Level != prec::Unknown)
418 return Level;
419
Daniel Jasper26f7e782013-01-08 14:56:18 +0000420 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000421 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000422
Daniel Jasperbac016b2012-12-03 18:12:45 +0000423 return 3;
424 }
425
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000426 unsigned getColumnLimit() {
427 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
428 }
429
Daniel Jasperbac016b2012-12-03 18:12:45 +0000430 /// \brief Calculate the number of lines needed to format the remaining part
431 /// of the unwrapped line.
432 ///
433 /// Assumes the formatting so far has led to
434 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
435 /// added after the previous token.
436 ///
437 /// \param StopAt is used for optimization. If we can determine that we'll
438 /// definitely need at least \p StopAt additional lines, we already know of a
439 /// better solution.
440 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
441 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000442 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 return 0;
444
Daniel Jasper26f7e782013-01-08 14:56:18 +0000445 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000446 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000447 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000448 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000449 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000450 State.LineContainsContinuedForLoopSection)
451 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000452
Daniel Jasper33182dd2012-12-05 14:57:28 +0000453 unsigned CurrentPenalty = 0;
454 if (NewLine) {
455 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000456 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000457 } else {
458 if (State.Indent.size() < State.StartOfLineLevel)
459 CurrentPenalty += Parameters.PenaltyLevelDecrease *
460 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000461 }
462
Daniel Jasper20409152012-12-04 14:54:30 +0000463 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000464
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000465 // Exceeding column limit is bad, assign penalty.
466 if (State.Column > getColumnLimit()) {
467 unsigned ExcessCharacters = State.Column - getColumnLimit();
468 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
469 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000470
Daniel Jasperbac016b2012-12-03 18:12:45 +0000471 if (StopAt <= CurrentPenalty)
472 return UINT_MAX;
473 StopAt -= CurrentPenalty;
474
Daniel Jasperbac016b2012-12-03 18:12:45 +0000475 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000476 if (I != Memory.end()) {
477 // If this state has already been examined, we can safely return the
478 // previous result if we
479 // - have not hit the optimatization (and thus returned UINT_MAX) OR
480 // - are now computing for a smaller or equal StopAt.
481 unsigned SavedResult = I->second.first;
482 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000483 if (SavedResult != UINT_MAX)
484 return SavedResult + CurrentPenalty;
485 else if (StopAt <= SavedStopAt)
486 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000487 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488
489 unsigned NoBreak = calcPenalty(State, false, StopAt);
490 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
491 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000492
493 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
494 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000495 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000496
497 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000498 }
499
500 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
501 /// each \c FormatToken.
Daniel Jasper9c837d02013-01-09 07:06:56 +0000502 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000503 unsigned Spaces) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000504 Replaces.insert(tooling::Replacement(
Daniel Jasper9c837d02013-01-09 07:06:56 +0000505 SourceMgr, Tok.FormatTok.WhiteSpaceStart,
506 Tok.FormatTok.WhiteSpaceLength,
Manuel Klimek060143e2013-01-02 18:33:23 +0000507 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
508 }
509
510 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
511 /// backslashes to escape newlines inside a preprocessor directive.
512 ///
513 /// This function and \c replaceWhitespace have the same behavior if
514 /// \c Newlines == 0.
Daniel Jasper9c837d02013-01-09 07:06:56 +0000515 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Manuel Klimek060143e2013-01-02 18:33:23 +0000516 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000517 std::string NewLineText;
Manuel Klimek060143e2013-01-02 18:33:23 +0000518 if (NewLines > 0) {
Daniel Jaspercd162382013-01-07 13:26:07 +0000519 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
520 WhitespaceStartColumn);
Manuel Klimeka080a182013-01-02 16:30:12 +0000521 for (unsigned i = 0; i < NewLines; ++i) {
522 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
523 NewLineText += "\\\n";
524 Offset = 0;
525 }
526 }
Daniel Jasper9c837d02013-01-09 07:06:56 +0000527 Replaces.insert(
528 tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
529 Tok.FormatTok.WhiteSpaceLength,
530 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000531 }
532
533 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000534 /// of the \c UnwrappedLine if there was no structural parsing error.
535 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000536 unsigned formatFirstToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000537 const FormatToken &Tok = RootToken.FormatTok;
538 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
539 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000540
Daniel Jasper26f7e782013-01-08 14:56:18 +0000541 unsigned Newlines = std::min(Tok.NewlinesBefore,
Daniel Jaspercd162382013-01-07 13:26:07 +0000542 Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000543 if (Newlines == 0 && !Tok.IsFirst)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000544 Newlines = 1;
545 unsigned Indent = Line.Level * 2;
Nico Weber6092d4e2013-01-07 19:05:19 +0000546
547 bool IsAccessModifier = false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000548 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
549 RootToken.is(tok::kw_private))
Nico Weber6092d4e2013-01-07 19:05:19 +0000550 IsAccessModifier = true;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000551 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
552 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
553 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
554 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
555 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
Nico Weber6092d4e2013-01-07 19:05:19 +0000556 IsAccessModifier = true;
557
558 if (IsAccessModifier &&
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000559 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000560 Indent += Style.AccessModifierOffset;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000561 if (!Line.InPPDirective || Tok.HasUnescapedNewline)
562 replaceWhitespace(Tok, Newlines, Indent);
Manuel Klimek060143e2013-01-02 18:33:23 +0000563 else
Daniel Jasper26f7e782013-01-08 14:56:18 +0000564 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000565 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 }
567
568 FormatStyle Style;
569 SourceManager &SourceMgr;
570 const UnwrappedLine &Line;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000571 const unsigned PreviousEndOfLineColumn;
Daniel Jasper71607512013-01-07 10:48:50 +0000572 const LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000573 const AnnotatedToken &RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000575 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000576
Daniel Jasper33182dd2012-12-05 14:57:28 +0000577 // A map from an indent state to a pair (Result, Used-StopAt).
578 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
579 StateMap Memory;
580
Daniel Jasperbac016b2012-12-03 18:12:45 +0000581 OptimizationParameters Parameters;
582};
583
584/// \brief Determines extra information about the tokens comprising an
585/// \c UnwrappedLine.
586class TokenAnnotator {
587public:
588 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000589 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper26f7e782013-01-08 14:56:18 +0000590 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
591 RootToken(Line.RootToken) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 }
593
594 /// \brief A parser that gathers additional information about tokens.
595 ///
596 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
597 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
598 /// into template parameter lists.
599 class AnnotatingParser {
600 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000601 AnnotatingParser(AnnotatedToken &RootToken)
602 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000603 }
604
Daniel Jasper20409152012-12-04 14:54:30 +0000605 bool parseAngle() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000606 while (CurrentToken != NULL) {
607 if (CurrentToken->is(tok::greater)) {
608 CurrentToken->Type = TT_TemplateCloser;
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_paren) || CurrentToken->is(tok::r_square) ||
613 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000614 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000615 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
616 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
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 parseParens() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000625 while (CurrentToken != NULL) {
626 if (CurrentToken->is(tok::r_paren)) {
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_square) || 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 Jasper20409152012-12-04 14:54:30 +0000638 bool parseSquare() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000639 while (CurrentToken != NULL) {
640 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000641 next();
642 return true;
643 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000644 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000645 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000646 if (!consumeToken())
647 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000648 }
649 return false;
650 }
651
Daniel Jasper20409152012-12-04 14:54:30 +0000652 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000653 while (CurrentToken != NULL) {
654 if (CurrentToken->is(tok::colon)) {
655 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000656 next();
657 return true;
658 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000659 if (!consumeToken())
660 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000661 }
662 return false;
663 }
664
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000665 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000666 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
667 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000668 next();
669 if (!parseAngle())
670 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000671 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000672 parseLine();
673 return true;
674 }
675 return false;
676 }
677
Daniel Jasper1f42f112013-01-04 18:52:56 +0000678 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000679 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000680 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000681 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000682 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000683 if (!parseParens())
684 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000685 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
686 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000687 next();
688 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000689 break;
690 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000691 if (!parseSquare())
692 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000693 break;
694 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000695 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +0000696 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000697 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000698 Tok->Type = TT_BinaryOperator;
699 CurrentToken = Tok;
700 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000701 }
702 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000703 case tok::r_paren:
704 case tok::r_square:
705 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000706 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000707 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000708 break;
709 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000710 if (CurrentToken->is(tok::l_paren)) {
711 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000712 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000713 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
714 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000715 next();
716 }
717 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000718 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
719 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000720 next();
721 }
722 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000723 break;
724 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000725 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000727 case tok::kw_template:
728 parseTemplateDeclaration();
729 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000730 default:
731 break;
732 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000733 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 }
735
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000736 void parseIncludeDirective() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000737 while (CurrentToken != NULL) {
738 if (CurrentToken->is(tok::slash))
739 CurrentToken->Type = TT_DirectorySeparator;
740 else if (CurrentToken->is(tok::less))
741 CurrentToken->Type = TT_TemplateOpener;
742 else if (CurrentToken->is(tok::greater))
743 CurrentToken->Type = TT_TemplateCloser;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000744 next();
745 }
746 }
747
748 void parsePreprocessorDirective() {
749 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +0000750 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000751 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000752 // Hashes in the middle of a line can lead to any strange token
753 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000754 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000755 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000756 switch (
757 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000758 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000759 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000760 parseIncludeDirective();
761 break;
762 default:
763 break;
764 }
765 }
766
Daniel Jasper71607512013-01-07 10:48:50 +0000767 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000768 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000769 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000770 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000771 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000772 while (CurrentToken != NULL) {
773 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +0000774 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000775 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000776 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000777 }
Daniel Jasper71607512013-01-07 10:48:50 +0000778 if (KeywordVirtualFound)
779 return LT_VirtualFunctionDecl;
780 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000781 }
782
783 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000784 if (CurrentToken != NULL && !CurrentToken->Children.empty())
785 CurrentToken = &CurrentToken->Children[0];
786 else
787 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000788 }
789
790 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000791 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +0000792 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000793 };
794
Daniel Jasper26f7e782013-01-08 14:56:18 +0000795 void createAnnotatedTokens(AnnotatedToken &Current) {
796 if (!Current.FormatTok.Children.empty()) {
797 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
798 Current.Children.back().Parent = &Current;
799 createAnnotatedTokens(Current.Children.back());
800 }
801 }
Daniel Jasper71607512013-01-07 10:48:50 +0000802
Daniel Jasper26f7e782013-01-08 14:56:18 +0000803 void calculateExtraInformation(AnnotatedToken &Current) {
804 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
805
Manuel Klimek526ed112013-01-09 15:25:02 +0000806 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000807 Current.MustBreakBefore = true;
808 } else {
Manuel Klimek526ed112013-01-09 15:25:02 +0000809 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
810 TT_LineComment || (Current.is(tok::string_literal) &&
811 Current.Parent->is(tok::string_literal))) {
812 Current.MustBreakBefore = true;
813 } else if (Current.is(tok::at) && Current.Parent->Parent->is(tok::at)) {
814 // Don't put two objc's '@' on the same line. This could happen,
815 // as in, @optional @property ...
816 Current.MustBreakBefore = true;
817 } else {
818 Current.MustBreakBefore = false;
819 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000821 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
822
823 if (!Current.Children.empty())
824 calculateExtraInformation(Current.Children[0]);
825 }
826
827 bool annotate() {
828 createAnnotatedTokens(RootToken);
829
830 AnnotatingParser Parser(RootToken);
Daniel Jasper71607512013-01-07 10:48:50 +0000831 CurrentLineType = Parser.parseLine();
832 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000833 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000834
Daniel Jasper26f7e782013-01-08 14:56:18 +0000835 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +0000836
Daniel Jasper26f7e782013-01-08 14:56:18 +0000837 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasper71607512013-01-07 10:48:50 +0000838 CurrentLineType = LT_ObjCMethodDecl;
839
Daniel Jasper26f7e782013-01-08 14:56:18 +0000840 if (!RootToken.Children.empty())
841 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000842 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000843 }
844
Daniel Jasper71607512013-01-07 10:48:50 +0000845 LineType getLineType() {
846 return CurrentLineType;
847 }
848
Daniel Jasper26f7e782013-01-08 14:56:18 +0000849 const AnnotatedToken &getRootToken() {
850 return RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000851 }
852
853private:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000854 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
855 if (getPrecedence(Current) == prec::Assignment ||
856 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
857 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858
Daniel Jasper26f7e782013-01-08 14:56:18 +0000859 if (Current.Type == TT_Unknown) {
860 if (Current.is(tok::star) || Current.is(tok::amp)) {
861 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +0000862 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
863 Current.is(tok::caret)) {
864 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +0000865 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
866 Current.Type = determineIncrementUsage(Current);
867 } else if (Current.is(tok::exclaim)) {
868 Current.Type = TT_UnaryOperator;
869 } else if (isBinaryOperator(Current)) {
870 Current.Type = TT_BinaryOperator;
871 } else if (Current.is(tok::comment)) {
872 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
873 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +0000874 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000875 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000876 else
Daniel Jasper26f7e782013-01-08 14:56:18 +0000877 Current.Type = TT_BlockComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000878 }
879 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000880
881 if (!Current.Children.empty())
882 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000883 }
884
Daniel Jasper26f7e782013-01-08 14:56:18 +0000885 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000886 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000887 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000888 }
889
Daniel Jasper26f7e782013-01-08 14:56:18 +0000890 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
891 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000892 return TT_UnaryOperator;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000893 if (Tok.Children.size() == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000894 return TT_Unknown;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000895 const FormatToken &PrevToken = Tok.Parent->FormatTok;
896 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000897
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000898 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
899 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000900 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +0000901 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000902
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000903 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000904 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
905 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
906 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
907 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000908 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000909
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000910 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
911 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000912 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000913
Daniel Jasper112fb272012-12-05 07:51:39 +0000914 // It is very unlikely that we are going to find a pointer or reference type
915 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000916 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000917 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000918
Daniel Jasper71607512013-01-07 10:48:50 +0000919 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000920 }
921
Daniel Jasper886568d2013-01-09 08:36:49 +0000922 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000923 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000924 if (Tok.Parent == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +0000925 return TT_ObjCMethodSpecifier;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000926
927 // Use heuristics to recognize unary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000928 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
929 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
930 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
931 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case))
Daniel Jasper71607512013-01-07 10:48:50 +0000932 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000933
934 // There can't be to consecutive binary operators.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000935 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +0000936 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000937
938 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +0000939 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000940 }
941
942 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000943 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
944 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +0000945 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000946
Daniel Jasper71607512013-01-07 10:48:50 +0000947 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000948 }
949
Daniel Jasper26f7e782013-01-08 14:56:18 +0000950 bool spaceRequiredBetween(const AnnotatedToken &Left,
951 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +0000952 if (Right.is(tok::hashhash))
953 return Left.is(tok::hash);
954 if (Left.is(tok::hashhash) || Left.is(tok::hash))
955 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +0000956 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
957 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000958 if (Left.is(tok::kw_template) && Right.is(tok::less))
959 return true;
960 if (Left.is(tok::arrow) || Right.is(tok::arrow))
961 return false;
962 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
963 return false;
Nico Webercb4d6902013-01-08 19:40:21 +0000964 if (Left.is(tok::at) &&
965 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
966 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
967 Right.is(tok::l_paren) || Right.is(tok::l_brace)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000968 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000969 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
970 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000971 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000972 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000973 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
974 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000975 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +0000976 return Right.FormatTok.Tok.isLiteral() ||
977 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978 if (Right.is(tok::star) && Left.is(tok::l_paren))
979 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000980 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
981 Right.is(tok::r_square))
982 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000983 if (Left.is(tok::coloncolon) ||
984 (Right.is(tok::coloncolon) &&
985 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000986 return false;
987 if (Left.is(tok::period) || Right.is(tok::period))
988 return false;
989 if (Left.is(tok::colon) || Right.is(tok::colon))
990 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000991 if (Left.is(tok::l_paren))
992 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000993 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000994 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000995 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
996 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasperba3d3072013-01-02 17:21:36 +0000997 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000998 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000999 if (Left.is(tok::at) &&
1000 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001001 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001002 return true;
1003 }
1004
Daniel Jasper26f7e782013-01-08 14:56:18 +00001005 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperda927712013-01-07 15:36:15 +00001006 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001007 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1008 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001009 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001010 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001011 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001012 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperda927712013-01-07 15:36:15 +00001013 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001014 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001015 // Don't space between ')' and <id>
1016 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001017 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001018 // Don't space between ':' and '('
1019 return false;
1020 }
1021
Daniel Jasper26f7e782013-01-08 14:56:18 +00001022 if (Tok.Type == TT_CtorInitializerColon)
Daniel Jasperda927712013-01-07 15:36:15 +00001023 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001024 if (Tok.Type == TT_OverloadedOperator)
1025 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
1026 Tok.is(tok::kw_delete);
1027 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001028 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001029 if (Tok.is(tok::colon))
1030 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
1031 if (Tok.Parent->Type == TT_UnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001032 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001033 if (Tok.Type == TT_UnaryOperator)
1034 return Tok.Parent->isNot(tok::l_paren) &&
1035 Tok.Parent->isNot(tok::l_square);
1036 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1037 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001038 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1039 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001040 if (Tok.Type == TT_DirectorySeparator ||
1041 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperda927712013-01-07 15:36:15 +00001042 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001043 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001044 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001045 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001046 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001047 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001048 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001049 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001050 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001051 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001052 }
1053
Daniel Jasper26f7e782013-01-08 14:56:18 +00001054 bool canBreakBefore(const AnnotatedToken &Right) {
1055 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperda927712013-01-07 15:36:15 +00001056 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001057 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1058 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001059 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001060 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1061 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001062 // Don't break this identifier as ':' or identifier
1063 // before it will break.
1064 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001065 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1066 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001067 // Don't break at ':' if identifier before it can beak.
1068 return false;
1069 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001070 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001071 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001072 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001073 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001074 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001075 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001076 return false;
1077
Daniel Jasper043835a2013-01-09 09:33:39 +00001078 if (Right.is(tok::comment))
1079 return !Right.Children.empty();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001080 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasper043835a2013-01-09 09:33:39 +00001081 Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001082 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001083 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1084 Left.is(tok::comma) || Right.is(tok::lessless) ||
1085 Right.is(tok::arrow) || Right.is(tok::period) ||
1086 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper9c837d02013-01-09 07:06:56 +00001087 Left.is(tok::l_brace) || Left.is(tok::question) ||
1088 Left.Type == TT_ConditionalExpr ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001089 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001090 }
1091
Daniel Jasperbac016b2012-12-03 18:12:45 +00001092 FormatStyle Style;
1093 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001094 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001095 LineType CurrentLineType;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001096 AnnotatedToken RootToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001097};
1098
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001099class LexerBasedFormatTokenSource : public FormatTokenSource {
1100public:
1101 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001102 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001103 IdentTable(Lex.getLangOpts()) {
1104 Lex.SetKeepWhitespaceMode(true);
1105 }
1106
1107 virtual FormatToken getNextToken() {
1108 if (GreaterStashed) {
1109 FormatTok.NewlinesBefore = 0;
1110 FormatTok.WhiteSpaceStart =
1111 FormatTok.Tok.getLocation().getLocWithOffset(1);
1112 FormatTok.WhiteSpaceLength = 0;
1113 GreaterStashed = false;
1114 return FormatTok;
1115 }
1116
1117 FormatTok = FormatToken();
1118 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001119 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001120 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001121 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1122 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001123
1124 // Consume and record whitespace until we find a significant token.
1125 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001126 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001127 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1128 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001129 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1130
1131 if (FormatTok.Tok.is(tok::eof))
1132 return FormatTok;
1133 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001134 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001135 }
Manuel Klimek95419382013-01-07 07:56:50 +00001136
1137 // Now FormatTok is the next non-whitespace token.
1138 FormatTok.TokenLength = Text.size();
1139
Manuel Klimekd4397b92013-01-04 23:34:14 +00001140 // In case the token starts with escaped newlines, we want to
1141 // take them into account as whitespace - this pattern is quite frequent
1142 // in macro definitions.
1143 // FIXME: What do we want to do with other escaped spaces, and escaped
1144 // spaces or newlines in the middle of tokens?
1145 // FIXME: Add a more explicit test.
1146 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001147 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001148 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001149 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001150 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001151 }
1152
1153 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001154 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001155 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001156 FormatTok.Tok.setKind(Info.getTokenID());
1157 }
1158
1159 if (FormatTok.Tok.is(tok::greatergreater)) {
1160 FormatTok.Tok.setKind(tok::greater);
1161 GreaterStashed = true;
1162 }
1163
1164 return FormatTok;
1165 }
1166
1167private:
1168 FormatToken FormatTok;
1169 bool GreaterStashed;
1170 Lexer &Lex;
1171 SourceManager &SourceMgr;
1172 IdentifierTable IdentTable;
1173
1174 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001175 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001176 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1177 Tok.getLength());
1178 }
1179};
1180
Daniel Jasperbac016b2012-12-03 18:12:45 +00001181class Formatter : public UnwrappedLineConsumer {
1182public:
1183 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1184 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001185 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001186 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001187 }
1188
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001189 virtual ~Formatter() {
1190 }
1191
Daniel Jasperbac016b2012-12-03 18:12:45 +00001192 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001193 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1194 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001195 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001196 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001197 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1198 E = UnwrappedLines.end();
1199 I != E; ++I)
Daniel Jaspercd162382013-01-07 13:26:07 +00001200 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1201 PreviousEndOfLineColumn);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001202 return Replaces;
1203 }
1204
1205private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001206 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001207 UnwrappedLines.push_back(TheLine);
1208 }
1209
Manuel Klimekd4397b92013-01-04 23:34:14 +00001210 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1211 unsigned PreviousEndOfLineColumn) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001212 const FormatToken *First = &TheLine.RootToken;
1213 const FormatToken *Last = First;
1214 while (!Last->Children.empty())
1215 Last = &Last->Children.back();
Daniel Jaspercd162382013-01-07 13:26:07 +00001216 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001217 First->Tok.getLocation(),
1218 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001219
1220 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1221 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1222 Ranges[i].getBegin()) ||
1223 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1224 LineRange.getBegin()))
1225 continue;
1226
Manuel Klimek6cf58142013-01-07 08:54:53 +00001227 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasper1f42f112013-01-04 18:52:56 +00001228 if (!Annotator.annotate())
Manuel Klimekd4397b92013-01-04 23:34:14 +00001229 break;
1230 UnwrappedLineFormatter Formatter(
1231 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
Daniel Jasper26f7e782013-01-08 14:56:18 +00001232 Annotator.getLineType(), Annotator.getRootToken(), Replaces,
Daniel Jasper71607512013-01-07 10:48:50 +00001233 StructuralError);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001234 return Formatter.format();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001235 }
Manuel Klimekd4397b92013-01-04 23:34:14 +00001236 // If we did not reformat this unwrapped line, the column at the end of the
1237 // last token is unchanged - thus, we can calculate the end of the last
1238 // token, and return the result.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001239 return SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1240 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
Manuel Klimekd4397b92013-01-04 23:34:14 +00001241 Lex.getLangOpts()) -
1242 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001243 }
1244
1245 FormatStyle Style;
1246 Lexer &Lex;
1247 SourceManager &SourceMgr;
1248 tooling::Replacements Replaces;
1249 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001250 std::vector<UnwrappedLine> UnwrappedLines;
1251 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001252};
1253
1254tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1255 SourceManager &SourceMgr,
1256 std::vector<CharSourceRange> Ranges) {
1257 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1258 return formatter.format();
1259}
1260
Daniel Jaspercd162382013-01-07 13:26:07 +00001261} // namespace format
1262} // namespace clang