blob: 7d135d9b175a63c1cc8f979d42447e576b6ea84b [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 Jasperbac016b2012-12-03 18:12:45 +000021#include "clang/Basic/SourceManager.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
24
Daniel Jasper8822d3a2012-12-04 13:02:32 +000025#include <string>
26
Daniel Jasperbac016b2012-12-03 18:12:45 +000027namespace clang {
28namespace format {
29
30// FIXME: Move somewhere sane.
31struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000032 enum TokenType {
33 TT_Unknown,
34 TT_TemplateOpener,
35 TT_TemplateCloser,
36 TT_BinaryOperator,
37 TT_UnaryOperator,
Daniel Jasper98e6b4a2012-12-21 09:41:31 +000038 TT_TrailingUnaryOperator,
Daniel Jasper33182dd2012-12-05 14:57:28 +000039 TT_OverloadedOperator,
40 TT_PointerOrReference,
41 TT_ConditionalExpr,
Daniel Jasper1321eb52012-12-18 21:05:13 +000042 TT_CtorInitializerColon,
Daniel Jasper33182dd2012-12-05 14:57:28 +000043 TT_LineComment,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000044 TT_BlockComment,
Daniel Jaspercd1a32b2012-12-21 17:58:39 +000045 TT_DirectorySeparator,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000046 TT_ObjCMethodSpecifier
Daniel Jasper33182dd2012-12-05 14:57:28 +000047 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000048
49 TokenType Type;
50
Daniel Jasperbac016b2012-12-03 18:12:45 +000051 bool SpaceRequiredBefore;
52 bool CanBreakBefore;
53 bool MustBreakBefore;
54};
55
Daniel Jaspercf225b62012-12-24 13:43:52 +000056static prec::Level getPrecedence(const FormatToken &Tok) {
57 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
58}
59
Daniel Jasperbac016b2012-12-03 18:12:45 +000060using llvm::MutableArrayRef;
61
62FormatStyle getLLVMStyle() {
63 FormatStyle LLVMStyle;
64 LLVMStyle.ColumnLimit = 80;
65 LLVMStyle.MaxEmptyLinesToKeep = 1;
66 LLVMStyle.PointerAndReferenceBindToType = false;
67 LLVMStyle.AccessModifierOffset = -2;
68 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000069 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000070 return LLVMStyle;
71}
72
73FormatStyle getGoogleStyle() {
74 FormatStyle GoogleStyle;
75 GoogleStyle.ColumnLimit = 80;
76 GoogleStyle.MaxEmptyLinesToKeep = 1;
77 GoogleStyle.PointerAndReferenceBindToType = true;
78 GoogleStyle.AccessModifierOffset = -1;
79 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000080 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000081 return GoogleStyle;
82}
83
84struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000085 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +000086 unsigned PenaltyLevelDecrease;
Daniel Jasperbac016b2012-12-03 18:12:45 +000087};
88
89class UnwrappedLineFormatter {
90public:
91 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
92 const UnwrappedLine &Line,
93 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000094 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000095 : Style(Style), SourceMgr(SourceMgr), Line(Line),
96 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000097 StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +000098 Parameters.PenaltyIndentLevel = 15;
Daniel Jaspera4974cf2012-12-24 16:43:00 +000099 Parameters.PenaltyLevelDecrease = 10;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000100 }
101
102 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000103 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000104 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000105
106 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000107 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000108 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000109 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000110 State.Indent.push_back(Indent + 4);
111 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000112 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000113 State.ForLoopVariablePos = 0;
114 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000115 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000116
117 // The first token has already been indented and thus consumed.
118 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000119
Daniel Jasper1321eb52012-12-18 21:05:13 +0000120 // Check whether the UnwrappedLine can be put onto a single line. If so,
121 // this is bound to be the optimal solution (by definition) and we don't
122 // need to analyze the entire solution space.
123 unsigned Columns = State.Column;
124 bool FitsOnALine = true;
125 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
126 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
127 Line.Tokens[i].Tok.getLength();
128 // A special case for the colon of a constructor initializer as this only
129 // needs to be put on a new line if the line needs to be split.
130 if (Columns > Style.ColumnLimit ||
131 (Annotations[i].MustBreakBefore &&
132 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
133 FitsOnALine = false;
134 break;
135 }
136 }
137
Daniel Jasperbac016b2012-12-03 18:12:45 +0000138 // Start iterating at 1 as we have correctly formatted of Token #0 above.
139 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000140 if (FitsOnALine) {
141 addTokenToState(false, false, State);
142 } else {
143 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
144 unsigned Break = calcPenalty(State, true, NoBreak);
145 addTokenToState(Break < NoBreak, false, State);
146 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000147 }
148 }
149
150private:
151 /// \brief The current state when indenting a unwrapped line.
152 ///
153 /// As the indenting tries different combinations this is copied by value.
154 struct IndentState {
155 /// \brief The number of used columns in the current line.
156 unsigned Column;
157
158 /// \brief The number of tokens already consumed.
159 unsigned ConsumedTokens;
160
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000161 /// \brief The parenthesis level of the first token on the current line.
162 unsigned StartOfLineLevel;
163
Daniel Jasperbac016b2012-12-03 18:12:45 +0000164 /// \brief The position to which a specific parenthesis level needs to be
165 /// indented.
166 std::vector<unsigned> Indent;
167
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000168 /// \brief The position of the last space on each level.
169 ///
170 /// Used e.g. to break like:
171 /// functionCall(Parameter, otherCall(
172 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000173 std::vector<unsigned> LastSpace;
174
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000175 /// \brief The position the first "<<" operator encountered on each level.
176 ///
177 /// Used to align "<<" operators. 0 if no such operator has been encountered
178 /// on a level.
179 std::vector<unsigned> FirstLessLess;
180
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000181 /// \brief The column of the first variable in a for-loop declaration.
182 ///
183 /// Used to align the second variable if necessary.
184 unsigned ForLoopVariablePos;
185
186 /// \brief \c true if this line contains a continued for-loop section.
187 bool LineContainsContinuedForLoopSection;
188
Daniel Jasperbac016b2012-12-03 18:12:45 +0000189 /// \brief Comparison operator to be able to used \c IndentState in \c map.
190 bool operator<(const IndentState &Other) const {
191 if (Other.ConsumedTokens != ConsumedTokens)
192 return Other.ConsumedTokens > ConsumedTokens;
193 if (Other.Column != Column)
194 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000195 if (Other.StartOfLineLevel != StartOfLineLevel)
196 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000197 if (Other.Indent.size() != Indent.size())
198 return Other.Indent.size() > Indent.size();
199 for (int i = 0, e = Indent.size(); i != e; ++i) {
200 if (Other.Indent[i] != Indent[i])
201 return Other.Indent[i] > Indent[i];
202 }
203 if (Other.LastSpace.size() != LastSpace.size())
204 return Other.LastSpace.size() > LastSpace.size();
205 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
206 if (Other.LastSpace[i] != LastSpace[i])
207 return Other.LastSpace[i] > LastSpace[i];
208 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000209 if (Other.FirstLessLess.size() != FirstLessLess.size())
210 return Other.FirstLessLess.size() > FirstLessLess.size();
211 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
212 if (Other.FirstLessLess[i] != FirstLessLess[i])
213 return Other.FirstLessLess[i] > FirstLessLess[i];
214 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000215 if (Other.ForLoopVariablePos != ForLoopVariablePos)
216 return Other.ForLoopVariablePos < ForLoopVariablePos;
217 if (Other.LineContainsContinuedForLoopSection !=
218 LineContainsContinuedForLoopSection)
219 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000220 return false;
221 }
222 };
223
Daniel Jasper20409152012-12-04 14:54:30 +0000224 /// \brief Appends the next token to \p State and updates information
225 /// necessary for indentation.
226 ///
227 /// Puts the token on the current line if \p Newline is \c true and adds a
228 /// line break and necessary indentation otherwise.
229 ///
230 /// If \p DryRun is \c false, also creates and stores the required
231 /// \c Replacement.
232 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000233 unsigned Index = State.ConsumedTokens;
234 const FormatToken &Current = Line.Tokens[Index];
235 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000236 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000237
238 if (Newline) {
239 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000240 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000241 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000242 } else if (Current.Tok.is(tok::lessless) &&
243 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000244 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000245 } else if (ParenLevel != 0 &&
246 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
247 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000248 // Indent and extra 4 spaces after '=' as it continues an expression.
249 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000251 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
252 Previous.Tok.is(tok::comma)) {
253 State.Column = State.ForLoopVariablePos;
254 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000255 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000256 }
257
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000258 State.StartOfLineLevel = ParenLevel + 1;
259
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000260 if (Line.Tokens[0].Tok.is(tok::kw_for))
261 State.LineContainsContinuedForLoopSection =
262 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000263
Daniel Jasperbac016b2012-12-03 18:12:45 +0000264 if (!DryRun)
265 replaceWhitespace(Current, 1, State.Column);
266
Daniel Jaspera88bb452012-12-04 10:50:12 +0000267 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000268 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000269 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
270 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000271 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000273 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
274 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
275
Daniel Jasperbac016b2012-12-03 18:12:45 +0000276 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
277 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
278 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000279
Daniel Jasperbac016b2012-12-03 18:12:45 +0000280 if (!DryRun)
281 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000282
Daniel Jaspercf225b62012-12-24 13:43:52 +0000283 // FIXME: Look into using this alignment at other ParenLevels.
284 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
285 Previous.Tok.is(tok::kw_return)))
286 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper20409152012-12-04 14:54:30 +0000287 if (Previous.Tok.is(tok::l_paren) ||
288 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000289 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000290
Daniel Jasperbac016b2012-12-03 18:12:45 +0000291 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000292 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000293 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000294 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000295 }
Daniel Jasper20409152012-12-04 14:54:30 +0000296 moveStateToNextToken(State);
297 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000298
Daniel Jasper20409152012-12-04 14:54:30 +0000299 /// \brief Mark the next token as consumed in \p State and modify its stacks
300 /// accordingly.
301 void moveStateToNextToken(IndentState &State) {
302 unsigned Index = State.ConsumedTokens;
303 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000304 unsigned ParenLevel = State.Indent.size() - 1;
305
306 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
307 State.FirstLessLess[ParenLevel] = State.Column;
308
309 State.Column += Current.Tok.getLength();
Daniel Jasper20409152012-12-04 14:54:30 +0000310
Daniel Jaspercf225b62012-12-24 13:43:52 +0000311 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000312 // prepare for the following tokens.
313 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000314 Current.Tok.is(tok::l_brace) ||
Daniel Jasper20409152012-12-04 14:54:30 +0000315 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
316 State.Indent.push_back(4 + State.LastSpace.back());
317 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000318 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000319 }
320
Daniel Jaspercf225b62012-12-24 13:43:52 +0000321 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000322 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000323 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000324 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jaspera88bb452012-12-04 10:50:12 +0000325 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000326 State.Indent.pop_back();
327 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000328 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 }
330
331 ++State.ConsumedTokens;
332 }
333
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000334 /// \brief Calculate the panelty for splitting after the token at \p Index.
335 unsigned splitPenalty(unsigned Index) {
336 assert(Index < Line.Tokens.size() &&
337 "Tried to calculate penalty for splitting after the last token");
338 const FormatToken &Left = Line.Tokens[Index];
339 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000340
341 // In for-loops, prefer breaking at ',' and ';'.
342 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
343 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
344 return 20;
345
Daniel Jasper1321eb52012-12-18 21:05:13 +0000346 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000347 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000348 if (Left.Tok.is(tok::l_paren))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000349 return 2;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000350
Daniel Jaspercf225b62012-12-24 13:43:52 +0000351 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000352 if (Level != prec::Unknown)
353 return Level;
354
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000355 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000356 return 50;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000357
Daniel Jasperbac016b2012-12-03 18:12:45 +0000358 return 3;
359 }
360
361 /// \brief Calculate the number of lines needed to format the remaining part
362 /// of the unwrapped line.
363 ///
364 /// Assumes the formatting so far has led to
365 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
366 /// added after the previous token.
367 ///
368 /// \param StopAt is used for optimization. If we can determine that we'll
369 /// definitely need at least \p StopAt additional lines, we already know of a
370 /// better solution.
371 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
372 // We are at the end of the unwrapped line, so we don't need any more lines.
373 if (State.ConsumedTokens >= Line.Tokens.size())
374 return 0;
375
376 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
377 return UINT_MAX;
378 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
379 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000380 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
381 State.LineContainsContinuedForLoopSection)
382 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000383
Daniel Jasper33182dd2012-12-05 14:57:28 +0000384 unsigned CurrentPenalty = 0;
385 if (NewLine) {
386 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper1321eb52012-12-18 21:05:13 +0000387 splitPenalty(State.ConsumedTokens - 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000388 } else {
389 if (State.Indent.size() < State.StartOfLineLevel)
390 CurrentPenalty += Parameters.PenaltyLevelDecrease *
391 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000392 }
393
Daniel Jasper20409152012-12-04 14:54:30 +0000394 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000395
396 // Exceeding column limit is bad.
397 if (State.Column > Style.ColumnLimit)
398 return UINT_MAX;
399
Daniel Jasperbac016b2012-12-03 18:12:45 +0000400 if (StopAt <= CurrentPenalty)
401 return UINT_MAX;
402 StopAt -= CurrentPenalty;
403
Daniel Jasperbac016b2012-12-03 18:12:45 +0000404 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000405 if (I != Memory.end()) {
406 // If this state has already been examined, we can safely return the
407 // previous result if we
408 // - have not hit the optimatization (and thus returned UINT_MAX) OR
409 // - are now computing for a smaller or equal StopAt.
410 unsigned SavedResult = I->second.first;
411 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000412 if (SavedResult != UINT_MAX)
413 return SavedResult + CurrentPenalty;
414 else if (StopAt <= SavedStopAt)
415 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000416 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000417
418 unsigned NoBreak = calcPenalty(State, false, StopAt);
419 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
420 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000421
422 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
423 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000424 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000425
426 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000427 }
428
429 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
430 /// each \c FormatToken.
431 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
432 unsigned Spaces) {
433 Replaces.insert(tooling::Replacement(
434 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
435 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
436 }
437
438 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000439 /// of the \c UnwrappedLine if there was no structural parsing error.
440 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000441 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000442 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000443 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
444 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
445
446 unsigned Newlines =
447 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
448 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
449 if (Newlines == 0 && Offset != 0)
450 Newlines = 1;
451 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000452 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
453 Token.Tok.is(tok::kw_private)) &&
454 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000455 Indent += Style.AccessModifierOffset;
456 replaceWhitespace(Token, Newlines, Indent);
457 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000458 }
459
460 FormatStyle Style;
461 SourceManager &SourceMgr;
462 const UnwrappedLine &Line;
463 const std::vector<TokenAnnotation> &Annotations;
464 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000465 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000466
Daniel Jasper33182dd2012-12-05 14:57:28 +0000467 // A map from an indent state to a pair (Result, Used-StopAt).
468 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
469 StateMap Memory;
470
Daniel Jasperbac016b2012-12-03 18:12:45 +0000471 OptimizationParameters Parameters;
472};
473
474/// \brief Determines extra information about the tokens comprising an
475/// \c UnwrappedLine.
476class TokenAnnotator {
477public:
478 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
479 SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000480 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000481 }
482
483 /// \brief A parser that gathers additional information about tokens.
484 ///
485 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
486 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
487 /// into template parameter lists.
488 class AnnotatingParser {
489 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000490 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000491 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000492 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000493 }
494
Daniel Jasper20409152012-12-04 14:54:30 +0000495 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000496 while (Index < Tokens.size()) {
497 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000498 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000499 next();
500 return true;
501 }
502 if (Tokens[Index].Tok.is(tok::r_paren) ||
503 Tokens[Index].Tok.is(tok::r_square))
504 return false;
505 if (Tokens[Index].Tok.is(tok::pipepipe) ||
506 Tokens[Index].Tok.is(tok::ampamp) ||
507 Tokens[Index].Tok.is(tok::question) ||
508 Tokens[Index].Tok.is(tok::colon))
509 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000510 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000511 }
512 return false;
513 }
514
Daniel Jasper20409152012-12-04 14:54:30 +0000515 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000516 while (Index < Tokens.size()) {
517 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000518 next();
519 return true;
520 }
521 if (Tokens[Index].Tok.is(tok::r_square))
522 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000523 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000524 }
525 return false;
526 }
527
Daniel Jasper20409152012-12-04 14:54:30 +0000528 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000529 while (Index < Tokens.size()) {
530 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000531 next();
532 return true;
533 }
534 if (Tokens[Index].Tok.is(tok::r_paren))
535 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000536 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000537 }
538 return false;
539 }
540
Daniel Jasper20409152012-12-04 14:54:30 +0000541 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000542 while (Index < Tokens.size()) {
543 if (Tokens[Index].Tok.is(tok::colon)) {
544 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
545 next();
546 return true;
547 }
Daniel Jasper20409152012-12-04 14:54:30 +0000548 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000549 }
550 return false;
551 }
552
Daniel Jasper20409152012-12-04 14:54:30 +0000553 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000554 unsigned CurrentIndex = Index;
555 next();
556 switch (Tokens[CurrentIndex].Tok.getKind()) {
557 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000558 parseParens();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000559 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
560 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
561 next();
562 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000563 break;
564 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000565 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 break;
567 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000568 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000569 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
570 else {
571 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
572 Index = CurrentIndex + 1;
573 }
574 break;
575 case tok::greater:
576 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
577 break;
578 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000579 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000580 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000581 next();
582 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
583 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
584 next();
585 }
586 } else {
587 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
588 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
589 next();
590 }
591 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 break;
593 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000594 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000595 break;
596 default:
597 break;
598 }
599 }
600
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000601 void parseIncludeDirective() {
602 while (Index < Tokens.size()) {
603 if (Tokens[Index].Tok.is(tok::slash))
604 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
605 else if (Tokens[Index].Tok.is(tok::less))
606 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
607 else if (Tokens[Index].Tok.is(tok::greater))
608 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
609 next();
610 }
611 }
612
613 void parsePreprocessorDirective() {
614 next();
615 if (Index >= Tokens.size())
616 return;
617 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
618 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000619 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000620 parseIncludeDirective();
621 break;
622 default:
623 break;
624 }
625 }
626
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 void parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000628 if (Tokens[Index].Tok.is(tok::hash)) {
629 parsePreprocessorDirective();
630 return;
631 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000632 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000633 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 }
635 }
636
637 void next() {
638 ++Index;
639 }
640
641 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000642 const SmallVector<FormatToken, 16> &Tokens;
643 std::vector<TokenAnnotation> &Annotations;
644 unsigned Index;
645 };
646
647 void annotate() {
648 Annotations.clear();
649 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
650 Annotations.push_back(TokenAnnotation());
651 }
652
Manuel Klimek0be4b362012-12-03 20:55:42 +0000653 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000654 Parser.parseLine();
655
656 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000657 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000658 (Line.Tokens.size() > 0 &&
659 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000660 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
661 TokenAnnotation &Annotation = Annotations[i];
662
663 Annotation.CanBreakBefore =
664 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
665
Daniel Jasper1321eb52012-12-18 21:05:13 +0000666 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
667 Annotation.MustBreakBefore = true;
668 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000669 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
670 Annotation.SpaceRequiredBefore =
671 Line.Tokens[i].Tok.is(tok::identifier) || Line.Tokens[i].Tok.is(
672 tok::kw_new) || Line.Tokens[i].Tok.is(tok::kw_delete);
673 } else if (
674 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
675 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000676 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
677 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
678 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000679 Annotation.CanBreakBefore = true;
680 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000681 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
682 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
683 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000684 // Don't break this identifier as ':' or identifier
685 // before it will break.
686 Annotation.CanBreakBefore = false;
687 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000688 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000689 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000690 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000691 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000692 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000693 Annotation.SpaceRequiredBefore =
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000694 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
695 (i != e - 1);
696 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000697 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
698 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000699 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000700 } else if (
701 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000702 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000703 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000704 Annotation.SpaceRequiredBefore = false;
705 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
706 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000707 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
708 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000709 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
710 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000711 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000712 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000713 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714 else
715 Annotation.SpaceRequiredBefore = false;
716 } else if (
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000717 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
718 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
719 Annotation.SpaceRequiredBefore = false;
720 } else if (
Daniel Jasperbac016b2012-12-03 18:12:45 +0000721 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
722 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
723 Annotation.SpaceRequiredBefore = true;
724 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000725 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 Line.Tokens[i].Tok.is(tok::l_paren)) {
727 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000728 } else if (Line.Tokens[i].Tok.is(tok::less) &&
729 Line.Tokens[0].Tok.is(tok::hash)) {
730 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000731 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
732 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000733 // Don't space between ')' and <id>
734 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000735 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
736 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000737 // Don't space between ':' and '('
738 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000739 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
740 Annotation.SpaceRequiredBefore = false;
741 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000742 Annotation.SpaceRequiredBefore =
743 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
744 }
745
746 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
747 (Line.Tokens[i].Tok.is(tok::string_literal) &&
748 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
749 Annotation.MustBreakBefore = true;
750 }
751
752 if (Annotation.MustBreakBefore)
753 Annotation.CanBreakBefore = true;
754 }
755 }
756
757 const std::vector<TokenAnnotation> &getAnnotations() {
758 return Annotations;
759 }
760
761private:
762 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000763 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000764 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
765 TokenAnnotation &Annotation = Annotations[i];
766 const FormatToken &Tok = Line.Tokens[i];
767
Daniel Jaspercf225b62012-12-24 13:43:52 +0000768 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000769 IsRHS = true;
770 else if (Tok.Tok.is(tok::kw_return))
771 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000772
Daniel Jasper675d2e32012-12-21 10:20:02 +0000773 if (Annotation.Type != TokenAnnotation::TT_Unknown)
774 continue;
775
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000776 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000777 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000778 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
779 Annotation.Type = determinePlusMinusUsage(i);
780 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
781 Annotation.Type = determineIncrementUsage(i);
782 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000784 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000785 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000786 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000787 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
788 Tok.Tok.getLength());
789 if (Data.startswith("//"))
790 Annotation.Type = TokenAnnotation::TT_LineComment;
791 else
792 Annotation.Type = TokenAnnotation::TT_BlockComment;
793 }
794 }
795 }
796
Daniel Jasperbac016b2012-12-03 18:12:45 +0000797 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000798 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000799 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000800 }
801
Daniel Jasper112fb272012-12-05 07:51:39 +0000802 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Nico Weber00d5a042012-12-23 01:07:46 +0000803 bool IsRHS) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000804 if (Index == Annotations.size())
805 return TokenAnnotation::TT_Unknown;
806
807 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
808 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
Nico Weber00d5a042012-12-23 01:07:46 +0000809 Line.Tokens[Index - 1].Tok.is(tok::kw_return) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000810 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
811 return TokenAnnotation::TT_UnaryOperator;
812
813 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000814 Line.Tokens[Index + 1].Tok.isLiteral() ||
815 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000816 return TokenAnnotation::TT_BinaryOperator;
817
Daniel Jasper112fb272012-12-05 07:51:39 +0000818 // It is very unlikely that we are going to find a pointer or reference type
819 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000820 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000821 return TokenAnnotation::TT_BinaryOperator;
822
Daniel Jasperbac016b2012-12-03 18:12:45 +0000823 return TokenAnnotation::TT_PointerOrReference;
824 }
825
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000826 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
827 // At the start of the line, +/- specific ObjectiveC method declarations.
828 if (Index == 0)
829 return TokenAnnotation::TT_ObjCMethodSpecifier;
830
831 // Use heuristics to recognize unary operators.
832 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
833 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
834 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
835 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
836 return TokenAnnotation::TT_UnaryOperator;
837
838 // There can't be to consecutive binary operators.
839 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
840 return TokenAnnotation::TT_UnaryOperator;
841
842 // Fall back to marking the token as binary operator.
843 return TokenAnnotation::TT_BinaryOperator;
844 }
845
846 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
847 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
848 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
849 return TokenAnnotation::TT_TrailingUnaryOperator;
850
851 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000852 }
853
854 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000855 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
856 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000857 if (Left.is(tok::kw_template) && Right.is(tok::less))
858 return true;
859 if (Left.is(tok::arrow) || Right.is(tok::arrow))
860 return false;
861 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
862 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000863 if (Left.is(tok::at) && Right.is(tok::identifier))
864 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000865 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
866 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000867 if (Right.is(tok::amp) || Right.is(tok::star))
868 return Left.isLiteral() ||
869 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
870 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000871 if (Left.is(tok::amp) || Left.is(tok::star))
872 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
873 if (Right.is(tok::star) && Left.is(tok::l_paren))
874 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
876 Right.is(tok::r_square))
877 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000878 if (Left.is(tok::coloncolon) ||
879 (Right.is(tok::coloncolon) &&
880 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000881 return false;
882 if (Left.is(tok::period) || Right.is(tok::period))
883 return false;
884 if (Left.is(tok::colon) || Right.is(tok::colon))
885 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000886 if (Left.is(tok::l_paren))
887 return false;
888 if (Left.is(tok::hash))
889 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000890 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000891 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
892 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
893 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
894 Left.isNot(tok::kw_typeof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000895 }
896 return true;
897 }
898
899 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000900 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
901 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000902 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000903 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
904 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
905 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
906 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
907 Left.Tok.is(tok::l_brace) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000908 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
909 }
910
911 const UnwrappedLine &Line;
912 FormatStyle Style;
913 SourceManager &SourceMgr;
914 std::vector<TokenAnnotation> Annotations;
915};
916
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000917class LexerBasedFormatTokenSource : public FormatTokenSource {
918public:
919 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000920 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000921 IdentTable(Lex.getLangOpts()) {
922 Lex.SetKeepWhitespaceMode(true);
923 }
924
925 virtual FormatToken getNextToken() {
926 if (GreaterStashed) {
927 FormatTok.NewlinesBefore = 0;
928 FormatTok.WhiteSpaceStart =
929 FormatTok.Tok.getLocation().getLocWithOffset(1);
930 FormatTok.WhiteSpaceLength = 0;
931 GreaterStashed = false;
932 return FormatTok;
933 }
934
935 FormatTok = FormatToken();
936 Lex.LexFromRawLexer(FormatTok.Tok);
937 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
938
939 // Consume and record whitespace until we find a significant token.
940 while (FormatTok.Tok.is(tok::unknown)) {
941 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
942 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
943
944 if (FormatTok.Tok.is(tok::eof))
945 return FormatTok;
946 Lex.LexFromRawLexer(FormatTok.Tok);
947 }
948
949 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000950 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
951 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000952 FormatTok.Tok.setKind(Info.getTokenID());
953 }
954
955 if (FormatTok.Tok.is(tok::greatergreater)) {
956 FormatTok.Tok.setKind(tok::greater);
957 GreaterStashed = true;
958 }
959
960 return FormatTok;
961 }
962
963private:
964 FormatToken FormatTok;
965 bool GreaterStashed;
966 Lexer &Lex;
967 SourceManager &SourceMgr;
968 IdentifierTable IdentTable;
969
970 /// Returns the text of \c FormatTok.
971 StringRef tokenText(Token &Tok) {
972 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
973 Tok.getLength());
974 }
975};
976
Daniel Jasperbac016b2012-12-03 18:12:45 +0000977class Formatter : public UnwrappedLineConsumer {
978public:
979 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
980 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000981 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000982 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000983 }
984
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000985 virtual ~Formatter() {
986 }
987
Daniel Jasperbac016b2012-12-03 18:12:45 +0000988 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000989 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
990 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000991 StructuralError = Parser.parse();
992 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
993 E = UnwrappedLines.end();
994 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000995 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000996 return Replaces;
997 }
998
999private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001000 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001001 UnwrappedLines.push_back(TheLine);
1002 }
1003
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001004 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001005 if (TheLine.Tokens.size() == 0)
1006 return;
1007
1008 CharSourceRange LineRange =
1009 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1010 TheLine.Tokens.back().Tok.getLocation());
1011
1012 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1013 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1014 Ranges[i].getBegin()) ||
1015 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1016 LineRange.getBegin()))
1017 continue;
1018
1019 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1020 Annotator.annotate();
1021 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001022 Annotator.getAnnotations(), Replaces,
1023 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001024 Formatter.format();
1025 return;
1026 }
1027 }
1028
1029 FormatStyle Style;
1030 Lexer &Lex;
1031 SourceManager &SourceMgr;
1032 tooling::Replacements Replaces;
1033 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001034 std::vector<UnwrappedLine> UnwrappedLines;
1035 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001036};
1037
1038tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1039 SourceManager &SourceMgr,
1040 std::vector<CharSourceRange> Ranges) {
1041 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1042 return formatter.format();
1043}
1044
1045} // namespace format
1046} // namespace clang