blob: 22805f691e93a62e0c6b575d09d14470ce5fc885 [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
318 /// of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000319 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000320 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000321 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
322 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
323
324 unsigned Newlines =
325 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
326 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
327 if (Newlines == 0 && Offset != 0)
328 Newlines = 1;
329 unsigned Indent = Line.Level * 2;
330 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
331 Token.Tok.is(tok::kw_private))
332 Indent += Style.AccessModifierOffset;
333 replaceWhitespace(Token, Newlines, Indent);
334 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000335 }
336
337 FormatStyle Style;
338 SourceManager &SourceMgr;
339 const UnwrappedLine &Line;
340 const std::vector<TokenAnnotation> &Annotations;
341 tooling::Replacements &Replaces;
342 unsigned int count;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000343 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000344
345 OptimizationParameters Parameters;
346};
347
348/// \brief Determines extra information about the tokens comprising an
349/// \c UnwrappedLine.
350class TokenAnnotator {
351public:
352 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
353 SourceManager &SourceMgr)
354 : Line(Line),
355 Style(Style),
356 SourceMgr(SourceMgr) {
357 }
358
359 /// \brief A parser that gathers additional information about tokens.
360 ///
361 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
362 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
363 /// into template parameter lists.
364 class AnnotatingParser {
365 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000366 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000367 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek0be4b362012-12-03 20:55:42 +0000368 : Tokens(Tokens),
Daniel Jasperbac016b2012-12-03 18:12:45 +0000369 Annotations(Annotations),
370 Index(0) {
371 }
372
Daniel Jasper20409152012-12-04 14:54:30 +0000373 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000374 while (Index < Tokens.size()) {
375 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000376 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000377 next();
378 return true;
379 }
380 if (Tokens[Index].Tok.is(tok::r_paren) ||
381 Tokens[Index].Tok.is(tok::r_square))
382 return false;
383 if (Tokens[Index].Tok.is(tok::pipepipe) ||
384 Tokens[Index].Tok.is(tok::ampamp) ||
385 Tokens[Index].Tok.is(tok::question) ||
386 Tokens[Index].Tok.is(tok::colon))
387 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000388 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000389 }
390 return false;
391 }
392
Daniel Jasper20409152012-12-04 14:54:30 +0000393 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000394 while (Index < Tokens.size()) {
395 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000396 next();
397 return true;
398 }
399 if (Tokens[Index].Tok.is(tok::r_square))
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 parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000407 while (Index < Tokens.size()) {
408 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000409 next();
410 return true;
411 }
412 if (Tokens[Index].Tok.is(tok::r_paren))
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 parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000420 while (Index < Tokens.size()) {
421 if (Tokens[Index].Tok.is(tok::colon)) {
422 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
423 next();
424 return true;
425 }
Daniel Jasper20409152012-12-04 14:54:30 +0000426 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000427 }
428 return false;
429 }
430
Daniel Jasper20409152012-12-04 14:54:30 +0000431 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000432 unsigned CurrentIndex = Index;
433 next();
434 switch (Tokens[CurrentIndex].Tok.getKind()) {
435 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000436 parseParens();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000437 break;
438 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000439 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000440 break;
441 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000442 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
444 else {
445 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
446 Index = CurrentIndex + 1;
447 }
448 break;
449 case tok::greater:
450 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
451 break;
452 case tok::kw_operator:
453 if (!Tokens[Index].Tok.is(tok::l_paren))
454 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
455 next();
456 break;
457 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000458 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000459 break;
460 default:
461 break;
462 }
463 }
464
465 void parseLine() {
466 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000467 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000468 }
469 }
470
471 void next() {
472 ++Index;
473 }
474
475 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000476 const SmallVector<FormatToken, 16> &Tokens;
477 std::vector<TokenAnnotation> &Annotations;
478 unsigned Index;
479 };
480
481 void annotate() {
482 Annotations.clear();
483 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
484 Annotations.push_back(TokenAnnotation());
485 }
486
Manuel Klimek0be4b362012-12-03 20:55:42 +0000487 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488 Parser.parseLine();
489
490 determineTokenTypes();
491
492 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
493 TokenAnnotation &Annotation = Annotations[i];
494
495 Annotation.CanBreakBefore =
496 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
497
498 if (Line.Tokens[i].Tok.is(tok::colon)) {
499 if (Line.Tokens[0].Tok.is(tok::kw_case) || i == e - 1) {
500 Annotation.SpaceRequiredBefore = false;
501 } else {
502 Annotation.SpaceRequiredBefore = TokenAnnotation::TT_ConditionalExpr;
503 }
504 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
505 Annotation.SpaceRequiredBefore = false;
506 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
507 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000508 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
509 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000510 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
511 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000512 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000513 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000514 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000515 else
516 Annotation.SpaceRequiredBefore = false;
517 } else if (
518 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
519 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
520 Annotation.SpaceRequiredBefore = true;
521 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000522 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 Line.Tokens[i].Tok.is(tok::l_paren)) {
524 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000525 } else if (Line.Tokens[i].Tok.is(tok::less) &&
526 Line.Tokens[0].Tok.is(tok::hash)) {
527 Annotation.SpaceRequiredBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000528 } else {
529 Annotation.SpaceRequiredBefore =
530 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
531 }
532
533 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
534 (Line.Tokens[i].Tok.is(tok::string_literal) &&
535 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
536 Annotation.MustBreakBefore = true;
537 }
538
539 if (Annotation.MustBreakBefore)
540 Annotation.CanBreakBefore = true;
541 }
542 }
543
544 const std::vector<TokenAnnotation> &getAnnotations() {
545 return Annotations;
546 }
547
548private:
549 void determineTokenTypes() {
Daniel Jasper112fb272012-12-05 07:51:39 +0000550 bool EqualEncountered = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000551 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
552 TokenAnnotation &Annotation = Annotations[i];
553 const FormatToken &Tok = Line.Tokens[i];
554
Daniel Jasper112fb272012-12-05 07:51:39 +0000555 if (Tok.Tok.is(tok::equal))
556 EqualEncountered = true;
557
Daniel Jasperbac016b2012-12-03 18:12:45 +0000558 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasper112fb272012-12-05 07:51:39 +0000559 Annotation.Type = determineStarAmpUsage(i, EqualEncountered);
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000560 else if (isUnaryOperator(i))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000561 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
562 else if (isBinaryOperator(Line.Tokens[i]))
563 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
564 else if (Tok.Tok.is(tok::comment)) {
565 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
566 Tok.Tok.getLength());
567 if (Data.startswith("//"))
568 Annotation.Type = TokenAnnotation::TT_LineComment;
569 else
570 Annotation.Type = TokenAnnotation::TT_BlockComment;
571 }
572 }
573 }
574
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000575 bool isUnaryOperator(unsigned Index) {
576 const Token &Tok = Line.Tokens[Index].Tok;
577 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
578 return false;
579 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
580 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
581 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
582 return true;
583 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
584 }
585
Daniel Jasperbac016b2012-12-03 18:12:45 +0000586 bool isBinaryOperator(const FormatToken &Tok) {
587 switch (Tok.Tok.getKind()) {
588 case tok::equal:
589 case tok::equalequal:
Daniel Jasper112fb272012-12-05 07:51:39 +0000590 case tok::exclaimequal:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591 case tok::star:
592 //case tok::amp:
593 case tok::plus:
594 case tok::slash:
595 case tok::minus:
596 case tok::ampamp:
597 case tok::pipe:
598 case tok::pipepipe:
599 case tok::percent:
600 return true;
601 default:
602 return false;
603 }
604 }
605
Daniel Jasper112fb272012-12-05 07:51:39 +0000606 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
607 bool EqualEncountered) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000608 if (Index == Annotations.size())
609 return TokenAnnotation::TT_Unknown;
610
611 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
612 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
613 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
614 return TokenAnnotation::TT_UnaryOperator;
615
616 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
617 Line.Tokens[Index + 1].Tok.isLiteral())
618 return TokenAnnotation::TT_BinaryOperator;
619
Daniel Jasper112fb272012-12-05 07:51:39 +0000620 // It is very unlikely that we are going to find a pointer or reference type
621 // definition on the RHS of an assignment.
622 if (EqualEncountered)
623 return TokenAnnotation::TT_BinaryOperator;
624
Daniel Jasperbac016b2012-12-03 18:12:45 +0000625 return TokenAnnotation::TT_PointerOrReference;
626 }
627
628 bool isIfForOrWhile(Token Tok) {
629 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
630 }
631
632 bool spaceRequiredBetween(Token Left, Token Right) {
633 if (Left.is(tok::kw_template) && Right.is(tok::less))
634 return true;
635 if (Left.is(tok::arrow) || Right.is(tok::arrow))
636 return false;
637 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
638 return false;
639 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
640 return false;
641 if (Left.is(tok::amp) || Left.is(tok::star))
642 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
643 if (Right.is(tok::star) && Left.is(tok::l_paren))
644 return false;
645 if (Right.is(tok::amp) || Right.is(tok::star))
646 return Left.isLiteral() || !Style.PointerAndReferenceBindToType;
647 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
648 Right.is(tok::r_square))
649 return false;
650 if (Left.is(tok::coloncolon) || Right.is(tok::coloncolon))
651 return false;
652 if (Left.is(tok::period) || Right.is(tok::period))
653 return false;
654 if (Left.is(tok::colon) || Right.is(tok::colon))
655 return true;
656 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
657 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
658 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
659 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
660 return false;
661 if (Left.is(tok::l_paren))
662 return false;
663 if (Left.is(tok::hash))
664 return false;
665 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
666 return false;
667 if (Right.is(tok::l_paren)) {
668 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
669 }
670 return true;
671 }
672
673 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
674 if (Right.Tok.is(tok::r_paren))
675 return false;
676 if (isBinaryOperator(Left))
677 return true;
678 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) || Left.Tok.is(
679 tok::semi) || Left.Tok.is(tok::equal) || Left.Tok.is(tok::ampamp) ||
680 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
681 }
682
683 const UnwrappedLine &Line;
684 FormatStyle Style;
685 SourceManager &SourceMgr;
686 std::vector<TokenAnnotation> Annotations;
687};
688
689class Formatter : public UnwrappedLineConsumer {
690public:
691 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
692 const std::vector<CharSourceRange> &Ranges)
693 : Style(Style),
694 Lex(Lex),
695 SourceMgr(SourceMgr),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000696 Ranges(Ranges),
697 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000698 }
699
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000700 virtual ~Formatter() {
701 }
702
Daniel Jasperbac016b2012-12-03 18:12:45 +0000703 tooling::Replacements format() {
704 UnwrappedLineParser Parser(Lex, SourceMgr, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000705 StructuralError = Parser.parse();
706 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
707 E = UnwrappedLines.end();
708 I != E; ++I)
709 doFormatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000710 return Replaces;
711 }
712
713private:
714 virtual void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000715 UnwrappedLines.push_back(TheLine);
716 }
717
718 void doFormatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000719 if (TheLine.Tokens.size() == 0)
720 return;
721
722 CharSourceRange LineRange =
723 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
724 TheLine.Tokens.back().Tok.getLocation());
725
726 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
727 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
728 Ranges[i].getBegin()) ||
729 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
730 LineRange.getBegin()))
731 continue;
732
733 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
734 Annotator.annotate();
735 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000736 Annotator.getAnnotations(), Replaces,
737 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000738 Formatter.format();
739 return;
740 }
741 }
742
743 FormatStyle Style;
744 Lexer &Lex;
745 SourceManager &SourceMgr;
746 tooling::Replacements Replaces;
747 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000748 std::vector<UnwrappedLine> UnwrappedLines;
749 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000750};
751
752tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
753 SourceManager &SourceMgr,
754 std::vector<CharSourceRange> Ranges) {
755 Formatter formatter(Style, Lex, SourceMgr, Ranges);
756 return formatter.format();
757}
758
759} // namespace format
760} // namespace clang