blob: a09f9d0e116255ac551ffcac3e01df6f6325e2f4 [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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperf7935112012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasperda16db32013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasperda16db32013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper7194e182013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
Nico Weber9efe2912013-01-10 23:11:41 +000042 TT_ObjCSelectorStart,
Nico Webera2a84952013-01-10 21:30:42 +000043 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_OverloadedOperator,
45 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000046 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_TemplateCloser,
48 TT_TemplateOpener,
49 TT_TrailingUnaryOperator,
50 TT_UnaryOperator,
51 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000052};
53
54enum LineType {
55 LT_Invalid,
56 LT_Other,
57 LT_PreprocessorDirective,
58 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000059 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000060 LT_ObjCMethodDecl,
61 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000062};
63
Daniel Jasper7c85fde2013-01-08 14:56:18 +000064class AnnotatedToken {
65public:
66 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000067 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
68 CanBreakBefore(false), MustBreakBefore(false),
69 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000070
71 bool is(tok::TokenKind Kind) const {
72 return FormatTok.Tok.is(Kind);
73 }
74 bool isNot(tok::TokenKind Kind) const {
75 return FormatTok.Tok.isNot(Kind);
76 }
77 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
78 return FormatTok.Tok.isObjCAtKeyword(Kind);
79 }
80
81 FormatToken FormatTok;
82
Daniel Jasperf7935112012-12-03 18:12:45 +000083 TokenType Type;
84
Daniel Jasperf7935112012-12-03 18:12:45 +000085 bool SpaceRequiredBefore;
86 bool CanBreakBefore;
87 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000088
89 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000090
91 std::vector<AnnotatedToken> Children;
92 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000093};
94
Daniel Jasper7c85fde2013-01-08 14:56:18 +000095static prec::Level getPrecedence(const AnnotatedToken &Tok) {
96 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000097}
98
Daniel Jasperf7935112012-12-03 18:12:45 +000099FormatStyle getLLVMStyle() {
100 FormatStyle LLVMStyle;
101 LLVMStyle.ColumnLimit = 80;
102 LLVMStyle.MaxEmptyLinesToKeep = 1;
103 LLVMStyle.PointerAndReferenceBindToType = false;
104 LLVMStyle.AccessModifierOffset = -2;
105 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000106 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000107 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000108 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000109 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Nico Weber9efe2912013-01-10 23:11:41 +0000110 LLVMStyle.ObjCSpaceBeforeReturnType = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000111 return LLVMStyle;
112}
113
114FormatStyle getGoogleStyle() {
115 FormatStyle GoogleStyle;
116 GoogleStyle.ColumnLimit = 80;
117 GoogleStyle.MaxEmptyLinesToKeep = 1;
118 GoogleStyle.PointerAndReferenceBindToType = true;
119 GoogleStyle.AccessModifierOffset = -1;
120 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000121 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000122 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000123 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Nico Webera6087752013-01-10 20:12:55 +0000124 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Nico Weber9efe2912013-01-10 23:11:41 +0000125 GoogleStyle.ObjCSpaceBeforeReturnType = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000126 return GoogleStyle;
127}
128
129struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000130 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000131 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000132 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000133};
134
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000135/// \brief Replaces the whitespace in front of \p Tok. Only call once for
136/// each \c FormatToken.
137static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
138 unsigned Spaces, const FormatStyle &Style,
139 SourceManager &SourceMgr,
140 tooling::Replacements &Replaces) {
141 Replaces.insert(tooling::Replacement(
142 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
143 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
144}
145
146/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
147/// backslashes to escape newlines inside a preprocessor directive.
148///
149/// This function and \c replaceWhitespace have the same behavior if
150/// \c Newlines == 0.
151static void replacePPWhitespace(
152 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
153 unsigned WhitespaceStartColumn, const FormatStyle &Style,
154 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
155 std::string NewLineText;
156 if (NewLines > 0) {
157 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
158 WhitespaceStartColumn);
159 for (unsigned i = 0; i < NewLines; ++i) {
160 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
161 NewLineText += "\\\n";
162 Offset = 0;
163 }
164 }
165 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
166 Tok.FormatTok.WhiteSpaceLength,
167 NewLineText + std::string(Spaces, ' ')));
168}
169
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000170/// \brief Checks whether the (remaining) \c UnwrappedLine starting with
171/// \p RootToken fits into \p Limit columns.
172bool fitsIntoLimit(const AnnotatedToken &RootToken, unsigned Limit) {
173 unsigned Columns = RootToken.FormatTok.TokenLength;
174 bool FitsOnALine = true;
175 const AnnotatedToken *Tok = &RootToken;
176 while (!Tok->Children.empty()) {
177 Tok = &Tok->Children[0];
178 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) + Tok->FormatTok.TokenLength;
179 // A special case for the colon of a constructor initializer as this only
180 // needs to be put on a new line if the line needs to be split.
181 if (Columns > Limit ||
182 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
183 FitsOnALine = false;
184 break;
185 }
186 };
187 return FitsOnALine;
188}
189
Daniel Jasperf7935112012-12-03 18:12:45 +0000190class UnwrappedLineFormatter {
191public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000192 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
193 const UnwrappedLine &Line, unsigned FirstIndent,
194 bool FitsOnALine, LineType CurrentLineType,
195 const AnnotatedToken &RootToken,
196 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000197 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000198 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000199 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000200 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000201 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000202 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000203 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 }
205
Manuel Klimek1abf7892013-01-04 23:34:14 +0000206 /// \brief Formats an \c UnwrappedLine.
207 ///
208 /// \returns The column after the last token in the last line of the
209 /// \c UnwrappedLine.
210 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000211 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000212 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000213 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000214 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000215 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000216 State.ForLoopVariablePos = 0;
217 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000218 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000219
220 // The first token has already been indented and thus consumed.
221 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000222
223 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000224 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000225 if (FitsOnALine) {
226 addTokenToState(false, false, State);
227 } else {
228 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
229 unsigned Break = calcPenalty(State, true, NoBreak);
230 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000231 if (State.NextToken != NULL &&
232 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
233 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
234 !fitsIntoLimit(*State.NextToken,
235 getColumnLimit() - State.Column - 1))
236 State.Stack.back().BreakAfterComma = true;
237 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000238 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000239 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000240 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000241 }
242
243private:
Daniel Jasper337816e2013-01-11 10:22:12 +0000244 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000245 ParenState(unsigned Indent, unsigned LastSpace)
246 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
247 BreakBeforeClosingBrace(false), BreakAfterComma(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000248
Daniel Jasperf7935112012-12-03 18:12:45 +0000249 /// \brief The position to which a specific parenthesis level needs to be
250 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000251 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000252
Daniel Jaspere9de2602012-12-06 09:56:08 +0000253 /// \brief The position of the last space on each level.
254 ///
255 /// Used e.g. to break like:
256 /// functionCall(Parameter, otherCall(
257 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000258 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000259
Daniel Jaspere9de2602012-12-06 09:56:08 +0000260 /// \brief The position the first "<<" operator encountered on each level.
261 ///
262 /// Used to align "<<" operators. 0 if no such operator has been encountered
263 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000264 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000265
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000266 /// \brief Whether a newline needs to be inserted before the block's closing
267 /// brace.
268 ///
269 /// We only want to insert a newline before the closing brace if there also
270 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000271 bool BreakBeforeClosingBrace;
272
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000273 bool BreakAfterComma;
274
Daniel Jasper337816e2013-01-11 10:22:12 +0000275 bool operator<(const ParenState &Other) const {
276 if (Indent != Other.Indent)
277 return Indent < Other.Indent;
278 if (LastSpace != Other.LastSpace)
279 return LastSpace < Other.LastSpace;
280 if (FirstLessLess != Other.FirstLessLess)
281 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000282 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
283 return BreakBeforeClosingBrace;
284 return BreakAfterComma;
Daniel Jasper337816e2013-01-11 10:22:12 +0000285 }
286 };
287
288 /// \brief The current state when indenting a unwrapped line.
289 ///
290 /// As the indenting tries different combinations this is copied by value.
291 struct LineState {
292 /// \brief The number of used columns in the current line.
293 unsigned Column;
294
295 /// \brief The token that needs to be next formatted.
296 const AnnotatedToken *NextToken;
297
298 /// \brief The parenthesis level of the first token on the current line.
299 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000300
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000301 /// \brief The column of the first variable in a for-loop declaration.
302 ///
303 /// Used to align the second variable if necessary.
304 unsigned ForLoopVariablePos;
305
306 /// \brief \c true if this line contains a continued for-loop section.
307 bool LineContainsContinuedForLoopSection;
308
Daniel Jasper337816e2013-01-11 10:22:12 +0000309 /// \brief A stack keeping track of properties applying to parenthesis
310 /// levels.
311 std::vector<ParenState> Stack;
312
313 /// \brief Comparison operator to be able to used \c LineState in \c map.
314 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000315 if (Other.NextToken != NextToken)
316 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 if (Other.Column != Column)
318 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000319 if (Other.StartOfLineLevel != StartOfLineLevel)
320 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000321 if (Other.ForLoopVariablePos != ForLoopVariablePos)
322 return Other.ForLoopVariablePos < ForLoopVariablePos;
323 if (Other.LineContainsContinuedForLoopSection !=
324 LineContainsContinuedForLoopSection)
325 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000326 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 }
328 };
329
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000330 /// \brief Appends the next token to \p State and updates information
331 /// necessary for indentation.
332 ///
333 /// Puts the token on the current line if \p Newline is \c true and adds a
334 /// line break and necessary indentation otherwise.
335 ///
336 /// If \p DryRun is \c false, also creates and stores the required
337 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000338 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000339 const AnnotatedToken &Current = *State.NextToken;
340 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 assert(State.Stack.size());
342 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000343
344 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000345 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000346 if (Current.is(tok::r_brace)) {
347 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000348 } else if (Current.is(tok::string_literal) &&
349 Previous.is(tok::string_literal)) {
350 State.Column = State.Column - Previous.FormatTok.TokenLength;
351 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000352 State.Stack[ParenLevel].FirstLessLess != 0) {
353 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000354 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000355 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
356 Current.is(tok::period) || Previous.is(tok::question) ||
357 Previous.Type == TT_ConditionalExpr)) {
358 // Indent and extra 4 spaces after if we know the current expression is
359 // continued. Don't do that on the top level, as we already indent 4
360 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000361 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000362 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000363 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000364 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000365 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000367 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000368 }
369
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000370 // A line starting with a closing brace is assumed to be correct for the
371 // same level as before the opening brace.
372 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000373
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000374 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000375 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000376
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000377 if (!DryRun) {
378 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000379 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
380 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000381 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000382 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000383 WhitespaceStartColumn, Style, SourceMgr,
384 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000385 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000386
Daniel Jasper337816e2013-01-11 10:22:12 +0000387 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000388 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000389 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000392 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
393 State.ForLoopVariablePos = State.Column -
394 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000395
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000396 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
397 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000398 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000399
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000401 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000402
Daniel Jasperbcab4302013-01-09 10:40:23 +0000403 // FIXME: Do we need to do this for assignments nested in other
404 // expressions?
405 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000406 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000407 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000408 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000409 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000410 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000411 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000412 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000413
Daniel Jasper206df732013-01-07 13:08:40 +0000414 // Top-level spaces that are not part of assignments are exempt as that
415 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000416 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000417 if (Spaces > 0 &&
418 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000419 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000420 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000421 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000422 if (Newline && Previous.is(tok::l_brace)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000423 State.Stack.back().BreakBeforeClosingBrace = true;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000424 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000425 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000426
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000427 /// \brief Mark the next token as consumed in \p State and modify its stacks
428 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000429 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000430 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000432
Daniel Jasper337816e2013-01-11 10:22:12 +0000433 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
434 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000435
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000436 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000437 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000438 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
439 Current.is(tok::l_brace) ||
440 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000441 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000442 if (Current.is(tok::l_brace)) {
443 // FIXME: This does not work with nested static initializers.
444 // Implement a better handling for static initializers and similar
445 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000447 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000448 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000449 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000450 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000451 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000452 }
453
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000454 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000455 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000456 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
457 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
458 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000459 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000460 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000461
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000462 if (State.NextToken->Children.empty())
463 State.NextToken = NULL;
464 else
465 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000466
467 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000468 }
469
Nico Weber49cbc2c2013-01-07 15:15:29 +0000470 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000471 unsigned splitPenalty(const AnnotatedToken &Tok) {
472 const AnnotatedToken &Left = Tok;
473 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000474
475 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000476 if (RootToken.is(tok::kw_for) &&
477 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000478 return 20;
479
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000480 if (Left.is(tok::semi) || Left.is(tok::comma) ||
481 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000483 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000484 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000485
Daniel Jasper399d24b2013-01-09 07:06:56 +0000486 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
487 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000488 prec::Level Level = getPrecedence(Left);
489
490 // Breaking after an assignment leads to a bad result as the two sides of
491 // the assignment are visually very close together.
492 if (Level == prec::Assignment)
493 return 50;
494
Daniel Jasperde5c2072012-12-24 00:13:23 +0000495 if (Level != prec::Unknown)
496 return Level;
497
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000498 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000499 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000500
Daniel Jasperf7935112012-12-03 18:12:45 +0000501 return 3;
502 }
503
Daniel Jasper2df93312013-01-09 10:16:05 +0000504 unsigned getColumnLimit() {
505 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
506 }
507
Daniel Jasperf7935112012-12-03 18:12:45 +0000508 /// \brief Calculate the number of lines needed to format the remaining part
509 /// of the unwrapped line.
510 ///
511 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000512 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 /// added after the previous token.
514 ///
515 /// \param StopAt is used for optimization. If we can determine that we'll
516 /// definitely need at least \p StopAt additional lines, we already know of a
517 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000518 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000519 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000520 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 return 0;
522
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000523 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000524 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000525 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000526 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000527 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000528 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000529 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000530 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000531 State.LineContainsContinuedForLoopSection)
532 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000533 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
534 State.NextToken->Type != TT_LineComment &&
535 State.Stack.back().BreakAfterComma)
536 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000537
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000538 unsigned CurrentPenalty = 0;
539 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000541 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000542 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 if (State.Stack.size() < State.StartOfLineLevel)
Daniel Jasper6d822722012-12-24 16:43:00 +0000544 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000546 }
547
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000548 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000549
Daniel Jasper2df93312013-01-09 10:16:05 +0000550 // Exceeding column limit is bad, assign penalty.
551 if (State.Column > getColumnLimit()) {
552 unsigned ExcessCharacters = State.Column - getColumnLimit();
553 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
554 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000555
Daniel Jasperf7935112012-12-03 18:12:45 +0000556 if (StopAt <= CurrentPenalty)
557 return UINT_MAX;
558 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000560 if (I != Memory.end()) {
561 // If this state has already been examined, we can safely return the
562 // previous result if we
563 // - have not hit the optimatization (and thus returned UINT_MAX) OR
564 // - are now computing for a smaller or equal StopAt.
565 unsigned SavedResult = I->second.first;
566 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000567 if (SavedResult != UINT_MAX)
568 return SavedResult + CurrentPenalty;
569 else if (StopAt <= SavedStopAt)
570 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000571 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000572
573 unsigned NoBreak = calcPenalty(State, false, StopAt);
574 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
575 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000576
577 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
578 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000579 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000580
581 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 }
583
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 FormatStyle Style;
585 SourceManager &SourceMgr;
586 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000587 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000588 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000589 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000592
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000593 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000595 StateMap Memory;
596
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 OptimizationParameters Parameters;
598};
599
600/// \brief Determines extra information about the tokens comprising an
601/// \c UnwrappedLine.
602class TokenAnnotator {
603public:
604 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000605 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000606 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
607 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000608 }
609
610 /// \brief A parser that gathers additional information about tokens.
611 ///
612 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
613 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
614 /// into template parameter lists.
615 class AnnotatingParser {
616 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000617 AnnotatingParser(AnnotatedToken &RootToken)
618 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000619 }
620
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000621 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000622 while (CurrentToken != NULL) {
623 if (CurrentToken->is(tok::greater)) {
624 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000625 next();
626 return true;
627 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
629 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000631 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
632 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000633 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000634 if (!consumeToken())
635 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 }
637 return false;
638 }
639
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000640 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000641 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
642 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000643 while (CurrentToken != NULL) {
644 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000645 next();
646 return true;
647 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000648 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000649 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000650 if (!consumeToken())
651 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 }
653 return false;
654 }
655
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000656 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000657 while (CurrentToken != NULL) {
658 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 next();
660 return true;
661 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000662 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000663 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000664 if (!consumeToken())
665 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000666 }
667 return false;
668 }
669
Daniel Jasper83a54d22013-01-10 09:26:47 +0000670 bool parseBrace() {
671 while (CurrentToken != NULL) {
672 if (CurrentToken->is(tok::r_brace)) {
673 next();
674 return true;
675 }
676 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
677 return false;
678 if (!consumeToken())
679 return false;
680 }
681 // Lines can currently end with '{'.
682 return true;
683 }
684
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000685 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000686 while (CurrentToken != NULL) {
687 if (CurrentToken->is(tok::colon)) {
688 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000689 next();
690 return true;
691 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000692 if (!consumeToken())
693 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000694 }
695 return false;
696 }
697
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000698 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000699 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
700 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000701 next();
702 if (!parseAngle())
703 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000704 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000705 parseLine();
706 return true;
707 }
708 return false;
709 }
710
Daniel Jasperc0880a92013-01-04 18:52:56 +0000711 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000712 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000713 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000714 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +0000715 case tok::plus:
716 case tok::minus:
717 // At the start of the line, +/- specific ObjectiveC method
718 // declarations.
719 if (Tok->Parent == NULL)
720 Tok->Type = TT_ObjCMethodSpecifier;
721 break;
722 case tok::l_paren: {
723 bool ParensWereObjCReturnType =
724 Tok->Parent && Tok->Parent->Type == TT_ObjCMethodSpecifier;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000725 if (!parseParens())
726 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000727 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
728 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000729 next();
Nico Weber9efe2912013-01-10 23:11:41 +0000730 } else if (CurrentToken != NULL && ParensWereObjCReturnType) {
731 CurrentToken->Type = TT_ObjCSelectorStart;
732 next();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000733 }
Nico Weber9efe2912013-01-10 23:11:41 +0000734 } break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000736 if (!parseSquare())
737 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000739 case tok::l_brace:
740 if (!parseBrace())
741 return false;
742 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000744 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000745 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000746 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000747 Tok->Type = TT_BinaryOperator;
748 CurrentToken = Tok;
749 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000750 }
751 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000752 case tok::r_paren:
753 case tok::r_square:
754 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000755 case tok::r_brace:
756 // Lines can start with '}'.
757 if (Tok->Parent != NULL)
758 return false;
759 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000760 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000761 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 break;
763 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 if (CurrentToken->is(tok::l_paren)) {
765 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000766 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000767 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
768 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000769 next();
770 }
771 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
773 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000774 next();
775 }
776 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000777 break;
778 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000779 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000781 case tok::kw_template:
782 parseTemplateDeclaration();
783 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000784 default:
785 break;
786 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000787 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000788 }
789
Daniel Jasper050948a52012-12-21 17:58:39 +0000790 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000791 while (CurrentToken != NULL) {
792 if (CurrentToken->is(tok::slash))
793 CurrentToken->Type = TT_DirectorySeparator;
794 else if (CurrentToken->is(tok::less))
795 CurrentToken->Type = TT_TemplateOpener;
796 else if (CurrentToken->is(tok::greater))
797 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000798 next();
799 }
800 }
801
802 void parsePreprocessorDirective() {
803 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000804 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000805 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000806 // Hashes in the middle of a line can lead to any strange token
807 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000808 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000809 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000810 switch (
811 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000812 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000813 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000814 parseIncludeDirective();
815 break;
816 default:
817 break;
818 }
819 }
820
Daniel Jasperda16db32013-01-07 10:48:50 +0000821 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000822 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000823 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000824 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000825 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000826 while (CurrentToken != NULL) {
827 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000828 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000829 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000830 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000831 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000832 if (KeywordVirtualFound)
833 return LT_VirtualFunctionDecl;
834 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000835 }
836
837 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000838 if (CurrentToken != NULL && !CurrentToken->Children.empty())
839 CurrentToken = &CurrentToken->Children[0];
840 else
841 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000842 }
843
844 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000846 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 };
848
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000849 void createAnnotatedTokens(AnnotatedToken &Current) {
850 if (!Current.FormatTok.Children.empty()) {
851 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
852 Current.Children.back().Parent = &Current;
853 createAnnotatedTokens(Current.Children.back());
854 }
855 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000856
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000857 void calculateExtraInformation(AnnotatedToken &Current) {
858 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
859
Manuel Klimek52b15152013-01-09 15:25:02 +0000860 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000861 Current.MustBreakBefore = true;
862 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000863 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
864 TT_LineComment || (Current.is(tok::string_literal) &&
865 Current.Parent->is(tok::string_literal))) {
866 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000867 } else {
868 Current.MustBreakBefore = false;
869 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000870 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000871 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000872 if (!Current.Children.empty())
873 calculateExtraInformation(Current.Children[0]);
874 }
875
876 bool annotate() {
877 createAnnotatedTokens(RootToken);
878
879 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000880 CurrentLineType = Parser.parseLine();
881 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000882 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000883
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000884 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000885
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000886 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000887 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000888 else if (RootToken.Type == TT_ObjCDecl)
889 CurrentLineType = LT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000890 else if (RootToken.Type == TT_ObjCProperty)
891 CurrentLineType = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +0000892
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000893 if (!RootToken.Children.empty())
894 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000895 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000896 }
897
Daniel Jasperda16db32013-01-07 10:48:50 +0000898 LineType getLineType() {
899 return CurrentLineType;
900 }
901
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902 const AnnotatedToken &getRootToken() {
903 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000904 }
905
906private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000907 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
908 if (getPrecedence(Current) == prec::Assignment ||
909 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
910 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000911
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000912 if (Current.Type == TT_Unknown) {
913 if (Current.is(tok::star) || Current.is(tok::amp)) {
914 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000915 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
916 Current.is(tok::caret)) {
917 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
919 Current.Type = determineIncrementUsage(Current);
920 } else if (Current.is(tok::exclaim)) {
921 Current.Type = TT_UnaryOperator;
922 } else if (isBinaryOperator(Current)) {
923 Current.Type = TT_BinaryOperator;
924 } else if (Current.is(tok::comment)) {
925 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
926 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000927 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000928 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000930 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000931 } else if (Current.is(tok::r_paren) &&
932 (Current.Parent->Type == TT_PointerOrReference ||
933 Current.Parent->Type == TT_TemplateCloser)) {
934 // FIXME: We need to get smarter and understand more cases of casts.
935 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000936 } else if (Current.is(tok::at) && Current.Children.size()) {
937 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
938 case tok::objc_interface:
939 case tok::objc_implementation:
940 case tok::objc_protocol:
941 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +0000942 break;
943 case tok::objc_property:
944 Current.Type = TT_ObjCProperty;
945 break;
Nico Weber2bb00742013-01-10 19:19:14 +0000946 default:
947 break;
948 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000949 }
950 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000951
952 if (!Current.Children.empty())
953 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000954 }
955
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000956 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000957 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000958 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000959 }
960
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
962 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000963 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000965 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000966 const FormatToken &PrevToken = Tok.Parent->FormatTok;
967 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000968
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000969 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
970 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000971 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
972 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000973 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000974
Daniel Jasper542de162013-01-02 15:46:59 +0000975 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000976 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
977 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
978 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
979 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000980 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000981
Daniel Jasper542de162013-01-02 15:46:59 +0000982 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
983 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000984 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000985
Daniel Jasper426702d2012-12-05 07:51:39 +0000986 // It is very unlikely that we are going to find a pointer or reference type
987 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000988 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000989 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000990
Daniel Jasperda16db32013-01-07 10:48:50 +0000991 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000992 }
993
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000994 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000995 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000996 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
997 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
998 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +0000999 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
1000 Tok.Parent->is(tok::at))
Daniel Jasperda16db32013-01-07 10:48:50 +00001001 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001002
1003 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001004 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001005 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001006
1007 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001008 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001009 }
1010
1011 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001012 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1013 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001014 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001015
Daniel Jasperda16db32013-01-07 10:48:50 +00001016 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 }
1018
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 bool spaceRequiredBetween(const AnnotatedToken &Left,
1020 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001021 if (Right.is(tok::hashhash))
1022 return Left.is(tok::hash);
1023 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1024 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001025 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1026 return false;
Nico Webera6087752013-01-10 20:12:55 +00001027 if (Right.is(tok::less) &&
1028 (Left.is(tok::kw_template) ||
1029 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 return true;
1031 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1032 return false;
1033 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1034 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001035 if (Left.is(tok::at) &&
1036 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1037 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001038 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1039 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001040 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1042 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001043 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001044 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001045 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1046 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001047 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001048 return Right.FormatTok.Tok.isLiteral() ||
1049 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001050 if (Right.is(tok::star) && Left.is(tok::l_paren))
1051 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1053 Right.is(tok::r_square))
1054 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001055 if (Left.is(tok::coloncolon) ||
1056 (Right.is(tok::coloncolon) &&
1057 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 return false;
1059 if (Left.is(tok::period) || Right.is(tok::period))
1060 return false;
1061 if (Left.is(tok::colon) || Right.is(tok::colon))
1062 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001063 if (Left.is(tok::l_paren))
1064 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001065 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001066 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1067 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1068 Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001069 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001070 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001071 if (Left.is(tok::at) &&
1072 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001073 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001074 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1075 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 return true;
1077 }
1078
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001079 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001080 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001081 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1082 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001083 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001084 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001085 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001086 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber9efe2912013-01-10 23:11:41 +00001087 return Style.ObjCSpaceBeforeReturnType || Tok.isNot(tok::l_paren);
1088 if (Tok.Type == TT_ObjCSelectorStart)
1089 return !Style.ObjCSpaceBeforeReturnType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001090 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001091 // Don't space between ')' and <id>
1092 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001093 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001094 // Don't space between ':' and '('
1095 return false;
1096 }
Nico Webera2a84952013-01-10 21:30:42 +00001097 if (CurrentLineType == LT_ObjCProperty &&
1098 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1099 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001100
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001101 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001102 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001103 if (Tok.Type == TT_OverloadedOperator)
1104 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001105 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001107 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001108 if (Tok.is(tok::colon))
1109 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001110 if (Tok.Parent->Type == TT_UnaryOperator ||
1111 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001112 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001113 if (Tok.Type == TT_UnaryOperator)
1114 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001115 Tok.Parent->isNot(tok::l_square) &&
1116 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1118 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001119 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1120 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 if (Tok.Type == TT_DirectorySeparator ||
1122 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001123 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001125 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001127 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001128 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001129 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001130 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001131 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001133 }
1134
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 bool canBreakBefore(const AnnotatedToken &Right) {
1136 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001137 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001138 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1139 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001140 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1142 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001143 // Don't break this identifier as ':' or identifier
1144 // before it will break.
1145 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001146 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1147 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001148 // Don't break at ':' if identifier before it can beak.
1149 return false;
1150 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001152 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001153 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001154 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001155 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001156 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001157 return false;
1158
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001159 if (Right.is(tok::comment))
1160 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001161 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001162 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001163 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001164 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1165 Left.is(tok::comma) || Right.is(tok::lessless) ||
1166 Right.is(tok::arrow) || Right.is(tok::period) ||
1167 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001168 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001169 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001170 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001171 }
1172
Daniel Jasperf7935112012-12-03 18:12:45 +00001173 FormatStyle Style;
1174 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001175 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001176 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001177 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001178};
1179
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001180class LexerBasedFormatTokenSource : public FormatTokenSource {
1181public:
1182 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001183 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184 IdentTable(Lex.getLangOpts()) {
1185 Lex.SetKeepWhitespaceMode(true);
1186 }
1187
1188 virtual FormatToken getNextToken() {
1189 if (GreaterStashed) {
1190 FormatTok.NewlinesBefore = 0;
1191 FormatTok.WhiteSpaceStart =
1192 FormatTok.Tok.getLocation().getLocWithOffset(1);
1193 FormatTok.WhiteSpaceLength = 0;
1194 GreaterStashed = false;
1195 return FormatTok;
1196 }
1197
1198 FormatTok = FormatToken();
1199 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001200 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001201 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001202 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1203 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001204
1205 // Consume and record whitespace until we find a significant token.
1206 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001207 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001208 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1209 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001210 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1211
1212 if (FormatTok.Tok.is(tok::eof))
1213 return FormatTok;
1214 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001215 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001216 }
Manuel Klimekef920692013-01-07 07:56:50 +00001217
1218 // Now FormatTok is the next non-whitespace token.
1219 FormatTok.TokenLength = Text.size();
1220
Manuel Klimek1abf7892013-01-04 23:34:14 +00001221 // In case the token starts with escaped newlines, we want to
1222 // take them into account as whitespace - this pattern is quite frequent
1223 // in macro definitions.
1224 // FIXME: What do we want to do with other escaped spaces, and escaped
1225 // spaces or newlines in the middle of tokens?
1226 // FIXME: Add a more explicit test.
1227 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001228 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001229 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001230 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001231 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001232 }
1233
1234 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001235 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001236 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001237 FormatTok.Tok.setKind(Info.getTokenID());
1238 }
1239
1240 if (FormatTok.Tok.is(tok::greatergreater)) {
1241 FormatTok.Tok.setKind(tok::greater);
1242 GreaterStashed = true;
1243 }
1244
1245 return FormatTok;
1246 }
1247
1248private:
1249 FormatToken FormatTok;
1250 bool GreaterStashed;
1251 Lexer &Lex;
1252 SourceManager &SourceMgr;
1253 IdentifierTable IdentTable;
1254
1255 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001256 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001257 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1258 Tok.getLength());
1259 }
1260};
1261
Daniel Jasperf7935112012-12-03 18:12:45 +00001262class Formatter : public UnwrappedLineConsumer {
1263public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001264 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1265 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001266 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001267 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001268 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001269
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001270 virtual ~Formatter() {
1271 }
1272
Daniel Jasperf7935112012-12-03 18:12:45 +00001273 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001274 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001275 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001276 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001277 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001278 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1279 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001280 I != E; ++I) {
1281 const UnwrappedLine &TheLine = *I;
1282 if (touchesRanges(TheLine)) {
1283 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
1284 if (!Annotator.annotate())
1285 break;
1286 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1287 TheLine.Level, TheLine.InPPDirective,
1288 PreviousEndOfLineColumn);
Daniel Jasper2408a8c2013-01-11 11:37:55 +00001289 unsigned Limit = Style.ColumnLimit - (TheLine.InPPDirective ? 1 : 0) -
1290 Indent;
1291 // Check whether the UnwrappedLine can be put onto a single line. If
1292 // so, this is bound to be the optimal solution (by definition) and we
1293 // don't need to analyze the entire solution space.
1294 bool FitsOnALine = fitsIntoLimit(Annotator.getRootToken(), Limit);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001295 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1296 FitsOnALine, Annotator.getLineType(),
1297 Annotator.getRootToken(), Replaces,
1298 StructuralError);
1299 PreviousEndOfLineColumn = Formatter.format();
1300 } else {
1301 // If we did not reformat this unwrapped line, the column at the end of
1302 // the last token is unchanged - thus, we can calculate the end of the
1303 // last token, and return the result.
1304 const FormatToken *Last = getLastLine(TheLine);
1305 PreviousEndOfLineColumn =
1306 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1307 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1308 Lex.getLangOpts()) -
1309 1;
1310 }
1311 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001312 return Replaces;
1313 }
1314
1315private:
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001316 const FormatToken *getLastLine(const UnwrappedLine &TheLine) {
1317 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001318 while (!Last->Children.empty())
1319 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001320 return Last;
1321 }
1322
1323 bool touchesRanges(const UnwrappedLine &TheLine) {
1324 const FormatToken *First = &TheLine.RootToken;
1325 const FormatToken *Last = getLastLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001326 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001327 First->Tok.getLocation(),
1328 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001329 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001330 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1331 Ranges[i].getBegin()) &&
1332 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1333 LineRange.getBegin()))
1334 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001335 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001336 return false;
1337 }
1338
1339 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1340 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001341 }
1342
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001343 /// \brief Add a new line and the required indent before the first Token
1344 /// of the \c UnwrappedLine if there was no structural parsing error.
1345 /// Returns the indent level of the \c UnwrappedLine.
1346 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1347 bool InPPDirective,
1348 unsigned PreviousEndOfLineColumn) {
1349 const FormatToken& Tok = RootToken.FormatTok;
1350 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1351 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1352
1353 unsigned Newlines = std::min(Tok.NewlinesBefore,
1354 Style.MaxEmptyLinesToKeep + 1);
1355 if (Newlines == 0 && !Tok.IsFirst)
1356 Newlines = 1;
1357 unsigned Indent = Level * 2;
1358
1359 bool IsAccessModifier = false;
1360 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1361 RootToken.is(tok::kw_private))
1362 IsAccessModifier = true;
1363 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1364 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1365 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1366 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1367 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1368 IsAccessModifier = true;
1369
1370 if (IsAccessModifier &&
1371 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1372 Indent += Style.AccessModifierOffset;
1373 if (!InPPDirective || Tok.HasUnescapedNewline) {
1374 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1375 } else {
1376 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1377 SourceMgr, Replaces);
1378 }
1379 return Indent;
1380 }
1381
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001382 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001383 FormatStyle Style;
1384 Lexer &Lex;
1385 SourceManager &SourceMgr;
1386 tooling::Replacements Replaces;
1387 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001388 std::vector<UnwrappedLine> UnwrappedLines;
1389 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001390};
1391
1392tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1393 SourceManager &SourceMgr,
1394 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001395 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1396 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1397 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1398 DiagnosticsEngine Diagnostics(
1399 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1400 &DiagnosticPrinter, false);
1401 Diagnostics.setSourceManager(&SourceMgr);
1402 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001403 return formatter.format();
1404}
1405
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001406LangOptions getFormattingLangOpts() {
1407 LangOptions LangOpts;
1408 LangOpts.CPlusPlus = 1;
1409 LangOpts.CPlusPlus11 = 1;
1410 LangOpts.Bool = 1;
1411 LangOpts.ObjC1 = 1;
1412 LangOpts.ObjC2 = 1;
1413 return LangOpts;
1414}
1415
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001416} // namespace format
1417} // namespace clang