blob: 78450469f5b486a46ee7967164186239ab1969fe [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 Jaspera88bb452012-12-04 10:50:12 +000031 enum TokenType { TT_Unknown, TT_TemplateOpener, TT_TemplateCloser,
32 TT_BinaryOperator, TT_UnaryOperator, TT_OverloadedOperator,
33 TT_PointerOrReference, TT_ConditionalExpr, TT_LineComment,
34 TT_BlockComment };
Daniel Jasperbac016b2012-12-03 18:12:45 +000035
36 TokenType Type;
37
Daniel Jasperbac016b2012-12-03 18:12:45 +000038 bool SpaceRequiredBefore;
39 bool CanBreakBefore;
40 bool MustBreakBefore;
41};
42
43using llvm::MutableArrayRef;
44
45FormatStyle getLLVMStyle() {
46 FormatStyle LLVMStyle;
47 LLVMStyle.ColumnLimit = 80;
48 LLVMStyle.MaxEmptyLinesToKeep = 1;
49 LLVMStyle.PointerAndReferenceBindToType = false;
50 LLVMStyle.AccessModifierOffset = -2;
51 LLVMStyle.SplitTemplateClosingGreater = true;
52 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
59 GoogleStyle.PointerAndReferenceBindToType = true;
60 GoogleStyle.AccessModifierOffset = -1;
61 GoogleStyle.SplitTemplateClosingGreater = false;
62 return GoogleStyle;
63}
64
65struct OptimizationParameters {
66 unsigned PenaltyExtraLine;
67 unsigned PenaltyIndentLevel;
68};
69
70class UnwrappedLineFormatter {
71public:
72 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
73 const UnwrappedLine &Line,
74 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000075 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasperbac016b2012-12-03 18:12:45 +000076 : Style(Style),
77 SourceMgr(SourceMgr),
78 Line(Line),
79 Annotations(Annotations),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000080 Replaces(Replaces),
81 StructuralError(StructuralError) {
Daniel Jasperbac016b2012-12-03 18:12:45 +000082 Parameters.PenaltyExtraLine = 100;
83 Parameters.PenaltyIndentLevel = 5;
84 }
85
86 void format() {
Alexander Kornienkocff563c2012-12-04 17:27:50 +000087 unsigned Indent = formatFirstToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +000088 count = 0;
89 IndentState State;
Alexander Kornienkocff563c2012-12-04 17:27:50 +000090 State.Column = Indent + Line.Tokens[0].Tok.getLength();
Daniel Jasperbac016b2012-12-03 18:12:45 +000091 State.CtorInitializerOnNewLine = false;
92 State.InCtorInitializer = false;
93 State.ConsumedTokens = 1;
94
95 //State.UsedIndent.push_back(Line.Level * 2);
Alexander Kornienkocff563c2012-12-04 17:27:50 +000096 State.Indent.push_back(Indent + 4);
97 State.LastSpace.push_back(Indent);
Daniel Jasperbac016b2012-12-03 18:12:45 +000098
99 // Start iterating at 1 as we have correctly formatted of Token #0 above.
100 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
101 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
102 unsigned Break = calcPenalty(State, true, NoBreak);
Daniel Jasper20409152012-12-04 14:54:30 +0000103 addTokenToState(Break < NoBreak, false, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000104 }
105 }
106
107private:
108 /// \brief The current state when indenting a unwrapped line.
109 ///
110 /// As the indenting tries different combinations this is copied by value.
111 struct IndentState {
112 /// \brief The number of used columns in the current line.
113 unsigned Column;
114
115 /// \brief The number of tokens already consumed.
116 unsigned ConsumedTokens;
117
118 /// \brief The position to which a specific parenthesis level needs to be
119 /// indented.
120 std::vector<unsigned> Indent;
121
122 std::vector<unsigned> LastSpace;
123
124 bool CtorInitializerOnNewLine;
125 bool InCtorInitializer;
126
127 /// \brief Comparison operator to be able to used \c IndentState in \c map.
128 bool operator<(const IndentState &Other) const {
129 if (Other.ConsumedTokens != ConsumedTokens)
130 return Other.ConsumedTokens > ConsumedTokens;
131 if (Other.Column != Column)
132 return Other.Column > Column;
133 if (Other.Indent.size() != Indent.size())
134 return Other.Indent.size() > Indent.size();
135 for (int i = 0, e = Indent.size(); i != e; ++i) {
136 if (Other.Indent[i] != Indent[i])
137 return Other.Indent[i] > Indent[i];
138 }
139 if (Other.LastSpace.size() != LastSpace.size())
140 return Other.LastSpace.size() > LastSpace.size();
141 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
142 if (Other.LastSpace[i] != LastSpace[i])
143 return Other.LastSpace[i] > LastSpace[i];
144 }
145 return false;
146 }
147 };
148
Daniel Jasper20409152012-12-04 14:54:30 +0000149 /// \brief Appends the next token to \p State and updates information
150 /// necessary for indentation.
151 ///
152 /// Puts the token on the current line if \p Newline is \c true and adds a
153 /// line break and necessary indentation otherwise.
154 ///
155 /// If \p DryRun is \c false, also creates and stores the required
156 /// \c Replacement.
157 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000158 unsigned Index = State.ConsumedTokens;
159 const FormatToken &Current = Line.Tokens[Index];
160 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000161 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000162
163 if (Newline) {
164 if (Current.Tok.is(tok::string_literal) &&
165 Previous.Tok.is(tok::string_literal))
166 State.Column = State.Column - Previous.Tok.getLength();
167 else if (Previous.Tok.is(tok::equal) && ParenLevel != 0)
Daniel Jasper20409152012-12-04 14:54:30 +0000168 // Indent and extra 4 spaces after '=' as it continues an expression.
169 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000170 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000171 else
Daniel Jasperbac016b2012-12-03 18:12:45 +0000172 State.Column = State.Indent[ParenLevel];
Daniel Jasper20409152012-12-04 14:54:30 +0000173
Daniel Jasperbac016b2012-12-03 18:12:45 +0000174 if (!DryRun)
175 replaceWhitespace(Current, 1, State.Column);
176
177 State.Column += Current.Tok.getLength();
Daniel Jaspera88bb452012-12-04 10:50:12 +0000178 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000179 if (Current.Tok.is(tok::colon) &&
180 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr) {
181 State.Indent[ParenLevel] += 2;
182 State.CtorInitializerOnNewLine = true;
183 State.InCtorInitializer = true;
184 }
185 } else {
186 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
187 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
188 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000189
Daniel Jasperbac016b2012-12-03 18:12:45 +0000190 if (!DryRun)
191 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000192
193 if (Previous.Tok.is(tok::l_paren) ||
194 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000195 State.Indent[ParenLevel] = State.Column;
196 if (Current.Tok.is(tok::colon)) {
197 State.Indent[ParenLevel] = State.Column + 3;
198 State.InCtorInitializer = true;
199 }
200 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000201 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000202 State.LastSpace[ParenLevel] = State.Column + Spaces;
203 State.Column += Current.Tok.getLength() + Spaces;
204 }
Daniel Jasper20409152012-12-04 14:54:30 +0000205 moveStateToNextToken(State);
206 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000207
Daniel Jasper20409152012-12-04 14:54:30 +0000208 /// \brief Mark the next token as consumed in \p State and modify its stacks
209 /// accordingly.
210 void moveStateToNextToken(IndentState &State) {
211 unsigned Index = State.ConsumedTokens;
212 const FormatToken &Current = Line.Tokens[Index];
213
214 // If we encounter an opening (, [ or <, we add a level to our stacks to
215 // prepare for the following tokens.
216 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
217 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
218 State.Indent.push_back(4 + State.LastSpace.back());
219 State.LastSpace.push_back(State.LastSpace.back());
220 }
221
222 // If we encounter a closing ), ] or >, we can remove a level from our
223 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000224 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
225 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000226 State.Indent.pop_back();
227 State.LastSpace.pop_back();
228 }
229
230 ++State.ConsumedTokens;
231 }
232
233 typedef std::map<IndentState, unsigned> StateMap;
234 StateMap Memory;
235
236 unsigned splitPenalty(const FormatToken &Token) {
237 if (Token.Tok.is(tok::semi))
238 return 0;
239 if (Token.Tok.is(tok::comma))
240 return 1;
241 if (Token.Tok.is(tok::equal) || Token.Tok.is(tok::l_paren) ||
242 Token.Tok.is(tok::pipepipe) || Token.Tok.is(tok::ampamp))
243 return 2;
244 return 3;
245 }
246
247 /// \brief Calculate the number of lines needed to format the remaining part
248 /// of the unwrapped line.
249 ///
250 /// Assumes the formatting so far has led to
251 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
252 /// added after the previous token.
253 ///
254 /// \param StopAt is used for optimization. If we can determine that we'll
255 /// definitely need at least \p StopAt additional lines, we already know of a
256 /// better solution.
257 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
258 // We are at the end of the unwrapped line, so we don't need any more lines.
259 if (State.ConsumedTokens >= Line.Tokens.size())
260 return 0;
261
262 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
263 return UINT_MAX;
264 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
265 return UINT_MAX;
266
267 if (State.ConsumedTokens > 0 && !NewLine &&
268 State.CtorInitializerOnNewLine &&
269 Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::comma))
270 return UINT_MAX;
271
272 if (NewLine && State.InCtorInitializer && !State.CtorInitializerOnNewLine)
273 return UINT_MAX;
274
Daniel Jasper20409152012-12-04 14:54:30 +0000275 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000276
277 // Exceeding column limit is bad.
278 if (State.Column > Style.ColumnLimit)
279 return UINT_MAX;
280
281 unsigned CurrentPenalty = 0;
282 if (NewLine) {
Daniel Jasper20409152012-12-04 14:54:30 +0000283 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperbac016b2012-12-03 18:12:45 +0000284 Parameters.PenaltyExtraLine +
285 splitPenalty(Line.Tokens[State.ConsumedTokens - 2]);
286 }
287
288 if (StopAt <= CurrentPenalty)
289 return UINT_MAX;
290 StopAt -= CurrentPenalty;
291
292 // Has this state already been examined?
293 StateMap::iterator I = Memory.find(State);
294 if (I != Memory.end())
295 return I->second;
296 ++count;
297
298 unsigned NoBreak = calcPenalty(State, false, StopAt);
299 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
300 unsigned Result = std::min(NoBreak, WithBreak);
301 if (Result != UINT_MAX)
302 Result += CurrentPenalty;
303 Memory[State] = Result;
304 assert(Memory.find(State) != Memory.end());
305 return Result;
306 }
307
308 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
309 /// each \c FormatToken.
310 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
311 unsigned Spaces) {
312 Replaces.insert(tooling::Replacement(
313 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
314 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
315 }
316
317 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000318 /// of the \c UnwrappedLine if there was no structural parsing error.
319 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000320 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000321 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000322 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
323 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
324
325 unsigned Newlines =
326 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
327 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
328 if (Newlines == 0 && Offset != 0)
329 Newlines = 1;
330 unsigned Indent = Line.Level * 2;
331 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
332 Token.Tok.is(tok::kw_private))
333 Indent += Style.AccessModifierOffset;
334 replaceWhitespace(Token, Newlines, Indent);
335 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000336 }
337
338 FormatStyle Style;
339 SourceManager &SourceMgr;
340 const UnwrappedLine &Line;
341 const std::vector<TokenAnnotation> &Annotations;
342 tooling::Replacements &Replaces;
343 unsigned int count;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000344 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000345
346 OptimizationParameters Parameters;
347};
348
349/// \brief Determines extra information about the tokens comprising an
350/// \c UnwrappedLine.
351class TokenAnnotator {
352public:
353 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
354 SourceManager &SourceMgr)
355 : Line(Line),
356 Style(Style),
357 SourceMgr(SourceMgr) {
358 }
359
360 /// \brief A parser that gathers additional information about tokens.
361 ///
362 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
363 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
364 /// into template parameter lists.
365 class AnnotatingParser {
366 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000367 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000368 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek0be4b362012-12-03 20:55:42 +0000369 : Tokens(Tokens),
Daniel Jasperbac016b2012-12-03 18:12:45 +0000370 Annotations(Annotations),
371 Index(0) {
372 }
373
Daniel Jasper20409152012-12-04 14:54:30 +0000374 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000375 while (Index < Tokens.size()) {
376 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000377 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000378 next();
379 return true;
380 }
381 if (Tokens[Index].Tok.is(tok::r_paren) ||
382 Tokens[Index].Tok.is(tok::r_square))
383 return false;
384 if (Tokens[Index].Tok.is(tok::pipepipe) ||
385 Tokens[Index].Tok.is(tok::ampamp) ||
386 Tokens[Index].Tok.is(tok::question) ||
387 Tokens[Index].Tok.is(tok::colon))
388 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000389 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390 }
391 return false;
392 }
393
Daniel Jasper20409152012-12-04 14:54:30 +0000394 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000395 while (Index < Tokens.size()) {
396 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000397 next();
398 return true;
399 }
400 if (Tokens[Index].Tok.is(tok::r_square))
401 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000402 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000403 }
404 return false;
405 }
406
Daniel Jasper20409152012-12-04 14:54:30 +0000407 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000408 while (Index < Tokens.size()) {
409 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000410 next();
411 return true;
412 }
413 if (Tokens[Index].Tok.is(tok::r_paren))
414 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000415 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000416 }
417 return false;
418 }
419
Daniel Jasper20409152012-12-04 14:54:30 +0000420 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000421 while (Index < Tokens.size()) {
422 if (Tokens[Index].Tok.is(tok::colon)) {
423 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
424 next();
425 return true;
426 }
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 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000433 unsigned CurrentIndex = Index;
434 next();
435 switch (Tokens[CurrentIndex].Tok.getKind()) {
436 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000437 parseParens();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000438 break;
439 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000440 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000441 break;
442 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000443 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000444 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
445 else {
446 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
447 Index = CurrentIndex + 1;
448 }
449 break;
450 case tok::greater:
451 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
452 break;
453 case tok::kw_operator:
454 if (!Tokens[Index].Tok.is(tok::l_paren))
455 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
456 next();
457 break;
458 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000459 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000460 break;
461 default:
462 break;
463 }
464 }
465
466 void parseLine() {
467 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000468 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000469 }
470 }
471
472 void next() {
473 ++Index;
474 }
475
476 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000477 const SmallVector<FormatToken, 16> &Tokens;
478 std::vector<TokenAnnotation> &Annotations;
479 unsigned Index;
480 };
481
482 void annotate() {
483 Annotations.clear();
484 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
485 Annotations.push_back(TokenAnnotation());
486 }
487
Manuel Klimek0be4b362012-12-03 20:55:42 +0000488 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000489 Parser.parseLine();
490
491 determineTokenTypes();
492
493 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
494 TokenAnnotation &Annotation = Annotations[i];
495
496 Annotation.CanBreakBefore =
497 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
498
499 if (Line.Tokens[i].Tok.is(tok::colon)) {
500 if (Line.Tokens[0].Tok.is(tok::kw_case) || i == e - 1) {
501 Annotation.SpaceRequiredBefore = false;
502 } else {
503 Annotation.SpaceRequiredBefore = TokenAnnotation::TT_ConditionalExpr;
504 }
505 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
506 Annotation.SpaceRequiredBefore = false;
507 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
508 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000509 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
510 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000511 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
512 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000513 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000514 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000515 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000516 else
517 Annotation.SpaceRequiredBefore = false;
518 } else if (
519 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
520 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
521 Annotation.SpaceRequiredBefore = true;
522 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000523 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000524 Line.Tokens[i].Tok.is(tok::l_paren)) {
525 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000526 } else if (Line.Tokens[i].Tok.is(tok::less) &&
527 Line.Tokens[0].Tok.is(tok::hash)) {
528 Annotation.SpaceRequiredBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000529 } else {
530 Annotation.SpaceRequiredBefore =
531 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
532 }
533
534 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
535 (Line.Tokens[i].Tok.is(tok::string_literal) &&
536 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
537 Annotation.MustBreakBefore = true;
538 }
539
540 if (Annotation.MustBreakBefore)
541 Annotation.CanBreakBefore = true;
542 }
543 }
544
545 const std::vector<TokenAnnotation> &getAnnotations() {
546 return Annotations;
547 }
548
549private:
550 void determineTokenTypes() {
Daniel Jasper112fb272012-12-05 07:51:39 +0000551 bool EqualEncountered = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000552 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
553 TokenAnnotation &Annotation = Annotations[i];
554 const FormatToken &Tok = Line.Tokens[i];
555
Daniel Jasper112fb272012-12-05 07:51:39 +0000556 if (Tok.Tok.is(tok::equal))
557 EqualEncountered = true;
558
Daniel Jasperbac016b2012-12-03 18:12:45 +0000559 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasper112fb272012-12-05 07:51:39 +0000560 Annotation.Type = determineStarAmpUsage(i, EqualEncountered);
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000561 else if (isUnaryOperator(i))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000562 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
563 else if (isBinaryOperator(Line.Tokens[i]))
564 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
565 else if (Tok.Tok.is(tok::comment)) {
566 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
567 Tok.Tok.getLength());
568 if (Data.startswith("//"))
569 Annotation.Type = TokenAnnotation::TT_LineComment;
570 else
571 Annotation.Type = TokenAnnotation::TT_BlockComment;
572 }
573 }
574 }
575
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000576 bool isUnaryOperator(unsigned Index) {
577 const Token &Tok = Line.Tokens[Index].Tok;
578 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
579 return false;
580 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
581 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
582 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
583 return true;
584 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
585 }
586
Daniel Jasperbac016b2012-12-03 18:12:45 +0000587 bool isBinaryOperator(const FormatToken &Tok) {
588 switch (Tok.Tok.getKind()) {
589 case tok::equal:
590 case tok::equalequal:
Daniel Jasper112fb272012-12-05 07:51:39 +0000591 case tok::exclaimequal:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 case tok::star:
593 //case tok::amp:
594 case tok::plus:
595 case tok::slash:
596 case tok::minus:
597 case tok::ampamp:
598 case tok::pipe:
599 case tok::pipepipe:
600 case tok::percent:
601 return true;
602 default:
603 return false;
604 }
605 }
606
Daniel Jasper112fb272012-12-05 07:51:39 +0000607 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
608 bool EqualEncountered) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000609 if (Index == Annotations.size())
610 return TokenAnnotation::TT_Unknown;
611
612 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
613 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
614 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
615 return TokenAnnotation::TT_UnaryOperator;
616
617 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
618 Line.Tokens[Index + 1].Tok.isLiteral())
619 return TokenAnnotation::TT_BinaryOperator;
620
Daniel Jasper112fb272012-12-05 07:51:39 +0000621 // It is very unlikely that we are going to find a pointer or reference type
622 // definition on the RHS of an assignment.
623 if (EqualEncountered)
624 return TokenAnnotation::TT_BinaryOperator;
625
Daniel Jasperbac016b2012-12-03 18:12:45 +0000626 return TokenAnnotation::TT_PointerOrReference;
627 }
628
629 bool isIfForOrWhile(Token Tok) {
630 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
631 }
632
633 bool spaceRequiredBetween(Token Left, Token Right) {
634 if (Left.is(tok::kw_template) && Right.is(tok::less))
635 return true;
636 if (Left.is(tok::arrow) || Right.is(tok::arrow))
637 return false;
638 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
639 return false;
640 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
641 return false;
642 if (Left.is(tok::amp) || Left.is(tok::star))
643 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
644 if (Right.is(tok::star) && Left.is(tok::l_paren))
645 return false;
646 if (Right.is(tok::amp) || Right.is(tok::star))
647 return Left.isLiteral() || !Style.PointerAndReferenceBindToType;
648 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
649 Right.is(tok::r_square))
650 return false;
651 if (Left.is(tok::coloncolon) || Right.is(tok::coloncolon))
652 return false;
653 if (Left.is(tok::period) || Right.is(tok::period))
654 return false;
655 if (Left.is(tok::colon) || Right.is(tok::colon))
656 return true;
657 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
658 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
659 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
660 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
661 return false;
662 if (Left.is(tok::l_paren))
663 return false;
664 if (Left.is(tok::hash))
665 return false;
666 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
667 return false;
668 if (Right.is(tok::l_paren)) {
669 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
670 }
671 return true;
672 }
673
674 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
675 if (Right.Tok.is(tok::r_paren))
676 return false;
677 if (isBinaryOperator(Left))
678 return true;
679 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) || Left.Tok.is(
680 tok::semi) || Left.Tok.is(tok::equal) || Left.Tok.is(tok::ampamp) ||
681 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
682 }
683
684 const UnwrappedLine &Line;
685 FormatStyle Style;
686 SourceManager &SourceMgr;
687 std::vector<TokenAnnotation> Annotations;
688};
689
690class Formatter : public UnwrappedLineConsumer {
691public:
692 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
693 const std::vector<CharSourceRange> &Ranges)
694 : Style(Style),
695 Lex(Lex),
696 SourceMgr(SourceMgr),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000697 Ranges(Ranges),
698 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000699 }
700
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000701 virtual ~Formatter() {
702 }
703
Daniel Jasperbac016b2012-12-03 18:12:45 +0000704 tooling::Replacements format() {
705 UnwrappedLineParser Parser(Lex, SourceMgr, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000706 StructuralError = Parser.parse();
707 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
708 E = UnwrappedLines.end();
709 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000710 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000711 return Replaces;
712 }
713
714private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000715 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000716 UnwrappedLines.push_back(TheLine);
717 }
718
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000719 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000720 if (TheLine.Tokens.size() == 0)
721 return;
722
723 CharSourceRange LineRange =
724 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
725 TheLine.Tokens.back().Tok.getLocation());
726
727 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
728 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
729 Ranges[i].getBegin()) ||
730 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
731 LineRange.getBegin()))
732 continue;
733
734 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
735 Annotator.annotate();
736 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000737 Annotator.getAnnotations(), Replaces,
738 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000739 Formatter.format();
740 return;
741 }
742 }
743
744 FormatStyle Style;
745 Lexer &Lex;
746 SourceManager &SourceMgr;
747 tooling::Replacements Replaces;
748 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000749 std::vector<UnwrappedLine> UnwrappedLines;
750 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000751};
752
753tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
754 SourceManager &SourceMgr,
755 std::vector<CharSourceRange> Ranges) {
756 Formatter formatter(Style, Lex, SourceMgr, Ranges);
757 return formatter.format();
758}
759
760} // namespace format
761} // namespace clang