blob: 7085aaf8b770cb41717305c5264ffacfb5a643b8 [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000021#include "clang/Basic/SourceManager.h"
22#include "clang/Lex/Lexer.h"
23
Daniel Jasper8822d3a2012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperbac016b2012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000031 enum TokenType {
32 TT_Unknown,
33 TT_TemplateOpener,
34 TT_TemplateCloser,
35 TT_BinaryOperator,
36 TT_UnaryOperator,
37 TT_OverloadedOperator,
38 TT_PointerOrReference,
39 TT_ConditionalExpr,
40 TT_LineComment,
41 TT_BlockComment
42 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000043
44 TokenType Type;
45
Daniel Jasperbac016b2012-12-03 18:12:45 +000046 bool SpaceRequiredBefore;
47 bool CanBreakBefore;
48 bool MustBreakBefore;
49};
50
51using llvm::MutableArrayRef;
52
53FormatStyle getLLVMStyle() {
54 FormatStyle LLVMStyle;
55 LLVMStyle.ColumnLimit = 80;
56 LLVMStyle.MaxEmptyLinesToKeep = 1;
57 LLVMStyle.PointerAndReferenceBindToType = false;
58 LLVMStyle.AccessModifierOffset = -2;
59 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000060 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000061 return LLVMStyle;
62}
63
64FormatStyle getGoogleStyle() {
65 FormatStyle GoogleStyle;
66 GoogleStyle.ColumnLimit = 80;
67 GoogleStyle.MaxEmptyLinesToKeep = 1;
68 GoogleStyle.PointerAndReferenceBindToType = true;
69 GoogleStyle.AccessModifierOffset = -1;
70 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000071 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
75struct OptimizationParameters {
76 unsigned PenaltyExtraLine;
77 unsigned PenaltyIndentLevel;
78};
79
80class UnwrappedLineFormatter {
81public:
82 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
83 const UnwrappedLine &Line,
84 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000085 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasperbac016b2012-12-03 18:12:45 +000086 : Style(Style),
87 SourceMgr(SourceMgr),
88 Line(Line),
89 Annotations(Annotations),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000090 Replaces(Replaces),
91 StructuralError(StructuralError) {
Daniel Jasperbac016b2012-12-03 18:12:45 +000092 Parameters.PenaltyExtraLine = 100;
93 Parameters.PenaltyIndentLevel = 5;
94 }
95
96 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +000097 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +000098 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +000099
100 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000101 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000102 State.Column = Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000103 State.CtorInitializerOnNewLine = false;
104 State.InCtorInitializer = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000105 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000106 State.Indent.push_back(Indent + 4);
107 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000108 State.FirstLessLess.push_back(0);
109
110 // The first token has already been indented and thus consumed.
111 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000112
113 // Start iterating at 1 as we have correctly formatted of Token #0 above.
114 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
115 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
116 unsigned Break = calcPenalty(State, true, NoBreak);
Daniel Jasper20409152012-12-04 14:54:30 +0000117 addTokenToState(Break < NoBreak, false, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000118 }
119 }
120
121private:
122 /// \brief The current state when indenting a unwrapped line.
123 ///
124 /// As the indenting tries different combinations this is copied by value.
125 struct IndentState {
126 /// \brief The number of used columns in the current line.
127 unsigned Column;
128
129 /// \brief The number of tokens already consumed.
130 unsigned ConsumedTokens;
131
132 /// \brief The position to which a specific parenthesis level needs to be
133 /// indented.
134 std::vector<unsigned> Indent;
135
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000136 /// \brief The position of the last space on each level.
137 ///
138 /// Used e.g. to break like:
139 /// functionCall(Parameter, otherCall(
140 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000141 std::vector<unsigned> LastSpace;
142
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000143 /// \brief The position the first "<<" operator encountered on each level.
144 ///
145 /// Used to align "<<" operators. 0 if no such operator has been encountered
146 /// on a level.
147 std::vector<unsigned> FirstLessLess;
148
Daniel Jasperbac016b2012-12-03 18:12:45 +0000149 bool CtorInitializerOnNewLine;
150 bool InCtorInitializer;
151
152 /// \brief Comparison operator to be able to used \c IndentState in \c map.
153 bool operator<(const IndentState &Other) const {
154 if (Other.ConsumedTokens != ConsumedTokens)
155 return Other.ConsumedTokens > ConsumedTokens;
156 if (Other.Column != Column)
157 return Other.Column > Column;
158 if (Other.Indent.size() != Indent.size())
159 return Other.Indent.size() > Indent.size();
160 for (int i = 0, e = Indent.size(); i != e; ++i) {
161 if (Other.Indent[i] != Indent[i])
162 return Other.Indent[i] > Indent[i];
163 }
164 if (Other.LastSpace.size() != LastSpace.size())
165 return Other.LastSpace.size() > LastSpace.size();
166 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
167 if (Other.LastSpace[i] != LastSpace[i])
168 return Other.LastSpace[i] > LastSpace[i];
169 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000170 if (Other.FirstLessLess.size() != FirstLessLess.size())
171 return Other.FirstLessLess.size() > FirstLessLess.size();
172 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
173 if (Other.FirstLessLess[i] != FirstLessLess[i])
174 return Other.FirstLessLess[i] > FirstLessLess[i];
175 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000176 return false;
177 }
178 };
179
Daniel Jasper20409152012-12-04 14:54:30 +0000180 /// \brief Appends the next token to \p State and updates information
181 /// necessary for indentation.
182 ///
183 /// Puts the token on the current line if \p Newline is \c true and adds a
184 /// line break and necessary indentation otherwise.
185 ///
186 /// If \p DryRun is \c false, also creates and stores the required
187 /// \c Replacement.
188 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000189 unsigned Index = State.ConsumedTokens;
190 const FormatToken &Current = Line.Tokens[Index];
191 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000192 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000193
194 if (Newline) {
195 if (Current.Tok.is(tok::string_literal) &&
196 Previous.Tok.is(tok::string_literal))
197 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000198 else if (Current.Tok.is(tok::lessless) &&
199 State.FirstLessLess[ParenLevel] != 0)
200 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000201 else if (Previous.Tok.is(tok::equal) && ParenLevel != 0)
Daniel Jasper20409152012-12-04 14:54:30 +0000202 // Indent and extra 4 spaces after '=' as it continues an expression.
203 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000204 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000205 else
Daniel Jasperbac016b2012-12-03 18:12:45 +0000206 State.Column = State.Indent[ParenLevel];
Daniel Jasper20409152012-12-04 14:54:30 +0000207
Daniel Jasperbac016b2012-12-03 18:12:45 +0000208 if (!DryRun)
209 replaceWhitespace(Current, 1, State.Column);
210
Daniel Jaspera88bb452012-12-04 10:50:12 +0000211 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212 if (Current.Tok.is(tok::colon) &&
213 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr) {
214 State.Indent[ParenLevel] += 2;
215 State.CtorInitializerOnNewLine = true;
216 State.InCtorInitializer = true;
217 }
218 } else {
219 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
220 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
221 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000222
Daniel Jasperbac016b2012-12-03 18:12:45 +0000223 if (!DryRun)
224 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000225
226 if (Previous.Tok.is(tok::l_paren) ||
227 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228 State.Indent[ParenLevel] = State.Column;
229 if (Current.Tok.is(tok::colon)) {
230 State.Indent[ParenLevel] = State.Column + 3;
231 State.InCtorInitializer = true;
232 }
233 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000234 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000235 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000236 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000237 }
Daniel Jasper20409152012-12-04 14:54:30 +0000238 moveStateToNextToken(State);
239 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000240
Daniel Jasper20409152012-12-04 14:54:30 +0000241 /// \brief Mark the next token as consumed in \p State and modify its stacks
242 /// accordingly.
243 void moveStateToNextToken(IndentState &State) {
244 unsigned Index = State.ConsumedTokens;
245 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000246 unsigned ParenLevel = State.Indent.size() - 1;
247
248 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
249 State.FirstLessLess[ParenLevel] = State.Column;
250
251 State.Column += Current.Tok.getLength();
Daniel Jasper20409152012-12-04 14:54:30 +0000252
253 // If we encounter an opening (, [ or <, we add a level to our stacks to
254 // prepare for the following tokens.
255 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
256 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
257 State.Indent.push_back(4 + State.LastSpace.back());
258 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000259 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000260 }
261
262 // If we encounter a closing ), ] or >, we can remove a level from our
263 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000264 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
265 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000266 State.Indent.pop_back();
267 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000268 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269 }
270
271 ++State.ConsumedTokens;
272 }
273
Daniel Jasperbac016b2012-12-03 18:12:45 +0000274 unsigned splitPenalty(const FormatToken &Token) {
275 if (Token.Tok.is(tok::semi))
276 return 0;
277 if (Token.Tok.is(tok::comma))
278 return 1;
279 if (Token.Tok.is(tok::equal) || Token.Tok.is(tok::l_paren) ||
280 Token.Tok.is(tok::pipepipe) || Token.Tok.is(tok::ampamp))
281 return 2;
282 return 3;
283 }
284
285 /// \brief Calculate the number of lines needed to format the remaining part
286 /// of the unwrapped line.
287 ///
288 /// Assumes the formatting so far has led to
289 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
290 /// added after the previous token.
291 ///
292 /// \param StopAt is used for optimization. If we can determine that we'll
293 /// definitely need at least \p StopAt additional lines, we already know of a
294 /// better solution.
295 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
296 // We are at the end of the unwrapped line, so we don't need any more lines.
297 if (State.ConsumedTokens >= Line.Tokens.size())
298 return 0;
299
300 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
301 return UINT_MAX;
302 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
303 return UINT_MAX;
304
305 if (State.ConsumedTokens > 0 && !NewLine &&
306 State.CtorInitializerOnNewLine &&
307 Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::comma))
308 return UINT_MAX;
309
310 if (NewLine && State.InCtorInitializer && !State.CtorInitializerOnNewLine)
311 return UINT_MAX;
312
Daniel Jasper33182dd2012-12-05 14:57:28 +0000313 unsigned CurrentPenalty = 0;
314 if (NewLine) {
315 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
316 Parameters.PenaltyExtraLine +
317 splitPenalty(Line.Tokens[State.ConsumedTokens - 1]);
318 }
319
Daniel Jasper20409152012-12-04 14:54:30 +0000320 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000321
322 // Exceeding column limit is bad.
323 if (State.Column > Style.ColumnLimit)
324 return UINT_MAX;
325
Daniel Jasperbac016b2012-12-03 18:12:45 +0000326 if (StopAt <= CurrentPenalty)
327 return UINT_MAX;
328 StopAt -= CurrentPenalty;
329
Daniel Jasperbac016b2012-12-03 18:12:45 +0000330 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000331 if (I != Memory.end()) {
332 // If this state has already been examined, we can safely return the
333 // previous result if we
334 // - have not hit the optimatization (and thus returned UINT_MAX) OR
335 // - are now computing for a smaller or equal StopAt.
336 unsigned SavedResult = I->second.first;
337 unsigned SavedStopAt = I->second.second;
338 if (SavedResult != UINT_MAX || StopAt <= SavedStopAt)
339 return SavedResult;
340 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341
342 unsigned NoBreak = calcPenalty(State, false, StopAt);
343 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
344 unsigned Result = std::min(NoBreak, WithBreak);
345 if (Result != UINT_MAX)
346 Result += CurrentPenalty;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000347 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000348 return Result;
349 }
350
351 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
352 /// each \c FormatToken.
353 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
354 unsigned Spaces) {
355 Replaces.insert(tooling::Replacement(
356 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
357 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
358 }
359
360 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000361 /// of the \c UnwrappedLine if there was no structural parsing error.
362 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000363 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000364 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000365 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
366 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
367
368 unsigned Newlines =
369 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
370 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
371 if (Newlines == 0 && Offset != 0)
372 Newlines = 1;
373 unsigned Indent = Line.Level * 2;
374 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
375 Token.Tok.is(tok::kw_private))
376 Indent += Style.AccessModifierOffset;
377 replaceWhitespace(Token, Newlines, Indent);
378 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000379 }
380
381 FormatStyle Style;
382 SourceManager &SourceMgr;
383 const UnwrappedLine &Line;
384 const std::vector<TokenAnnotation> &Annotations;
385 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000386 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387
Daniel Jasper33182dd2012-12-05 14:57:28 +0000388 // A map from an indent state to a pair (Result, Used-StopAt).
389 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
390 StateMap Memory;
391
Daniel Jasperbac016b2012-12-03 18:12:45 +0000392 OptimizationParameters Parameters;
393};
394
395/// \brief Determines extra information about the tokens comprising an
396/// \c UnwrappedLine.
397class TokenAnnotator {
398public:
399 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
400 SourceManager &SourceMgr)
401 : Line(Line),
402 Style(Style),
403 SourceMgr(SourceMgr) {
404 }
405
406 /// \brief A parser that gathers additional information about tokens.
407 ///
408 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
409 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
410 /// into template parameter lists.
411 class AnnotatingParser {
412 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000413 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000414 std::vector<TokenAnnotation> &Annotations)
Manuel Klimek0be4b362012-12-03 20:55:42 +0000415 : Tokens(Tokens),
Daniel Jasperbac016b2012-12-03 18:12:45 +0000416 Annotations(Annotations),
417 Index(0) {
418 }
419
Daniel Jasper20409152012-12-04 14:54:30 +0000420 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000421 while (Index < Tokens.size()) {
422 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000423 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000424 next();
425 return true;
426 }
427 if (Tokens[Index].Tok.is(tok::r_paren) ||
428 Tokens[Index].Tok.is(tok::r_square))
429 return false;
430 if (Tokens[Index].Tok.is(tok::pipepipe) ||
431 Tokens[Index].Tok.is(tok::ampamp) ||
432 Tokens[Index].Tok.is(tok::question) ||
433 Tokens[Index].Tok.is(tok::colon))
434 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000435 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000436 }
437 return false;
438 }
439
Daniel Jasper20409152012-12-04 14:54:30 +0000440 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000441 while (Index < Tokens.size()) {
442 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 next();
444 return true;
445 }
446 if (Tokens[Index].Tok.is(tok::r_square))
447 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000448 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000449 }
450 return false;
451 }
452
Daniel Jasper20409152012-12-04 14:54:30 +0000453 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000454 while (Index < Tokens.size()) {
455 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000456 next();
457 return true;
458 }
459 if (Tokens[Index].Tok.is(tok::r_paren))
460 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000461 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000462 }
463 return false;
464 }
465
Daniel Jasper20409152012-12-04 14:54:30 +0000466 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000467 while (Index < Tokens.size()) {
468 if (Tokens[Index].Tok.is(tok::colon)) {
469 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
470 next();
471 return true;
472 }
Daniel Jasper20409152012-12-04 14:54:30 +0000473 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000474 }
475 return false;
476 }
477
Daniel Jasper20409152012-12-04 14:54:30 +0000478 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000479 unsigned CurrentIndex = Index;
480 next();
481 switch (Tokens[CurrentIndex].Tok.getKind()) {
482 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000483 parseParens();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000484 break;
485 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000486 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000487 break;
488 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000489 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000490 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
491 else {
492 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
493 Index = CurrentIndex + 1;
494 }
495 break;
496 case tok::greater:
497 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
498 break;
499 case tok::kw_operator:
500 if (!Tokens[Index].Tok.is(tok::l_paren))
501 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
502 next();
503 break;
504 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000505 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000506 break;
507 default:
508 break;
509 }
510 }
511
512 void parseLine() {
513 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000514 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000515 }
516 }
517
518 void next() {
519 ++Index;
520 }
521
522 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 const SmallVector<FormatToken, 16> &Tokens;
524 std::vector<TokenAnnotation> &Annotations;
525 unsigned Index;
526 };
527
528 void annotate() {
529 Annotations.clear();
530 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
531 Annotations.push_back(TokenAnnotation());
532 }
533
Manuel Klimek0be4b362012-12-03 20:55:42 +0000534 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 Parser.parseLine();
536
537 determineTokenTypes();
538
539 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
540 TokenAnnotation &Annotation = Annotations[i];
541
542 Annotation.CanBreakBefore =
543 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
544
545 if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000546 Annotation.SpaceRequiredBefore =
547 Line.Tokens[0].Tok.isNot(tok::kw_case) && i != e - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000548 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
549 Annotation.SpaceRequiredBefore = false;
550 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
551 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000552 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
553 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000554 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
555 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000556 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000557 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000558 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000559 else
560 Annotation.SpaceRequiredBefore = false;
561 } else if (
562 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
563 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
564 Annotation.SpaceRequiredBefore = true;
565 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000566 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000567 Line.Tokens[i].Tok.is(tok::l_paren)) {
568 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000569 } else if (Line.Tokens[i].Tok.is(tok::less) &&
570 Line.Tokens[0].Tok.is(tok::hash)) {
571 Annotation.SpaceRequiredBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 } else {
573 Annotation.SpaceRequiredBefore =
574 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
575 }
576
577 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
578 (Line.Tokens[i].Tok.is(tok::string_literal) &&
579 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
580 Annotation.MustBreakBefore = true;
581 }
582
583 if (Annotation.MustBreakBefore)
584 Annotation.CanBreakBefore = true;
585 }
586 }
587
588 const std::vector<TokenAnnotation> &getAnnotations() {
589 return Annotations;
590 }
591
592private:
593 void determineTokenTypes() {
Daniel Jasper33182dd2012-12-05 14:57:28 +0000594 bool AssignmentEncountered = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000595 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
596 TokenAnnotation &Annotation = Annotations[i];
597 const FormatToken &Tok = Line.Tokens[i];
598
Daniel Jasper33182dd2012-12-05 14:57:28 +0000599 if (Tok.Tok.is(tok::equal) || Tok.Tok.is(tok::plusequal) ||
600 Tok.Tok.is(tok::minusequal) || Tok.Tok.is(tok::starequal) ||
601 Tok.Tok.is(tok::slashequal))
602 AssignmentEncountered = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000603
Daniel Jasperbac016b2012-12-03 18:12:45 +0000604 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasper33182dd2012-12-05 14:57:28 +0000605 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000606 else if (isUnaryOperator(i))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000607 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
608 else if (isBinaryOperator(Line.Tokens[i]))
609 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
610 else if (Tok.Tok.is(tok::comment)) {
611 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
612 Tok.Tok.getLength());
613 if (Data.startswith("//"))
614 Annotation.Type = TokenAnnotation::TT_LineComment;
615 else
616 Annotation.Type = TokenAnnotation::TT_BlockComment;
617 }
618 }
619 }
620
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000621 bool isUnaryOperator(unsigned Index) {
622 const Token &Tok = Line.Tokens[Index].Tok;
Daniel Jasperd56a7372012-12-06 13:16:39 +0000623
624 // '++', '--' and '!' are always unary operators.
625 if (Tok.is(tok::minusminus) || Tok.is(tok::plusplus) ||
626 Tok.is(tok::exclaim))
627 return true;
628
629 // The other possible unary operators are '+' and '-' as we
630 // determine the usage of '*' and '&' in determineStarAmpUsage().
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000631 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
632 return false;
Daniel Jasperd56a7372012-12-06 13:16:39 +0000633
634 // Use heuristics to recognize unary operators.
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000635 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
636 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
637 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
638 return true;
Daniel Jasperd56a7372012-12-06 13:16:39 +0000639
640 // Fall back to marking the token as binary operator.
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000641 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
642 }
643
Daniel Jasperbac016b2012-12-03 18:12:45 +0000644 bool isBinaryOperator(const FormatToken &Tok) {
645 switch (Tok.Tok.getKind()) {
646 case tok::equal:
647 case tok::equalequal:
Daniel Jasper112fb272012-12-05 07:51:39 +0000648 case tok::exclaimequal:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000649 case tok::star:
650 //case tok::amp:
651 case tok::plus:
652 case tok::slash:
653 case tok::minus:
654 case tok::ampamp:
655 case tok::pipe:
656 case tok::pipepipe:
657 case tok::percent:
658 return true;
659 default:
660 return false;
661 }
662 }
663
Daniel Jasper112fb272012-12-05 07:51:39 +0000664 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasper33182dd2012-12-05 14:57:28 +0000665 bool AssignmentEncountered) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000666 if (Index == Annotations.size())
667 return TokenAnnotation::TT_Unknown;
668
669 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
670 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
671 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
672 return TokenAnnotation::TT_UnaryOperator;
673
674 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
675 Line.Tokens[Index + 1].Tok.isLiteral())
676 return TokenAnnotation::TT_BinaryOperator;
677
Daniel Jasper112fb272012-12-05 07:51:39 +0000678 // It is very unlikely that we are going to find a pointer or reference type
679 // definition on the RHS of an assignment.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000680 if (AssignmentEncountered)
Daniel Jasper112fb272012-12-05 07:51:39 +0000681 return TokenAnnotation::TT_BinaryOperator;
682
Daniel Jasperbac016b2012-12-03 18:12:45 +0000683 return TokenAnnotation::TT_PointerOrReference;
684 }
685
686 bool isIfForOrWhile(Token Tok) {
687 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
688 }
689
690 bool spaceRequiredBetween(Token Left, Token Right) {
691 if (Left.is(tok::kw_template) && Right.is(tok::less))
692 return true;
693 if (Left.is(tok::arrow) || Right.is(tok::arrow))
694 return false;
695 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
696 return false;
697 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
698 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000699 if (Right.is(tok::amp) || Right.is(tok::star))
700 return Left.isLiteral() ||
701 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
702 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000703 if (Left.is(tok::amp) || Left.is(tok::star))
704 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
705 if (Right.is(tok::star) && Left.is(tok::l_paren))
706 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
708 Right.is(tok::r_square))
709 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000710 if (Left.is(tok::coloncolon) ||
711 (Right.is(tok::coloncolon) &&
712 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000713 return false;
714 if (Left.is(tok::period) || Right.is(tok::period))
715 return false;
716 if (Left.is(tok::colon) || Right.is(tok::colon))
717 return true;
718 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
719 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
720 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
721 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
722 return false;
723 if (Left.is(tok::l_paren))
724 return false;
725 if (Left.is(tok::hash))
726 return false;
727 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
728 return false;
729 if (Right.is(tok::l_paren)) {
730 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
731 }
732 return true;
733 }
734
735 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
736 if (Right.Tok.is(tok::r_paren))
737 return false;
738 if (isBinaryOperator(Left))
739 return true;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000740 if (Right.Tok.is(tok::lessless))
741 return true;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000742 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) ||
743 Left.Tok.is(tok::semi) || Left.Tok.is(tok::equal) ||
744 Left.Tok.is(tok::ampamp) || Left.Tok.is(tok::pipepipe) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000745 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
746 }
747
748 const UnwrappedLine &Line;
749 FormatStyle Style;
750 SourceManager &SourceMgr;
751 std::vector<TokenAnnotation> Annotations;
752};
753
754class Formatter : public UnwrappedLineConsumer {
755public:
756 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
757 const std::vector<CharSourceRange> &Ranges)
758 : Style(Style),
759 Lex(Lex),
760 SourceMgr(SourceMgr),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000761 Ranges(Ranges),
762 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000763 }
764
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000765 virtual ~Formatter() {
766 }
767
Daniel Jasperbac016b2012-12-03 18:12:45 +0000768 tooling::Replacements format() {
Alexander Kornienko15757312012-12-06 18:03:27 +0000769 UnwrappedLineParser Parser(Style, Lex, SourceMgr, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000770 StructuralError = Parser.parse();
771 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
772 E = UnwrappedLines.end();
773 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000774 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000775 return Replaces;
776 }
777
778private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000779 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000780 UnwrappedLines.push_back(TheLine);
781 }
782
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000783 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000784 if (TheLine.Tokens.size() == 0)
785 return;
786
787 CharSourceRange LineRange =
788 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
789 TheLine.Tokens.back().Tok.getLocation());
790
791 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
792 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
793 Ranges[i].getBegin()) ||
794 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
795 LineRange.getBegin()))
796 continue;
797
798 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
799 Annotator.annotate();
800 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000801 Annotator.getAnnotations(), Replaces,
802 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 Formatter.format();
804 return;
805 }
806 }
807
808 FormatStyle Style;
809 Lexer &Lex;
810 SourceManager &SourceMgr;
811 tooling::Replacements Replaces;
812 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000813 std::vector<UnwrappedLine> UnwrappedLines;
814 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000815};
816
817tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
818 SourceManager &SourceMgr,
819 std::vector<CharSourceRange> Ranges) {
820 Formatter formatter(Style, Lex, SourceMgr, Ranges);
821 return formatter.format();
822}
823
824} // namespace format
825} // namespace clang