blob: d928aa958040c68fe1a1bbd5cda129fe46903a3a [file] [log] [blame]
Daniel Jasperf7935112012-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 Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000021#include "clang/Basic/SourceManager.h"
22#include "clang/Lex/Lexer.h"
23
Daniel Jasper8b529712012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperf7935112012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasper9b155472012-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 Jasperf7935112012-12-03 18:12:45 +000035
36 TokenType Type;
37
Daniel Jasperf7935112012-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 Kornienko870f9eb2012-12-04 17:27:50 +000075 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasperf7935112012-12-03 18:12:45 +000076 : Style(Style),
77 SourceMgr(SourceMgr),
78 Line(Line),
79 Annotations(Annotations),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000080 Replaces(Replaces),
81 StructuralError(StructuralError) {
Daniel Jasperf7935112012-12-03 18:12:45 +000082 Parameters.PenaltyExtraLine = 100;
83 Parameters.PenaltyIndentLevel = 5;
84 }
85
86 void format() {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000087 unsigned Indent = formatFirstToken();
Daniel Jasperf7935112012-12-03 18:12:45 +000088 count = 0;
89 IndentState State;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000090 State.Column = Indent + Line.Tokens[0].Tok.getLength();
Daniel Jasperf7935112012-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 Kornienko870f9eb2012-12-04 17:27:50 +000096 State.Indent.push_back(Indent + 4);
97 State.LastSpace.push_back(Indent);
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000103 addTokenToState(Break < NoBreak, false, State);
Daniel Jasperf7935112012-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 Jasper6021c4a2012-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 Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000161 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-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 Jasper6021c4a2012-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 Jasperf7935112012-12-03 18:12:45 +0000170 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper9b155472012-12-04 10:50:12 +0000171 else
Daniel Jasperf7935112012-12-03 18:12:45 +0000172 State.Column = State.Indent[ParenLevel];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000173
Daniel Jasperf7935112012-12-03 18:12:45 +0000174 if (!DryRun)
175 replaceWhitespace(Current, 1, State.Column);
176
177 State.Column += Current.Tok.getLength();
Daniel Jasper9b155472012-12-04 10:50:12 +0000178 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000189
Daniel Jasperf7935112012-12-03 18:12:45 +0000190 if (!DryRun)
191 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000192
193 if (Previous.Tok.is(tok::l_paren) ||
194 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-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 Jasper9b155472012-12-04 10:50:12 +0000201 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasperf7935112012-12-03 18:12:45 +0000202 State.LastSpace[ParenLevel] = State.Column + Spaces;
203 State.Column += Current.Tok.getLength() + Spaces;
204 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000205 moveStateToNextToken(State);
206 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000207
Daniel Jasper6021c4a2012-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 Jasper9b155472012-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 Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000275 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000283 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperf7935112012-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 Kornienko870f9eb2012-12-04 17:27:50 +0000319 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000320 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-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 Jasperf7935112012-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 Kornienko870f9eb2012-12-04 17:27:50 +0000343 bool StructuralError;
Daniel Jasperf7935112012-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 Klimek6a5619d2012-12-03 20:55:42 +0000366 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000367 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000368 : Tokens(Tokens),
Daniel Jasperf7935112012-12-03 18:12:45 +0000369 Annotations(Annotations),
370 Index(0) {
371 }
372
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000373 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000374 while (Index < Tokens.size()) {
375 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000376 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000388 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000389 }
390 return false;
391 }
392
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000393 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000394 while (Index < Tokens.size()) {
395 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000396 next();
397 return true;
398 }
399 if (Tokens[Index].Tok.is(tok::r_square))
400 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000401 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000402 }
403 return false;
404 }
405
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000406 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000407 while (Index < Tokens.size()) {
408 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000409 next();
410 return true;
411 }
412 if (Tokens[Index].Tok.is(tok::r_paren))
413 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000414 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000415 }
416 return false;
417 }
418
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000419 bool parseConditional() {
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000426 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000427 }
428 return false;
429 }
430
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000431 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000432 unsigned CurrentIndex = Index;
433 next();
434 switch (Tokens[CurrentIndex].Tok.getKind()) {
435 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000436 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +0000437 break;
438 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000439 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000440 break;
441 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000442 if (parseAngle())
Daniel Jasperf7935112012-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 Jasper6021c4a2012-12-04 14:54:30 +0000458 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 break;
460 default:
461 break;
462 }
463 }
464
465 void parseLine() {
466 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000467 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000468 }
469 }
470
471 void next() {
472 ++Index;
473 }
474
475 private:
Daniel Jasperf7935112012-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 Klimek6a5619d2012-12-03 20:55:42 +0000487 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-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 Jasper8b529712012-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 Jasperf7935112012-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 Jasper8b529712012-12-04 13:02:32 +0000512 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000513 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000514 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-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 Jasper9b155472012-12-04 10:50:12 +0000522 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 Line.Tokens[i].Tok.is(tok::l_paren)) {
524 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-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 Jasperf7935112012-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() {
550 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
551 TokenAnnotation &Annotation = Annotations[i];
552 const FormatToken &Tok = Line.Tokens[i];
553
554 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
555 Annotation.Type = determineStarAmpUsage(i);
Daniel Jasper8b529712012-12-04 13:02:32 +0000556 else if (isUnaryOperator(i))
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
558 else if (isBinaryOperator(Line.Tokens[i]))
559 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
560 else if (Tok.Tok.is(tok::comment)) {
561 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
562 Tok.Tok.getLength());
563 if (Data.startswith("//"))
564 Annotation.Type = TokenAnnotation::TT_LineComment;
565 else
566 Annotation.Type = TokenAnnotation::TT_BlockComment;
567 }
568 }
569 }
570
Daniel Jasper8b529712012-12-04 13:02:32 +0000571 bool isUnaryOperator(unsigned Index) {
572 const Token &Tok = Line.Tokens[Index].Tok;
573 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
574 return false;
575 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
576 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
577 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
578 return true;
579 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
580 }
581
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 bool isBinaryOperator(const FormatToken &Tok) {
583 switch (Tok.Tok.getKind()) {
584 case tok::equal:
585 case tok::equalequal:
586 case tok::star:
587 //case tok::amp:
588 case tok::plus:
589 case tok::slash:
590 case tok::minus:
591 case tok::ampamp:
592 case tok::pipe:
593 case tok::pipepipe:
594 case tok::percent:
595 return true;
596 default:
597 return false;
598 }
599 }
600
601 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index) {
602 if (Index == Annotations.size())
603 return TokenAnnotation::TT_Unknown;
604
605 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
606 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
607 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
608 return TokenAnnotation::TT_UnaryOperator;
609
610 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
611 Line.Tokens[Index + 1].Tok.isLiteral())
612 return TokenAnnotation::TT_BinaryOperator;
613
614 return TokenAnnotation::TT_PointerOrReference;
615 }
616
617 bool isIfForOrWhile(Token Tok) {
618 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
619 }
620
621 bool spaceRequiredBetween(Token Left, Token Right) {
622 if (Left.is(tok::kw_template) && Right.is(tok::less))
623 return true;
624 if (Left.is(tok::arrow) || Right.is(tok::arrow))
625 return false;
626 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
627 return false;
628 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
629 return false;
630 if (Left.is(tok::amp) || Left.is(tok::star))
631 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
632 if (Right.is(tok::star) && Left.is(tok::l_paren))
633 return false;
634 if (Right.is(tok::amp) || Right.is(tok::star))
635 return Left.isLiteral() || !Style.PointerAndReferenceBindToType;
636 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
637 Right.is(tok::r_square))
638 return false;
639 if (Left.is(tok::coloncolon) || Right.is(tok::coloncolon))
640 return false;
641 if (Left.is(tok::period) || Right.is(tok::period))
642 return false;
643 if (Left.is(tok::colon) || Right.is(tok::colon))
644 return true;
645 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
646 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
647 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
648 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
649 return false;
650 if (Left.is(tok::l_paren))
651 return false;
652 if (Left.is(tok::hash))
653 return false;
654 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
655 return false;
656 if (Right.is(tok::l_paren)) {
657 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
658 }
659 return true;
660 }
661
662 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
663 if (Right.Tok.is(tok::r_paren))
664 return false;
665 if (isBinaryOperator(Left))
666 return true;
667 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) || Left.Tok.is(
668 tok::semi) || Left.Tok.is(tok::equal) || Left.Tok.is(tok::ampamp) ||
669 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
670 }
671
672 const UnwrappedLine &Line;
673 FormatStyle Style;
674 SourceManager &SourceMgr;
675 std::vector<TokenAnnotation> Annotations;
676};
677
678class Formatter : public UnwrappedLineConsumer {
679public:
680 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
681 const std::vector<CharSourceRange> &Ranges)
682 : Style(Style),
683 Lex(Lex),
684 SourceMgr(SourceMgr),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000685 Ranges(Ranges),
686 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000687 }
688
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000689 virtual ~Formatter() {
690 }
691
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 tooling::Replacements format() {
693 UnwrappedLineParser Parser(Lex, SourceMgr, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000694 StructuralError = Parser.parse();
695 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
696 E = UnwrappedLines.end();
697 I != E; ++I)
698 doFormatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +0000699 return Replaces;
700 }
701
702private:
703 virtual void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000704 UnwrappedLines.push_back(TheLine);
705 }
706
707 void doFormatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000708 if (TheLine.Tokens.size() == 0)
709 return;
710
711 CharSourceRange LineRange =
712 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
713 TheLine.Tokens.back().Tok.getLocation());
714
715 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
716 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
717 Ranges[i].getBegin()) ||
718 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
719 LineRange.getBegin()))
720 continue;
721
722 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
723 Annotator.annotate();
724 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000725 Annotator.getAnnotations(), Replaces,
726 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +0000727 Formatter.format();
728 return;
729 }
730 }
731
732 FormatStyle Style;
733 Lexer &Lex;
734 SourceManager &SourceMgr;
735 tooling::Replacements Replaces;
736 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000737 std::vector<UnwrappedLine> UnwrappedLines;
738 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000739};
740
741tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
742 SourceManager &SourceMgr,
743 std::vector<CharSourceRange> Ranges) {
744 Formatter formatter(Style, Lex, SourceMgr, Ranges);
745 return formatter.format();
746}
747
748} // namespace format
749} // namespace clang