blob: 030e35e38db2a4a27136d993cc4be8acf568a14a [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"
22#include "clang/Lex/Lexer.h"
23
Daniel Jasper8822d3a2012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperbac016b2012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000031 enum TokenType {
32 TT_Unknown,
33 TT_TemplateOpener,
34 TT_TemplateCloser,
35 TT_BinaryOperator,
36 TT_UnaryOperator,
37 TT_OverloadedOperator,
38 TT_PointerOrReference,
39 TT_ConditionalExpr,
40 TT_LineComment,
41 TT_BlockComment
42 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000043
44 TokenType Type;
45
Daniel Jasperbac016b2012-12-03 18:12:45 +000046 bool SpaceRequiredBefore;
47 bool CanBreakBefore;
48 bool MustBreakBefore;
49};
50
51using llvm::MutableArrayRef;
52
53FormatStyle getLLVMStyle() {
54 FormatStyle LLVMStyle;
55 LLVMStyle.ColumnLimit = 80;
56 LLVMStyle.MaxEmptyLinesToKeep = 1;
57 LLVMStyle.PointerAndReferenceBindToType = false;
58 LLVMStyle.AccessModifierOffset = -2;
59 LLVMStyle.SplitTemplateClosingGreater = true;
60 return LLVMStyle;
61}
62
63FormatStyle getGoogleStyle() {
64 FormatStyle GoogleStyle;
65 GoogleStyle.ColumnLimit = 80;
66 GoogleStyle.MaxEmptyLinesToKeep = 1;
67 GoogleStyle.PointerAndReferenceBindToType = true;
68 GoogleStyle.AccessModifierOffset = -1;
69 GoogleStyle.SplitTemplateClosingGreater = false;
70 return GoogleStyle;
71}
72
73struct OptimizationParameters {
74 unsigned PenaltyExtraLine;
75 unsigned PenaltyIndentLevel;
76};
77
78class UnwrappedLineFormatter {
79public:
80 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
81 const UnwrappedLine &Line,
82 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000083 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasperbac016b2012-12-03 18:12:45 +000084 : Style(Style),
85 SourceMgr(SourceMgr),
86 Line(Line),
87 Annotations(Annotations),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000088 Replaces(Replaces),
89 StructuralError(StructuralError) {
Daniel Jasperbac016b2012-12-03 18:12:45 +000090 Parameters.PenaltyExtraLine = 100;
91 Parameters.PenaltyIndentLevel = 5;
92 }
93
94 void format() {
Alexander Kornienkocff563c2012-12-04 17:27:50 +000095 unsigned Indent = formatFirstToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +000096 IndentState State;
Alexander Kornienkocff563c2012-12-04 17:27:50 +000097 State.Column = Indent + Line.Tokens[0].Tok.getLength();
Daniel Jasperbac016b2012-12-03 18:12:45 +000098 State.CtorInitializerOnNewLine = false;
99 State.InCtorInitializer = false;
100 State.ConsumedTokens = 1;
101
102 //State.UsedIndent.push_back(Line.Level * 2);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000103 State.Indent.push_back(Indent + 4);
104 State.LastSpace.push_back(Indent);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000105
106 // Start iterating at 1 as we have correctly formatted of Token #0 above.
107 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
108 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
109 unsigned Break = calcPenalty(State, true, NoBreak);
Daniel Jasper20409152012-12-04 14:54:30 +0000110 addTokenToState(Break < NoBreak, false, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000111 }
112 }
113
114private:
115 /// \brief The current state when indenting a unwrapped line.
116 ///
117 /// As the indenting tries different combinations this is copied by value.
118 struct IndentState {
119 /// \brief The number of used columns in the current line.
120 unsigned Column;
121
122 /// \brief The number of tokens already consumed.
123 unsigned ConsumedTokens;
124
125 /// \brief The position to which a specific parenthesis level needs to be
126 /// indented.
127 std::vector<unsigned> Indent;
128
129 std::vector<unsigned> LastSpace;
130
131 bool CtorInitializerOnNewLine;
132 bool InCtorInitializer;
133
134 /// \brief Comparison operator to be able to used \c IndentState in \c map.
135 bool operator<(const IndentState &Other) const {
136 if (Other.ConsumedTokens != ConsumedTokens)
137 return Other.ConsumedTokens > ConsumedTokens;
138 if (Other.Column != Column)
139 return Other.Column > Column;
140 if (Other.Indent.size() != Indent.size())
141 return Other.Indent.size() > Indent.size();
142 for (int i = 0, e = Indent.size(); i != e; ++i) {
143 if (Other.Indent[i] != Indent[i])
144 return Other.Indent[i] > Indent[i];
145 }
146 if (Other.LastSpace.size() != LastSpace.size())
147 return Other.LastSpace.size() > LastSpace.size();
148 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
149 if (Other.LastSpace[i] != LastSpace[i])
150 return Other.LastSpace[i] > LastSpace[i];
151 }
152 return false;
153 }
154 };
155
Daniel Jasper20409152012-12-04 14:54:30 +0000156 /// \brief Appends the next token to \p State and updates information
157 /// necessary for indentation.
158 ///
159 /// Puts the token on the current line if \p Newline is \c true and adds a
160 /// line break and necessary indentation otherwise.
161 ///
162 /// If \p DryRun is \c false, also creates and stores the required
163 /// \c Replacement.
164 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000165 unsigned Index = State.ConsumedTokens;
166 const FormatToken &Current = Line.Tokens[Index];
167 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000168 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000169
170 if (Newline) {
171 if (Current.Tok.is(tok::string_literal) &&
172 Previous.Tok.is(tok::string_literal))
173 State.Column = State.Column - Previous.Tok.getLength();
174 else if (Previous.Tok.is(tok::equal) && ParenLevel != 0)
Daniel Jasper20409152012-12-04 14:54:30 +0000175 // Indent and extra 4 spaces after '=' as it continues an expression.
176 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000177 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000178 else
Daniel Jasperbac016b2012-12-03 18:12:45 +0000179 State.Column = State.Indent[ParenLevel];
Daniel Jasper20409152012-12-04 14:54:30 +0000180
Daniel Jasperbac016b2012-12-03 18:12:45 +0000181 if (!DryRun)
182 replaceWhitespace(Current, 1, State.Column);
183
184 State.Column += Current.Tok.getLength();
Daniel Jaspera88bb452012-12-04 10:50:12 +0000185 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186 if (Current.Tok.is(tok::colon) &&
187 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr) {
188 State.Indent[ParenLevel] += 2;
189 State.CtorInitializerOnNewLine = true;
190 State.InCtorInitializer = true;
191 }
192 } else {
193 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
194 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
195 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000196
Daniel Jasperbac016b2012-12-03 18:12:45 +0000197 if (!DryRun)
198 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000199
200 if (Previous.Tok.is(tok::l_paren) ||
201 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000202 State.Indent[ParenLevel] = State.Column;
203 if (Current.Tok.is(tok::colon)) {
204 State.Indent[ParenLevel] = State.Column + 3;
205 State.InCtorInitializer = true;
206 }
207 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000208 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000209 State.LastSpace[ParenLevel] = State.Column + Spaces;
210 State.Column += Current.Tok.getLength() + Spaces;
211 }
Daniel Jasper20409152012-12-04 14:54:30 +0000212 moveStateToNextToken(State);
213 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000214
Daniel Jasper20409152012-12-04 14:54:30 +0000215 /// \brief Mark the next token as consumed in \p State and modify its stacks
216 /// accordingly.
217 void moveStateToNextToken(IndentState &State) {
218 unsigned Index = State.ConsumedTokens;
219 const FormatToken &Current = Line.Tokens[Index];
220
221 // If we encounter an opening (, [ or <, we add a level to our stacks to
222 // prepare for the following tokens.
223 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
224 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
225 State.Indent.push_back(4 + State.LastSpace.back());
226 State.LastSpace.push_back(State.LastSpace.back());
227 }
228
229 // If we encounter a closing ), ] or >, we can remove a level from our
230 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000231 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
232 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000233 State.Indent.pop_back();
234 State.LastSpace.pop_back();
235 }
236
237 ++State.ConsumedTokens;
238 }
239
Daniel Jasperbac016b2012-12-03 18:12:45 +0000240 unsigned splitPenalty(const FormatToken &Token) {
241 if (Token.Tok.is(tok::semi))
242 return 0;
243 if (Token.Tok.is(tok::comma))
244 return 1;
245 if (Token.Tok.is(tok::equal) || Token.Tok.is(tok::l_paren) ||
246 Token.Tok.is(tok::pipepipe) || Token.Tok.is(tok::ampamp))
247 return 2;
248 return 3;
249 }
250
251 /// \brief Calculate the number of lines needed to format the remaining part
252 /// of the unwrapped line.
253 ///
254 /// Assumes the formatting so far has led to
255 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
256 /// added after the previous token.
257 ///
258 /// \param StopAt is used for optimization. If we can determine that we'll
259 /// definitely need at least \p StopAt additional lines, we already know of a
260 /// better solution.
261 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
262 // We are at the end of the unwrapped line, so we don't need any more lines.
263 if (State.ConsumedTokens >= Line.Tokens.size())
264 return 0;
265
266 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
267 return UINT_MAX;
268 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
269 return UINT_MAX;
270
271 if (State.ConsumedTokens > 0 && !NewLine &&
272 State.CtorInitializerOnNewLine &&
273 Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::comma))
274 return UINT_MAX;
275
276 if (NewLine && State.InCtorInitializer && !State.CtorInitializerOnNewLine)
277 return UINT_MAX;
278
Daniel Jasper33182dd2012-12-05 14:57:28 +0000279 unsigned CurrentPenalty = 0;
280 if (NewLine) {
281 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
282 Parameters.PenaltyExtraLine +
283 splitPenalty(Line.Tokens[State.ConsumedTokens - 1]);
284 }
285
Daniel Jasper20409152012-12-04 14:54:30 +0000286 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000287
288 // Exceeding column limit is bad.
289 if (State.Column > Style.ColumnLimit)
290 return UINT_MAX;
291
Daniel Jasperbac016b2012-12-03 18:12:45 +0000292 if (StopAt <= CurrentPenalty)
293 return UINT_MAX;
294 StopAt -= CurrentPenalty;
295
Daniel Jasperbac016b2012-12-03 18:12:45 +0000296 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000297 if (I != Memory.end()) {
298 // If this state has already been examined, we can safely return the
299 // previous result if we
300 // - have not hit the optimatization (and thus returned UINT_MAX) OR
301 // - are now computing for a smaller or equal StopAt.
302 unsigned SavedResult = I->second.first;
303 unsigned SavedStopAt = I->second.second;
304 if (SavedResult != UINT_MAX || StopAt <= SavedStopAt)
305 return SavedResult;
306 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307
308 unsigned NoBreak = calcPenalty(State, false, StopAt);
309 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
310 unsigned Result = std::min(NoBreak, WithBreak);
311 if (Result != UINT_MAX)
312 Result += CurrentPenalty;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000313 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000314 return Result;
315 }
316
317 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
318 /// each \c FormatToken.
319 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
320 unsigned Spaces) {
321 Replaces.insert(tooling::Replacement(
322 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
323 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
324 }
325
326 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000327 /// of the \c UnwrappedLine if there was no structural parsing error.
328 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000329 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000330 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000331 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
332 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
333
334 unsigned Newlines =
335 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
336 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
337 if (Newlines == 0 && Offset != 0)
338 Newlines = 1;
339 unsigned Indent = Line.Level * 2;
340 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
341 Token.Tok.is(tok::kw_private))
342 Indent += Style.AccessModifierOffset;
343 replaceWhitespace(Token, Newlines, Indent);
344 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000345 }
346
347 FormatStyle Style;
348 SourceManager &SourceMgr;
349 const UnwrappedLine &Line;
350 const std::vector<TokenAnnotation> &Annotations;
351 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000352 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000353
Daniel Jasper33182dd2012-12-05 14:57:28 +0000354 // A map from an indent state to a pair (Result, Used-StopAt).
355 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
356 StateMap Memory;
357
Daniel Jasperbac016b2012-12-03 18:12:45 +0000358 OptimizationParameters Parameters;
359};
360
361/// \brief Determines extra information about the tokens comprising an
362/// \c UnwrappedLine.
363class TokenAnnotator {
364public:
365 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
366 SourceManager &SourceMgr)
367 : Line(Line),
368 Style(Style),
369 SourceMgr(SourceMgr) {
370 }
371
372 /// \brief A parser that gathers additional information about tokens.
373 ///
374 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
375 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
376 /// into template parameter lists.
377 class AnnotatingParser {
378 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000379 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000380 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek0be4b362012-12-03 20:55:42 +0000381 : Tokens(Tokens),
Daniel Jasperbac016b2012-12-03 18:12:45 +0000382 Annotations(Annotations),
383 Index(0) {
384 }
385
Daniel Jasper20409152012-12-04 14:54:30 +0000386 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 while (Index < Tokens.size()) {
388 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000389 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390 next();
391 return true;
392 }
393 if (Tokens[Index].Tok.is(tok::r_paren) ||
394 Tokens[Index].Tok.is(tok::r_square))
395 return false;
396 if (Tokens[Index].Tok.is(tok::pipepipe) ||
397 Tokens[Index].Tok.is(tok::ampamp) ||
398 Tokens[Index].Tok.is(tok::question) ||
399 Tokens[Index].Tok.is(tok::colon))
400 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000401 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000402 }
403 return false;
404 }
405
Daniel Jasper20409152012-12-04 14:54:30 +0000406 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000407 while (Index < Tokens.size()) {
408 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000409 next();
410 return true;
411 }
412 if (Tokens[Index].Tok.is(tok::r_square))
413 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000414 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000415 }
416 return false;
417 }
418
Daniel Jasper20409152012-12-04 14:54:30 +0000419 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000420 while (Index < Tokens.size()) {
421 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000422 next();
423 return true;
424 }
425 if (Tokens[Index].Tok.is(tok::r_paren))
426 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000427 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 }
429 return false;
430 }
431
Daniel Jasper20409152012-12-04 14:54:30 +0000432 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000433 while (Index < Tokens.size()) {
434 if (Tokens[Index].Tok.is(tok::colon)) {
435 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
436 next();
437 return true;
438 }
Daniel Jasper20409152012-12-04 14:54:30 +0000439 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000440 }
441 return false;
442 }
443
Daniel Jasper20409152012-12-04 14:54:30 +0000444 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000445 unsigned CurrentIndex = Index;
446 next();
447 switch (Tokens[CurrentIndex].Tok.getKind()) {
448 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000449 parseParens();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000450 break;
451 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000452 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000453 break;
454 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000455 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000456 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
457 else {
458 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
459 Index = CurrentIndex + 1;
460 }
461 break;
462 case tok::greater:
463 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
464 break;
465 case tok::kw_operator:
466 if (!Tokens[Index].Tok.is(tok::l_paren))
467 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
468 next();
469 break;
470 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000471 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000472 break;
473 default:
474 break;
475 }
476 }
477
478 void parseLine() {
479 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000480 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000481 }
482 }
483
484 void next() {
485 ++Index;
486 }
487
488 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000489 const SmallVector<FormatToken, 16> &Tokens;
490 std::vector<TokenAnnotation> &Annotations;
491 unsigned Index;
492 };
493
494 void annotate() {
495 Annotations.clear();
496 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
497 Annotations.push_back(TokenAnnotation());
498 }
499
Manuel Klimek0be4b362012-12-03 20:55:42 +0000500 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501 Parser.parseLine();
502
503 determineTokenTypes();
504
505 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
506 TokenAnnotation &Annotation = Annotations[i];
507
508 Annotation.CanBreakBefore =
509 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
510
511 if (Line.Tokens[i].Tok.is(tok::colon)) {
512 if (Line.Tokens[0].Tok.is(tok::kw_case) || i == e - 1) {
513 Annotation.SpaceRequiredBefore = false;
514 } else {
515 Annotation.SpaceRequiredBefore = TokenAnnotation::TT_ConditionalExpr;
516 }
517 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
518 Annotation.SpaceRequiredBefore = false;
519 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
520 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000521 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
522 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
524 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000525 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000526 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000527 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000528 else
529 Annotation.SpaceRequiredBefore = false;
530 } else if (
531 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
532 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
533 Annotation.SpaceRequiredBefore = true;
534 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000535 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000536 Line.Tokens[i].Tok.is(tok::l_paren)) {
537 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000538 } else if (Line.Tokens[i].Tok.is(tok::less) &&
539 Line.Tokens[0].Tok.is(tok::hash)) {
540 Annotation.SpaceRequiredBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000541 } else {
542 Annotation.SpaceRequiredBefore =
543 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
544 }
545
546 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
547 (Line.Tokens[i].Tok.is(tok::string_literal) &&
548 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
549 Annotation.MustBreakBefore = true;
550 }
551
552 if (Annotation.MustBreakBefore)
553 Annotation.CanBreakBefore = true;
554 }
555 }
556
557 const std::vector<TokenAnnotation> &getAnnotations() {
558 return Annotations;
559 }
560
561private:
562 void determineTokenTypes() {
Daniel Jasper33182dd2012-12-05 14:57:28 +0000563 bool AssignmentEncountered = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000564 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
565 TokenAnnotation &Annotation = Annotations[i];
566 const FormatToken &Tok = Line.Tokens[i];
567
Daniel Jasper33182dd2012-12-05 14:57:28 +0000568 if (Tok.Tok.is(tok::equal) || Tok.Tok.is(tok::plusequal) ||
569 Tok.Tok.is(tok::minusequal) || Tok.Tok.is(tok::starequal) ||
570 Tok.Tok.is(tok::slashequal))
571 AssignmentEncountered = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000572
Daniel Jasperbac016b2012-12-03 18:12:45 +0000573 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasper33182dd2012-12-05 14:57:28 +0000574 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000575 else if (isUnaryOperator(i))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000576 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
577 else if (isBinaryOperator(Line.Tokens[i]))
578 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
579 else if (Tok.Tok.is(tok::comment)) {
580 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
581 Tok.Tok.getLength());
582 if (Data.startswith("//"))
583 Annotation.Type = TokenAnnotation::TT_LineComment;
584 else
585 Annotation.Type = TokenAnnotation::TT_BlockComment;
586 }
587 }
588 }
589
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000590 bool isUnaryOperator(unsigned Index) {
591 const Token &Tok = Line.Tokens[Index].Tok;
592 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
593 return false;
594 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
595 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
596 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
597 return true;
598 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
599 }
600
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601 bool isBinaryOperator(const FormatToken &Tok) {
602 switch (Tok.Tok.getKind()) {
603 case tok::equal:
604 case tok::equalequal:
Daniel Jasper112fb272012-12-05 07:51:39 +0000605 case tok::exclaimequal:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000606 case tok::star:
607 //case tok::amp:
608 case tok::plus:
609 case tok::slash:
610 case tok::minus:
611 case tok::ampamp:
612 case tok::pipe:
613 case tok::pipepipe:
614 case tok::percent:
615 return true;
616 default:
617 return false;
618 }
619 }
620
Daniel Jasper112fb272012-12-05 07:51:39 +0000621 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasper33182dd2012-12-05 14:57:28 +0000622 bool AssignmentEncountered) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000623 if (Index == Annotations.size())
624 return TokenAnnotation::TT_Unknown;
625
626 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
627 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
628 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
629 return TokenAnnotation::TT_UnaryOperator;
630
631 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
632 Line.Tokens[Index + 1].Tok.isLiteral())
633 return TokenAnnotation::TT_BinaryOperator;
634
Daniel Jasper112fb272012-12-05 07:51:39 +0000635 // It is very unlikely that we are going to find a pointer or reference type
636 // definition on the RHS of an assignment.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000637 if (AssignmentEncountered)
Daniel Jasper112fb272012-12-05 07:51:39 +0000638 return TokenAnnotation::TT_BinaryOperator;
639
Daniel Jasperbac016b2012-12-03 18:12:45 +0000640 return TokenAnnotation::TT_PointerOrReference;
641 }
642
643 bool isIfForOrWhile(Token Tok) {
644 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
645 }
646
647 bool spaceRequiredBetween(Token Left, Token Right) {
648 if (Left.is(tok::kw_template) && Right.is(tok::less))
649 return true;
650 if (Left.is(tok::arrow) || Right.is(tok::arrow))
651 return false;
652 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
653 return false;
654 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
655 return false;
656 if (Left.is(tok::amp) || Left.is(tok::star))
657 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
658 if (Right.is(tok::star) && Left.is(tok::l_paren))
659 return false;
660 if (Right.is(tok::amp) || Right.is(tok::star))
661 return Left.isLiteral() || !Style.PointerAndReferenceBindToType;
662 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
663 Right.is(tok::r_square))
664 return false;
665 if (Left.is(tok::coloncolon) || Right.is(tok::coloncolon))
666 return false;
667 if (Left.is(tok::period) || Right.is(tok::period))
668 return false;
669 if (Left.is(tok::colon) || Right.is(tok::colon))
670 return true;
671 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
672 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
673 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
674 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
675 return false;
676 if (Left.is(tok::l_paren))
677 return false;
678 if (Left.is(tok::hash))
679 return false;
680 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
681 return false;
682 if (Right.is(tok::l_paren)) {
683 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
684 }
685 return true;
686 }
687
688 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
689 if (Right.Tok.is(tok::r_paren))
690 return false;
691 if (isBinaryOperator(Left))
692 return true;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000693 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) ||
694 Left.Tok.is(tok::semi) || Left.Tok.is(tok::equal) ||
695 Left.Tok.is(tok::ampamp) || Left.Tok.is(tok::pipepipe) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000696 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
697 }
698
699 const UnwrappedLine &Line;
700 FormatStyle Style;
701 SourceManager &SourceMgr;
702 std::vector<TokenAnnotation> Annotations;
703};
704
705class Formatter : public UnwrappedLineConsumer {
706public:
707 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
708 const std::vector<CharSourceRange> &Ranges)
709 : Style(Style),
710 Lex(Lex),
711 SourceMgr(SourceMgr),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000712 Ranges(Ranges),
713 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714 }
715
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000716 virtual ~Formatter() {
717 }
718
Daniel Jasperbac016b2012-12-03 18:12:45 +0000719 tooling::Replacements format() {
720 UnwrappedLineParser Parser(Lex, SourceMgr, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000721 StructuralError = Parser.parse();
722 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
723 E = UnwrappedLines.end();
724 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000725 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 return Replaces;
727 }
728
729private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000730 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000731 UnwrappedLines.push_back(TheLine);
732 }
733
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000734 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000735 if (TheLine.Tokens.size() == 0)
736 return;
737
738 CharSourceRange LineRange =
739 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
740 TheLine.Tokens.back().Tok.getLocation());
741
742 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
743 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
744 Ranges[i].getBegin()) ||
745 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
746 LineRange.getBegin()))
747 continue;
748
749 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
750 Annotator.annotate();
751 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000752 Annotator.getAnnotations(), Replaces,
753 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000754 Formatter.format();
755 return;
756 }
757 }
758
759 FormatStyle Style;
760 Lexer &Lex;
761 SourceManager &SourceMgr;
762 tooling::Replacements Replaces;
763 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000764 std::vector<UnwrappedLine> UnwrappedLines;
765 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000766};
767
768tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
769 SourceManager &SourceMgr,
770 std::vector<CharSourceRange> Ranges) {
771 Formatter formatter(Style, Lex, SourceMgr, Ranges);
772 return formatter.format();
773}
774
775} // namespace format
776} // namespace clang