blob: 45bd97d88dcbadb507564704a529f9ff1d4a6e7c [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,
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000040 TT_CtorInitializerColon,
Daniel Jasperaa1c9202012-12-05 14:57:28 +000041 TT_LineComment,
42 TT_BlockComment
43 };
Daniel Jasperf7935112012-12-03 18:12:45 +000044
45 TokenType Type;
46
Daniel Jasperf7935112012-12-03 18:12:45 +000047 bool SpaceRequiredBefore;
48 bool CanBreakBefore;
49 bool MustBreakBefore;
50};
51
52using llvm::MutableArrayRef;
53
54FormatStyle getLLVMStyle() {
55 FormatStyle LLVMStyle;
56 LLVMStyle.ColumnLimit = 80;
57 LLVMStyle.MaxEmptyLinesToKeep = 1;
58 LLVMStyle.PointerAndReferenceBindToType = false;
59 LLVMStyle.AccessModifierOffset = -2;
60 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000061 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000062 return LLVMStyle;
63}
64
65FormatStyle getGoogleStyle() {
66 FormatStyle GoogleStyle;
67 GoogleStyle.ColumnLimit = 80;
68 GoogleStyle.MaxEmptyLinesToKeep = 1;
69 GoogleStyle.PointerAndReferenceBindToType = true;
70 GoogleStyle.AccessModifierOffset = -1;
71 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000072 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000073 return GoogleStyle;
74}
75
76struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000077 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 Kornienko870f9eb2012-12-04 17:27:50 +000085 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000086 : Style(Style), SourceMgr(SourceMgr), Line(Line),
87 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000088 StructuralError(StructuralError) {
Daniel Jasperf7935112012-12-03 18:12:45 +000089 Parameters.PenaltyIndentLevel = 5;
90 }
91
92 void format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +000093 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000094 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +000095
96 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +000097 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +000098 State.Column = Indent;
Daniel Jaspere9de2602012-12-06 09:56:08 +000099 State.ConsumedTokens = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000100 State.Indent.push_back(Indent + 4);
101 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000102 State.FirstLessLess.push_back(0);
103
104 // The first token has already been indented and thus consumed.
105 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000106
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000107 // Check whether the UnwrappedLine can be put onto a single line. If so,
108 // this is bound to be the optimal solution (by definition) and we don't
109 // need to analyze the entire solution space.
110 unsigned Columns = State.Column;
111 bool FitsOnALine = true;
112 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
113 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
114 Line.Tokens[i].Tok.getLength();
115 // A special case for the colon of a constructor initializer as this only
116 // needs to be put on a new line if the line needs to be split.
117 if (Columns > Style.ColumnLimit ||
118 (Annotations[i].MustBreakBefore &&
119 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
120 FitsOnALine = false;
121 break;
122 }
123 }
124
Daniel Jasperf7935112012-12-03 18:12:45 +0000125 // Start iterating at 1 as we have correctly formatted of Token #0 above.
126 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000127 if (FitsOnALine) {
128 addTokenToState(false, false, State);
129 } else {
130 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
131 unsigned Break = calcPenalty(State, true, NoBreak);
132 addTokenToState(Break < NoBreak, false, State);
133 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000134 }
135 }
136
137private:
138 /// \brief The current state when indenting a unwrapped line.
139 ///
140 /// As the indenting tries different combinations this is copied by value.
141 struct IndentState {
142 /// \brief The number of used columns in the current line.
143 unsigned Column;
144
145 /// \brief The number of tokens already consumed.
146 unsigned ConsumedTokens;
147
148 /// \brief The position to which a specific parenthesis level needs to be
149 /// indented.
150 std::vector<unsigned> Indent;
151
Daniel Jaspere9de2602012-12-06 09:56:08 +0000152 /// \brief The position of the last space on each level.
153 ///
154 /// Used e.g. to break like:
155 /// functionCall(Parameter, otherCall(
156 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000157 std::vector<unsigned> LastSpace;
158
Daniel Jaspere9de2602012-12-06 09:56:08 +0000159 /// \brief The position the first "<<" operator encountered on each level.
160 ///
161 /// Used to align "<<" operators. 0 if no such operator has been encountered
162 /// on a level.
163 std::vector<unsigned> FirstLessLess;
164
Daniel Jasperf7935112012-12-03 18:12:45 +0000165 /// \brief Comparison operator to be able to used \c IndentState in \c map.
166 bool operator<(const IndentState &Other) const {
167 if (Other.ConsumedTokens != ConsumedTokens)
168 return Other.ConsumedTokens > ConsumedTokens;
169 if (Other.Column != Column)
170 return Other.Column > Column;
171 if (Other.Indent.size() != Indent.size())
172 return Other.Indent.size() > Indent.size();
173 for (int i = 0, e = Indent.size(); i != e; ++i) {
174 if (Other.Indent[i] != Indent[i])
175 return Other.Indent[i] > Indent[i];
176 }
177 if (Other.LastSpace.size() != LastSpace.size())
178 return Other.LastSpace.size() > LastSpace.size();
179 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
180 if (Other.LastSpace[i] != LastSpace[i])
181 return Other.LastSpace[i] > LastSpace[i];
182 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000183 if (Other.FirstLessLess.size() != FirstLessLess.size())
184 return Other.FirstLessLess.size() > FirstLessLess.size();
185 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
186 if (Other.FirstLessLess[i] != FirstLessLess[i])
187 return Other.FirstLessLess[i] > FirstLessLess[i];
188 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000189 return false;
190 }
191 };
192
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000193 /// \brief Appends the next token to \p State and updates information
194 /// necessary for indentation.
195 ///
196 /// Puts the token on the current line if \p Newline is \c true and adds a
197 /// line break and necessary indentation otherwise.
198 ///
199 /// If \p DryRun is \c false, also creates and stores the required
200 /// \c Replacement.
201 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000202 unsigned Index = State.ConsumedTokens;
203 const FormatToken &Current = Line.Tokens[Index];
204 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000205 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000206
207 if (Newline) {
208 if (Current.Tok.is(tok::string_literal) &&
209 Previous.Tok.is(tok::string_literal))
210 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000211 else if (Current.Tok.is(tok::lessless) &&
212 State.FirstLessLess[ParenLevel] != 0)
213 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000214 else if (ParenLevel != 0 &&
215 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
216 Current.Tok.is(tok::period)))
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000217 // Indent and extra 4 spaces after '=' as it continues an expression.
218 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000219 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper9b155472012-12-04 10:50:12 +0000220 else
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 State.Column = State.Indent[ParenLevel];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000222
Daniel Jasperf7935112012-12-03 18:12:45 +0000223 if (!DryRun)
224 replaceWhitespace(Current, 1, State.Column);
225
Daniel Jasper9b155472012-12-04 10:50:12 +0000226 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000227 if (Current.Tok.is(tok::colon) &&
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000228 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000229 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000230 } else {
231 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
232 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
233 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000234
Daniel Jasperf7935112012-12-03 18:12:45 +0000235 if (!DryRun)
236 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000237
238 if (Previous.Tok.is(tok::l_paren) ||
239 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000240 State.Indent[ParenLevel] = State.Column;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000241
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000243 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000244 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000245 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000246 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000247 moveStateToNextToken(State);
248 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000249
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000250 /// \brief Mark the next token as consumed in \p State and modify its stacks
251 /// accordingly.
252 void moveStateToNextToken(IndentState &State) {
253 unsigned Index = State.ConsumedTokens;
254 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000255 unsigned ParenLevel = State.Indent.size() - 1;
256
257 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
258 State.FirstLessLess[ParenLevel] = State.Column;
259
260 State.Column += Current.Tok.getLength();
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000261
262 // If we encounter an opening (, [ or <, we add a level to our stacks to
263 // prepare for the following tokens.
264 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
265 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
266 State.Indent.push_back(4 + State.LastSpace.back());
267 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000268 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000269 }
270
271 // If we encounter a closing ), ] or >, we can remove a level from our
272 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000273 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
274 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 State.Indent.pop_back();
276 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000277 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000278 }
279
280 ++State.ConsumedTokens;
281 }
282
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000283 /// \brief Calculate the panelty for splitting after the token at \p Index.
284 unsigned splitPenalty(unsigned Index) {
285 assert(Index < Line.Tokens.size() &&
286 "Tried to calculate penalty for splitting after the last token");
287 const FormatToken &Left = Line.Tokens[Index];
288 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000289 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000290 return 0;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000291 if (Left.Tok.is(tok::equal) || Left.Tok.is(tok::l_paren) ||
292 Left.Tok.is(tok::pipepipe) || Left.Tok.is(tok::ampamp))
Daniel Jasperf7935112012-12-03 18:12:45 +0000293 return 2;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000294
295 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
296 return 200;
297
Daniel Jasperf7935112012-12-03 18:12:45 +0000298 return 3;
299 }
300
301 /// \brief Calculate the number of lines needed to format the remaining part
302 /// of the unwrapped line.
303 ///
304 /// Assumes the formatting so far has led to
305 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
306 /// added after the previous token.
307 ///
308 /// \param StopAt is used for optimization. If we can determine that we'll
309 /// definitely need at least \p StopAt additional lines, we already know of a
310 /// better solution.
311 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
312 // We are at the end of the unwrapped line, so we don't need any more lines.
313 if (State.ConsumedTokens >= Line.Tokens.size())
314 return 0;
315
316 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
317 return UINT_MAX;
318 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
319 return UINT_MAX;
320
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000321 unsigned CurrentPenalty = 0;
322 if (NewLine) {
323 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000324 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000325 }
326
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000327 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000328
329 // Exceeding column limit is bad.
330 if (State.Column > Style.ColumnLimit)
331 return UINT_MAX;
332
Daniel Jasperf7935112012-12-03 18:12:45 +0000333 if (StopAt <= CurrentPenalty)
334 return UINT_MAX;
335 StopAt -= CurrentPenalty;
336
Daniel Jasperf7935112012-12-03 18:12:45 +0000337 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000338 if (I != Memory.end()) {
339 // If this state has already been examined, we can safely return the
340 // previous result if we
341 // - have not hit the optimatization (and thus returned UINT_MAX) OR
342 // - are now computing for a smaller or equal StopAt.
343 unsigned SavedResult = I->second.first;
344 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000345 if (SavedResult != UINT_MAX)
346 return SavedResult + CurrentPenalty;
347 else if (StopAt <= SavedStopAt)
348 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000349 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000350
351 unsigned NoBreak = calcPenalty(State, false, StopAt);
352 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
353 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000354
355 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
356 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000357 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000358
359 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000360 }
361
362 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
363 /// each \c FormatToken.
364 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
365 unsigned Spaces) {
366 Replaces.insert(tooling::Replacement(
367 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
368 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
369 }
370
371 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000372 /// of the \c UnwrappedLine if there was no structural parsing error.
373 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000374 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000375 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000376 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
377 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
378
379 unsigned Newlines =
380 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
381 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
382 if (Newlines == 0 && Offset != 0)
383 Newlines = 1;
384 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000385 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
386 Token.Tok.is(tok::kw_private)) &&
387 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000388 Indent += Style.AccessModifierOffset;
389 replaceWhitespace(Token, Newlines, Indent);
390 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 }
392
393 FormatStyle Style;
394 SourceManager &SourceMgr;
395 const UnwrappedLine &Line;
396 const std::vector<TokenAnnotation> &Annotations;
397 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000398 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000399
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000400 // A map from an indent state to a pair (Result, Used-StopAt).
401 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
402 StateMap Memory;
403
Daniel Jasperf7935112012-12-03 18:12:45 +0000404 OptimizationParameters Parameters;
405};
406
407/// \brief Determines extra information about the tokens comprising an
408/// \c UnwrappedLine.
409class TokenAnnotator {
410public:
411 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
412 SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000413 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000414 }
415
416 /// \brief A parser that gathers additional information about tokens.
417 ///
418 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
419 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
420 /// into template parameter lists.
421 class AnnotatingParser {
422 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000423 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000424 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000425 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 }
427
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000428 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000429 while (Index < Tokens.size()) {
430 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000431 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000432 next();
433 return true;
434 }
435 if (Tokens[Index].Tok.is(tok::r_paren) ||
436 Tokens[Index].Tok.is(tok::r_square))
437 return false;
438 if (Tokens[Index].Tok.is(tok::pipepipe) ||
439 Tokens[Index].Tok.is(tok::ampamp) ||
440 Tokens[Index].Tok.is(tok::question) ||
441 Tokens[Index].Tok.is(tok::colon))
442 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000443 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000444 }
445 return false;
446 }
447
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000448 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000449 while (Index < Tokens.size()) {
450 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000451 next();
452 return true;
453 }
454 if (Tokens[Index].Tok.is(tok::r_square))
455 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000456 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000457 }
458 return false;
459 }
460
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000462 while (Index < Tokens.size()) {
463 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000464 next();
465 return true;
466 }
467 if (Tokens[Index].Tok.is(tok::r_paren))
468 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000469 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000470 }
471 return false;
472 }
473
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000474 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000475 while (Index < Tokens.size()) {
476 if (Tokens[Index].Tok.is(tok::colon)) {
477 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
478 next();
479 return true;
480 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000481 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 }
483 return false;
484 }
485
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000486 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000487 unsigned CurrentIndex = Index;
488 next();
489 switch (Tokens[CurrentIndex].Tok.getKind()) {
490 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000491 parseParens();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000492 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
493 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
494 next();
495 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000496 break;
497 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000498 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000499 break;
500 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000501 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
503 else {
504 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
505 Index = CurrentIndex + 1;
506 }
507 break;
508 case tok::greater:
509 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
510 break;
511 case tok::kw_operator:
512 if (!Tokens[Index].Tok.is(tok::l_paren))
513 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
514 next();
515 break;
516 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000517 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000518 break;
519 default:
520 break;
521 }
522 }
523
524 void parseLine() {
525 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000526 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 }
528 }
529
530 void next() {
531 ++Index;
532 }
533
534 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000535 const SmallVector<FormatToken, 16> &Tokens;
536 std::vector<TokenAnnotation> &Annotations;
537 unsigned Index;
538 };
539
540 void annotate() {
541 Annotations.clear();
542 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
543 Annotations.push_back(TokenAnnotation());
544 }
545
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000546 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000547 Parser.parseLine();
548
549 determineTokenTypes();
550
551 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
552 TokenAnnotation &Annotation = Annotations[i];
553
554 Annotation.CanBreakBefore =
555 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
556
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000557 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
558 Annotation.MustBreakBefore = true;
559 Annotation.SpaceRequiredBefore = true;
560 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000561 Annotation.SpaceRequiredBefore =
562 Line.Tokens[0].Tok.isNot(tok::kw_case) && i != e - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000563 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
564 Annotation.SpaceRequiredBefore = false;
565 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
566 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000567 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
568 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000569 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
570 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000571 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000572 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000573 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000574 else
575 Annotation.SpaceRequiredBefore = false;
576 } else if (
577 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
578 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
579 Annotation.SpaceRequiredBefore = true;
580 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000581 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 Line.Tokens[i].Tok.is(tok::l_paren)) {
583 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000584 } else if (Line.Tokens[i].Tok.is(tok::less) &&
585 Line.Tokens[0].Tok.is(tok::hash)) {
586 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000587 } else {
588 Annotation.SpaceRequiredBefore =
589 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
590 }
591
592 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
593 (Line.Tokens[i].Tok.is(tok::string_literal) &&
594 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
595 Annotation.MustBreakBefore = true;
596 }
597
598 if (Annotation.MustBreakBefore)
599 Annotation.CanBreakBefore = true;
600 }
601 }
602
603 const std::vector<TokenAnnotation> &getAnnotations() {
604 return Annotations;
605 }
606
607private:
608 void determineTokenTypes() {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000609 bool AssignmentEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
611 TokenAnnotation &Annotation = Annotations[i];
612 const FormatToken &Tok = Line.Tokens[i];
613
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000614 if (Tok.Tok.is(tok::equal) || Tok.Tok.is(tok::plusequal) ||
615 Tok.Tok.is(tok::minusequal) || Tok.Tok.is(tok::starequal) ||
616 Tok.Tok.is(tok::slashequal))
617 AssignmentEncountered = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000618
Daniel Jasperf7935112012-12-03 18:12:45 +0000619 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp))
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000620 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8b529712012-12-04 13:02:32 +0000621 else if (isUnaryOperator(i))
Daniel Jasperf7935112012-12-03 18:12:45 +0000622 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
623 else if (isBinaryOperator(Line.Tokens[i]))
624 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
625 else if (Tok.Tok.is(tok::comment)) {
626 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
627 Tok.Tok.getLength());
628 if (Data.startswith("//"))
629 Annotation.Type = TokenAnnotation::TT_LineComment;
630 else
631 Annotation.Type = TokenAnnotation::TT_BlockComment;
632 }
633 }
634 }
635
Daniel Jasper8b529712012-12-04 13:02:32 +0000636 bool isUnaryOperator(unsigned Index) {
637 const Token &Tok = Line.Tokens[Index].Tok;
Daniel Jasper26333c32012-12-06 13:16:39 +0000638
639 // '++', '--' and '!' are always unary operators.
640 if (Tok.is(tok::minusminus) || Tok.is(tok::plusplus) ||
641 Tok.is(tok::exclaim))
642 return true;
643
644 // The other possible unary operators are '+' and '-' as we
645 // determine the usage of '*' and '&' in determineStarAmpUsage().
Daniel Jasper8b529712012-12-04 13:02:32 +0000646 if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus))
647 return false;
Daniel Jasper26333c32012-12-06 13:16:39 +0000648
649 // Use heuristics to recognize unary operators.
Daniel Jasper8b529712012-12-04 13:02:32 +0000650 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
651 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
652 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square))
653 return true;
Daniel Jasper26333c32012-12-06 13:16:39 +0000654
655 // Fall back to marking the token as binary operator.
Daniel Jasper8b529712012-12-04 13:02:32 +0000656 return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator;
657 }
658
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 bool isBinaryOperator(const FormatToken &Tok) {
660 switch (Tok.Tok.getKind()) {
661 case tok::equal:
662 case tok::equalequal:
Daniel Jasper426702d2012-12-05 07:51:39 +0000663 case tok::exclaimequal:
Daniel Jasperf7935112012-12-03 18:12:45 +0000664 case tok::star:
665 //case tok::amp:
666 case tok::plus:
667 case tok::slash:
668 case tok::minus:
669 case tok::ampamp:
670 case tok::pipe:
671 case tok::pipepipe:
672 case tok::percent:
673 return true;
674 default:
675 return false;
676 }
677 }
678
Daniel Jasper426702d2012-12-05 07:51:39 +0000679 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000680 bool AssignmentEncountered) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 if (Index == Annotations.size())
682 return TokenAnnotation::TT_Unknown;
683
684 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
685 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
686 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
687 return TokenAnnotation::TT_UnaryOperator;
688
689 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
690 Line.Tokens[Index + 1].Tok.isLiteral())
691 return TokenAnnotation::TT_BinaryOperator;
692
Daniel Jasper426702d2012-12-05 07:51:39 +0000693 // It is very unlikely that we are going to find a pointer or reference type
694 // definition on the RHS of an assignment.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000695 if (AssignmentEncountered)
Daniel Jasper426702d2012-12-05 07:51:39 +0000696 return TokenAnnotation::TT_BinaryOperator;
697
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 return TokenAnnotation::TT_PointerOrReference;
699 }
700
701 bool isIfForOrWhile(Token Tok) {
702 return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while);
703 }
704
705 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000706 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
707 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000708 if (Left.is(tok::kw_template) && Right.is(tok::less))
709 return true;
710 if (Left.is(tok::arrow) || Right.is(tok::arrow))
711 return false;
712 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
713 return false;
714 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
715 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000716 if (Right.is(tok::amp) || Right.is(tok::star))
717 return Left.isLiteral() ||
718 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
719 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000720 if (Left.is(tok::amp) || Left.is(tok::star))
721 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
722 if (Right.is(tok::star) && Left.is(tok::l_paren))
723 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000724 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
725 Right.is(tok::r_square))
726 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000727 if (Left.is(tok::coloncolon) ||
728 (Right.is(tok::coloncolon) &&
729 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000730 return false;
731 if (Left.is(tok::period) || Right.is(tok::period))
732 return false;
733 if (Left.is(tok::colon) || Right.is(tok::colon))
734 return true;
735 if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) ||
736 (Left.isAnyIdentifier() && Right.is(tok::plusplus)) ||
737 (Left.is(tok::minusminus) && Right.isAnyIdentifier()) ||
738 (Left.isAnyIdentifier() && Right.is(tok::minusminus)))
739 return false;
740 if (Left.is(tok::l_paren))
741 return false;
742 if (Left.is(tok::hash))
743 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000744 if (Right.is(tok::l_paren)) {
745 return !Left.isAnyIdentifier() || isIfForOrWhile(Left);
746 }
747 return true;
748 }
749
750 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jaspere25509f2012-12-17 11:29:41 +0000751 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
752 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000753 return false;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000754 if (isBinaryOperator(Left) || Right.Tok.is(tok::lessless) ||
755 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000756 return true;
Daniel Jaspere25509f2012-12-17 11:29:41 +0000757 return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) || Left.Tok.is(
758 tok::semi) || Left.Tok.is(tok::equal) || Left.Tok.is(tok::ampamp) ||
759 Left.Tok.is(tok::pipepipe) || Left.Tok.is(tok::l_brace) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000760 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
761 }
762
763 const UnwrappedLine &Line;
764 FormatStyle Style;
765 SourceManager &SourceMgr;
766 std::vector<TokenAnnotation> Annotations;
767};
768
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000769class LexerBasedFormatTokenSource : public FormatTokenSource {
770public:
771 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000772 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000773 IdentTable(Lex.getLangOpts()) {
774 Lex.SetKeepWhitespaceMode(true);
775 }
776
777 virtual FormatToken getNextToken() {
778 if (GreaterStashed) {
779 FormatTok.NewlinesBefore = 0;
780 FormatTok.WhiteSpaceStart =
781 FormatTok.Tok.getLocation().getLocWithOffset(1);
782 FormatTok.WhiteSpaceLength = 0;
783 GreaterStashed = false;
784 return FormatTok;
785 }
786
787 FormatTok = FormatToken();
788 Lex.LexFromRawLexer(FormatTok.Tok);
789 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
790
791 // Consume and record whitespace until we find a significant token.
792 while (FormatTok.Tok.is(tok::unknown)) {
793 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
794 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
795
796 if (FormatTok.Tok.is(tok::eof))
797 return FormatTok;
798 Lex.LexFromRawLexer(FormatTok.Tok);
799 }
800
801 if (FormatTok.Tok.is(tok::raw_identifier)) {
802 const IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
803 FormatTok.Tok.setKind(Info.getTokenID());
804 }
805
806 if (FormatTok.Tok.is(tok::greatergreater)) {
807 FormatTok.Tok.setKind(tok::greater);
808 GreaterStashed = true;
809 }
810
811 return FormatTok;
812 }
813
814private:
815 FormatToken FormatTok;
816 bool GreaterStashed;
817 Lexer &Lex;
818 SourceManager &SourceMgr;
819 IdentifierTable IdentTable;
820
821 /// Returns the text of \c FormatTok.
822 StringRef tokenText(Token &Tok) {
823 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
824 Tok.getLength());
825 }
826};
827
Daniel Jasperf7935112012-12-03 18:12:45 +0000828class Formatter : public UnwrappedLineConsumer {
829public:
830 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
831 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000832 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000833 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000834 }
835
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000836 virtual ~Formatter() {
837 }
838
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000840 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
841 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000842 StructuralError = Parser.parse();
843 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
844 E = UnwrappedLines.end();
845 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000846 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 return Replaces;
848 }
849
850private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000851 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000852 UnwrappedLines.push_back(TheLine);
853 }
854
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000855 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000856 if (TheLine.Tokens.size() == 0)
857 return;
858
859 CharSourceRange LineRange =
860 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
861 TheLine.Tokens.back().Tok.getLocation());
862
863 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
864 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
865 Ranges[i].getBegin()) ||
866 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
867 LineRange.getBegin()))
868 continue;
869
870 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
871 Annotator.annotate();
872 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000873 Annotator.getAnnotations(), Replaces,
874 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 Formatter.format();
876 return;
877 }
878 }
879
880 FormatStyle Style;
881 Lexer &Lex;
882 SourceManager &SourceMgr;
883 tooling::Replacements Replaces;
884 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000885 std::vector<UnwrappedLine> UnwrappedLines;
886 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000887};
888
889tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
890 SourceManager &SourceMgr,
891 std::vector<CharSourceRange> Ranges) {
892 Formatter formatter(Style, Lex, SourceMgr, Ranges);
893 return formatter.format();
894}
895
896} // namespace format
897} // namespace clang