blob: 08096866bf39779680c9a050538935f4cda2aec9 [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 Jasperaa1c9202012-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 Jasperf7935112012-12-03 18:12:45 +000043
44 TokenType Type;
45
Daniel Jasperf7935112012-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 Kornienko870f9eb2012-12-04 17:27:50 +000083 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasperf7935112012-12-03 18:12:45 +000084 : Style(Style),
85 SourceMgr(SourceMgr),
86 Line(Line),
87 Annotations(Annotations),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000088 Replaces(Replaces),
89 StructuralError(StructuralError) {
Daniel Jasperf7935112012-12-03 18:12:45 +000090 Parameters.PenaltyExtraLine = 100;
91 Parameters.PenaltyIndentLevel = 5;
92 }
93
94 void format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +000095 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000096 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +000097
98 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +000099 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000100 State.Column = Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000101 State.CtorInitializerOnNewLine = false;
102 State.InCtorInitializer = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000103 State.ConsumedTokens = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000104 State.Indent.push_back(Indent + 4);
105 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000106 State.FirstLessLess.push_back(0);
107
108 // The first token has already been indented and thus consumed.
109 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000110
111 // Start iterating at 1 as we have correctly formatted of Token #0 above.
112 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
113 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
114 unsigned Break = calcPenalty(State, true, NoBreak);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000115 addTokenToState(Break < NoBreak, false, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000116 }
117 }
118
119private:
120 /// \brief The current state when indenting a unwrapped line.
121 ///
122 /// As the indenting tries different combinations this is copied by value.
123 struct IndentState {
124 /// \brief The number of used columns in the current line.
125 unsigned Column;
126
127 /// \brief The number of tokens already consumed.
128 unsigned ConsumedTokens;
129
130 /// \brief The position to which a specific parenthesis level needs to be
131 /// indented.
132 std::vector<unsigned> Indent;
133
Daniel Jaspere9de2602012-12-06 09:56:08 +0000134 /// \brief The position of the last space on each level.
135 ///
136 /// Used e.g. to break like:
137 /// functionCall(Parameter, otherCall(
138 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000139 std::vector<unsigned> LastSpace;
140
Daniel Jaspere9de2602012-12-06 09:56:08 +0000141 /// \brief The position the first "<<" operator encountered on each level.
142 ///
143 /// Used to align "<<" operators. 0 if no such operator has been encountered
144 /// on a level.
145 std::vector<unsigned> FirstLessLess;
146
Daniel Jasperf7935112012-12-03 18:12:45 +0000147 bool CtorInitializerOnNewLine;
148 bool InCtorInitializer;
149
150 /// \brief Comparison operator to be able to used \c IndentState in \c map.
151 bool operator<(const IndentState &Other) const {
152 if (Other.ConsumedTokens != ConsumedTokens)
153 return Other.ConsumedTokens > ConsumedTokens;
154 if (Other.Column != Column)
155 return Other.Column > Column;
156 if (Other.Indent.size() != Indent.size())
157 return Other.Indent.size() > Indent.size();
158 for (int i = 0, e = Indent.size(); i != e; ++i) {
159 if (Other.Indent[i] != Indent[i])
160 return Other.Indent[i] > Indent[i];
161 }
162 if (Other.LastSpace.size() != LastSpace.size())
163 return Other.LastSpace.size() > LastSpace.size();
164 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
165 if (Other.LastSpace[i] != LastSpace[i])
166 return Other.LastSpace[i] > LastSpace[i];
167 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000168 if (Other.FirstLessLess.size() != FirstLessLess.size())
169 return Other.FirstLessLess.size() > FirstLessLess.size();
170 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
171 if (Other.FirstLessLess[i] != FirstLessLess[i])
172 return Other.FirstLessLess[i] > FirstLessLess[i];
173 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000174 return false;
175 }
176 };
177
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000178 /// \brief Appends the next token to \p State and updates information
179 /// necessary for indentation.
180 ///
181 /// Puts the token on the current line if \p Newline is \c true and adds a
182 /// line break and necessary indentation otherwise.
183 ///
184 /// If \p DryRun is \c false, also creates and stores the required
185 /// \c Replacement.
186 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000187 unsigned Index = State.ConsumedTokens;
188 const FormatToken &Current = Line.Tokens[Index];
189 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000190 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000191
192 if (Newline) {
193 if (Current.Tok.is(tok::string_literal) &&
194 Previous.Tok.is(tok::string_literal))
195 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000196 else if (Current.Tok.is(tok::lessless) &&
197 State.FirstLessLess[ParenLevel] != 0)
198 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000199 else if (Previous.Tok.is(tok::equal) && ParenLevel != 0)
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000200 // Indent and extra 4 spaces after '=' as it continues an expression.
201 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000202 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper9b155472012-12-04 10:50:12 +0000203 else
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 State.Column = State.Indent[ParenLevel];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000205
Daniel Jasperf7935112012-12-03 18:12:45 +0000206 if (!DryRun)
207 replaceWhitespace(Current, 1, State.Column);
208
Daniel Jasper9b155472012-12-04 10:50:12 +0000209 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000210 if (Current.Tok.is(tok::colon) &&
211 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr) {
212 State.Indent[ParenLevel] += 2;
213 State.CtorInitializerOnNewLine = true;
214 State.InCtorInitializer = true;
215 }
216 } else {
217 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
218 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
219 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000220
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 if (!DryRun)
222 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000223
224 if (Previous.Tok.is(tok::l_paren) ||
225 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000226 State.Indent[ParenLevel] = State.Column;
227 if (Current.Tok.is(tok::colon)) {
228 State.Indent[ParenLevel] = State.Column + 3;
229 State.InCtorInitializer = true;
230 }
231 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000232 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000233 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000234 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000235 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000236 moveStateToNextToken(State);
237 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000238
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000239 /// \brief Mark the next token as consumed in \p State and modify its stacks
240 /// accordingly.
241 void moveStateToNextToken(IndentState &State) {
242 unsigned Index = State.ConsumedTokens;
243 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000244 unsigned ParenLevel = State.Indent.size() - 1;
245
246 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
247 State.FirstLessLess[ParenLevel] = State.Column;
248
249 State.Column += Current.Tok.getLength();
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000250
251 // If we encounter an opening (, [ or <, we add a level to our stacks to
252 // prepare for the following tokens.
253 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
254 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
255 State.Indent.push_back(4 + State.LastSpace.back());
256 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000257 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000258 }
259
260 // If we encounter a closing ), ] or >, we can remove a level from our
261 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000262 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
263 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000264 State.Indent.pop_back();
265 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000266 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000267 }
268
269 ++State.ConsumedTokens;
270 }
271
Daniel Jasperf7935112012-12-03 18:12:45 +0000272 unsigned splitPenalty(const FormatToken &Token) {
273 if (Token.Tok.is(tok::semi))
274 return 0;
275 if (Token.Tok.is(tok::comma))
276 return 1;
277 if (Token.Tok.is(tok::equal) || Token.Tok.is(tok::l_paren) ||
278 Token.Tok.is(tok::pipepipe) || Token.Tok.is(tok::ampamp))
279 return 2;
280 return 3;
281 }
282
283 /// \brief Calculate the number of lines needed to format the remaining part
284 /// of the unwrapped line.
285 ///
286 /// Assumes the formatting so far has led to
287 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
288 /// added after the previous token.
289 ///
290 /// \param StopAt is used for optimization. If we can determine that we'll
291 /// definitely need at least \p StopAt additional lines, we already know of a
292 /// better solution.
293 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
294 // We are at the end of the unwrapped line, so we don't need any more lines.
295 if (State.ConsumedTokens >= Line.Tokens.size())
296 return 0;
297
298 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
299 return UINT_MAX;
300 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
301 return UINT_MAX;
302
303 if (State.ConsumedTokens > 0 && !NewLine &&
304 State.CtorInitializerOnNewLine &&
305 Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::comma))
306 return UINT_MAX;
307
308 if (NewLine && State.InCtorInitializer && !State.CtorInitializerOnNewLine)
309 return UINT_MAX;
310
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000311 unsigned CurrentPenalty = 0;
312 if (NewLine) {
313 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
314 Parameters.PenaltyExtraLine +
315 splitPenalty(Line.Tokens[State.ConsumedTokens - 1]);
316 }
317
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000318 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000319
320 // Exceeding column limit is bad.
321 if (State.Column > Style.ColumnLimit)
322 return UINT_MAX;
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324 if (StopAt <= CurrentPenalty)
325 return UINT_MAX;
326 StopAt -= CurrentPenalty;
327
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000329 if (I != Memory.end()) {
330 // If this state has already been examined, we can safely return the
331 // previous result if we
332 // - have not hit the optimatization (and thus returned UINT_MAX) OR
333 // - are now computing for a smaller or equal StopAt.
334 unsigned SavedResult = I->second.first;
335 unsigned SavedStopAt = I->second.second;
336 if (SavedResult != UINT_MAX || StopAt <= SavedStopAt)
337 return SavedResult;
338 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000339
340 unsigned NoBreak = calcPenalty(State, false, StopAt);
341 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
342 unsigned Result = std::min(NoBreak, WithBreak);
343 if (Result != UINT_MAX)
344 Result += CurrentPenalty;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000345 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasperf7935112012-12-03 18:12:45 +0000346 return Result;
347 }
348
349 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
350 /// each \c FormatToken.
351 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
352 unsigned Spaces) {
353 Replaces.insert(tooling::Replacement(
354 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
355 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
356 }
357
358 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000359 /// of the \c UnwrappedLine if there was no structural parsing error.
360 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000361 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000363 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
364 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
365
366 unsigned Newlines =
367 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
368 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
369 if (Newlines == 0 && Offset != 0)
370 Newlines = 1;
371 unsigned Indent = Line.Level * 2;
372 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
373 Token.Tok.is(tok::kw_private))
374 Indent += Style.AccessModifierOffset;
375 replaceWhitespace(Token, Newlines, Indent);
376 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000377 }
378
379 FormatStyle Style;
380 SourceManager &SourceMgr;
381 const UnwrappedLine &Line;
382 const std::vector<TokenAnnotation> &Annotations;
383 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000384 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000385
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000386 // A map from an indent state to a pair (Result, Used-StopAt).
387 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
388 StateMap Memory;
389
Daniel Jasperf7935112012-12-03 18:12:45 +0000390 OptimizationParameters Parameters;
391};
392
393/// \brief Determines extra information about the tokens comprising an
394/// \c UnwrappedLine.
395class TokenAnnotator {
396public:
397 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
398 SourceManager &SourceMgr)
399 : Line(Line),
400 Style(Style),
401 SourceMgr(SourceMgr) {
402 }
403
404 /// \brief A parser that gathers additional information about tokens.
405 ///
406 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
407 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
408 /// into template parameter lists.
409 class AnnotatingParser {
410 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000411 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000412 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000413 : Tokens(Tokens),
Daniel Jasperf7935112012-12-03 18:12:45 +0000414 Annotations(Annotations),
415 Index(0) {
416 }
417
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000418 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000419 while (Index < Tokens.size()) {
420 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000421 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000422 next();
423 return true;
424 }
425 if (Tokens[Index].Tok.is(tok::r_paren) ||
426 Tokens[Index].Tok.is(tok::r_square))
427 return false;
428 if (Tokens[Index].Tok.is(tok::pipepipe) ||
429 Tokens[Index].Tok.is(tok::ampamp) ||
430 Tokens[Index].Tok.is(tok::question) ||
431 Tokens[Index].Tok.is(tok::colon))
432 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000433 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000434 }
435 return false;
436 }
437
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000438 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000439 while (Index < Tokens.size()) {
440 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000441 next();
442 return true;
443 }
444 if (Tokens[Index].Tok.is(tok::r_square))
445 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000446 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000447 }
448 return false;
449 }
450
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000451 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000452 while (Index < Tokens.size()) {
453 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 next();
455 return true;
456 }
457 if (Tokens[Index].Tok.is(tok::r_paren))
458 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000459 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000460 }
461 return false;
462 }
463
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000464 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000465 while (Index < Tokens.size()) {
466 if (Tokens[Index].Tok.is(tok::colon)) {
467 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
468 next();
469 return true;
470 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000471 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000472 }
473 return false;
474 }
475
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000476 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000477 unsigned CurrentIndex = Index;
478 next();
479 switch (Tokens[CurrentIndex].Tok.getKind()) {
480 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000481 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 break;
483 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000484 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000485 break;
486 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000487 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000488 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
489 else {
490 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
491 Index = CurrentIndex + 1;
492 }
493 break;
494 case tok::greater:
495 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
496 break;
497 case tok::kw_operator:
498 if (!Tokens[Index].Tok.is(tok::l_paren))
499 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
500 next();
501 break;
502 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000503 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000504 break;
505 default:
506 break;
507 }
508 }
509
510 void parseLine() {
511 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000512 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 }
514 }
515
516 void next() {
517 ++Index;
518 }
519
520 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 const SmallVector<FormatToken, 16> &Tokens;
522 std::vector<TokenAnnotation> &Annotations;
523 unsigned Index;
524 };
525
526 void annotate() {
527 Annotations.clear();
528 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
529 Annotations.push_back(TokenAnnotation());
530 }
531
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000532 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000533 Parser.parseLine();
534
535 determineTokenTypes();
536
537 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
538 TokenAnnotation &Annotation = Annotations[i];
539
540 Annotation.CanBreakBefore =
541 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
542
543 if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000544 Annotation.SpaceRequiredBefore =
545 Line.Tokens[0].Tok.isNot(tok::kw_case) && i != e - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000546 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
547 Annotation.SpaceRequiredBefore = false;
548 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
549 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000550 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
551 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000552 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
553 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000554 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000555 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000556 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 else
558 Annotation.SpaceRequiredBefore = false;
559 } else if (
560 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
561 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
562 Annotation.SpaceRequiredBefore = true;
563 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000564 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 Line.Tokens[i].Tok.is(tok::l_paren)) {
566 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000567 } else if (Line.Tokens[i].Tok.is(tok::less) &&
568 Line.Tokens[0].Tok.is(tok::hash)) {
569 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 } else {
571 Annotation.SpaceRequiredBefore =
572 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
573 }
574
575 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
576 (Line.Tokens[i].Tok.is(tok::string_literal) &&
577 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
578 Annotation.MustBreakBefore = true;
579 }
580
581 if (Annotation.MustBreakBefore)
582 Annotation.CanBreakBefore = true;
583 }
584 }
585
586 const std::vector<TokenAnnotation> &getAnnotations() {
587 return Annotations;
588 }
589
590private:
591 void determineTokenTypes() {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000592 bool AssignmentEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000593 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
594 TokenAnnotation &Annotation = Annotations[i];
595 const FormatToken &Tok = Line.Tokens[i];
596
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000597 if (Tok.Tok.is(tok::equal) || Tok.Tok.is(tok::plusequal) ||
598 Tok.Tok.is(tok::minusequal) || Tok.Tok.is(tok::starequal) ||
599 Tok.Tok.is(tok::slashequal))
600 AssignmentEncountered = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000601
Daniel Jasperf7935112012-12-03 18:12:45 +0000602 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000603 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8b529712012-12-04 13:02:32 +0000604 else if (isUnaryOperator(i))
Daniel Jasperf7935112012-12-03 18:12:45 +0000605 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
606 else if (isBinaryOperator(Line.Tokens[i]))
607 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
608 else if (Tok.Tok.is(tok::comment)) {
609 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
610 Tok.Tok.getLength());
611 if (Data.startswith("//"))
612 Annotation.Type = TokenAnnotation::TT_LineComment;
613 else
614 Annotation.Type = TokenAnnotation::TT_BlockComment;
615 }
616 }
617 }
618
Daniel Jasper8b529712012-12-04 13:02:32 +0000619 bool isUnaryOperator(unsigned Index) {
620 const Token &Tok = Line.Tokens[Index].Tok;
621 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
622 return false;
623 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
624 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
625 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
626 return true;
627 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
628 }
629
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 bool isBinaryOperator(const FormatToken &Tok) {
631 switch (Tok.Tok.getKind()) {
632 case tok::equal:
633 case tok::equalequal:
Daniel Jasper426702d2012-12-05 07:51:39 +0000634 case tok::exclaimequal:
Daniel Jasperf7935112012-12-03 18:12:45 +0000635 case tok::star:
636 //case tok::amp:
637 case tok::plus:
638 case tok::slash:
639 case tok::minus:
640 case tok::ampamp:
641 case tok::pipe:
642 case tok::pipepipe:
643 case tok::percent:
644 return true;
645 default:
646 return false;
647 }
648 }
649
Daniel Jasper426702d2012-12-05 07:51:39 +0000650 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000651 bool AssignmentEncountered) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 if (Index == Annotations.size())
653 return TokenAnnotation::TT_Unknown;
654
655 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
656 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
657 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
658 return TokenAnnotation::TT_UnaryOperator;
659
660 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
661 Line.Tokens[Index + 1].Tok.isLiteral())
662 return TokenAnnotation::TT_BinaryOperator;
663
Daniel Jasper426702d2012-12-05 07:51:39 +0000664 // It is very unlikely that we are going to find a pointer or reference type
665 // definition on the RHS of an assignment.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000666 if (AssignmentEncountered)
Daniel Jasper426702d2012-12-05 07:51:39 +0000667 return TokenAnnotation::TT_BinaryOperator;
668
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 return TokenAnnotation::TT_PointerOrReference;
670 }
671
672 bool isIfForOrWhile(Token Tok) {
673 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
674 }
675
676 bool spaceRequiredBetween(Token Left, Token Right) {
677 if (Left.is(tok::kw_template) && Right.is(tok::less))
678 return true;
679 if (Left.is(tok::arrow) || Right.is(tok::arrow))
680 return false;
681 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
682 return false;
683 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
684 return false;
685 if (Left.is(tok::amp) || Left.is(tok::star))
686 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
687 if (Right.is(tok::star) && Left.is(tok::l_paren))
688 return false;
689 if (Right.is(tok::amp) || Right.is(tok::star))
690 return Left.isLiteral() || !Style.PointerAndReferenceBindToType;
691 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
692 Right.is(tok::r_square))
693 return false;
694 if (Left.is(tok::coloncolon) || Right.is(tok::coloncolon))
695 return false;
696 if (Left.is(tok::period) || Right.is(tok::period))
697 return false;
698 if (Left.is(tok::colon) || Right.is(tok::colon))
699 return true;
700 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
701 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
702 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
703 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
704 return false;
705 if (Left.is(tok::l_paren))
706 return false;
707 if (Left.is(tok::hash))
708 return false;
709 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
710 return false;
711 if (Right.is(tok::l_paren)) {
712 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
713 }
714 return true;
715 }
716
717 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
718 if (Right.Tok.is(tok::r_paren))
719 return false;
720 if (isBinaryOperator(Left))
721 return true;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000722 if (Right.Tok.is(tok::lessless))
723 return true;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000724 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) ||
725 Left.Tok.is(tok::semi) || Left.Tok.is(tok::equal) ||
726 Left.Tok.is(tok::ampamp) || Left.Tok.is(tok::pipepipe) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000727 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
728 }
729
730 const UnwrappedLine &Line;
731 FormatStyle Style;
732 SourceManager &SourceMgr;
733 std::vector<TokenAnnotation> Annotations;
734};
735
736class Formatter : public UnwrappedLineConsumer {
737public:
738 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
739 const std::vector<CharSourceRange> &Ranges)
740 : Style(Style),
741 Lex(Lex),
742 SourceMgr(SourceMgr),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000743 Ranges(Ranges),
744 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 }
746
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000747 virtual ~Formatter() {
748 }
749
Daniel Jasperf7935112012-12-03 18:12:45 +0000750 tooling::Replacements format() {
751 UnwrappedLineParser Parser(Lex, SourceMgr, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000752 StructuralError = Parser.parse();
753 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
754 E = UnwrappedLines.end();
755 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000756 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +0000757 return Replaces;
758 }
759
760private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000761 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000762 UnwrappedLines.push_back(TheLine);
763 }
764
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000765 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000766 if (TheLine.Tokens.size() == 0)
767 return;
768
769 CharSourceRange LineRange =
770 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
771 TheLine.Tokens.back().Tok.getLocation());
772
773 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
774 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
775 Ranges[i].getBegin()) ||
776 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
777 LineRange.getBegin()))
778 continue;
779
780 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
781 Annotator.annotate();
782 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000783 Annotator.getAnnotations(), Replaces,
784 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 Formatter.format();
786 return;
787 }
788 }
789
790 FormatStyle Style;
791 Lexer &Lex;
792 SourceManager &SourceMgr;
793 tooling::Replacements Replaces;
794 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000795 std::vector<UnwrappedLine> UnwrappedLines;
796 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000797};
798
799tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
800 SourceManager &SourceMgr,
801 std::vector<CharSourceRange> Ranges) {
802 Formatter formatter(Style, Lex, SourceMgr, Ranges);
803 return formatter.format();
804}
805
806} // namespace format
807} // namespace clang