blob: de92b75b0bb0732ed4ae3a47e08b9e5166c63f3d [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,
Daniel Jasper7194e182013-01-10 11:14:08 +000040 TT_ObjCMethodSpecifier,
41 TT_OverloadedOperator,
42 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000043 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_TemplateCloser,
45 TT_TemplateOpener,
46 TT_TrailingUnaryOperator,
47 TT_UnaryOperator,
48 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000049};
50
51enum LineType {
52 LT_Invalid,
53 LT_Other,
54 LT_PreprocessorDirective,
55 LT_VirtualFunctionDecl,
56 LT_ObjCMethodDecl
57};
58
Daniel Jasper7c85fde2013-01-08 14:56:18 +000059class AnnotatedToken {
60public:
61 AnnotatedToken(const FormatToken &FormatTok)
62 : FormatTok(FormatTok), Type(TT_Unknown),
63 ClosesTemplateDeclaration(false), Parent(NULL) {
64 }
65
66 bool is(tok::TokenKind Kind) const {
67 return FormatTok.Tok.is(Kind);
68 }
69 bool isNot(tok::TokenKind Kind) const {
70 return FormatTok.Tok.isNot(Kind);
71 }
72 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
73 return FormatTok.Tok.isObjCAtKeyword(Kind);
74 }
75
76 FormatToken FormatTok;
77
Daniel Jasperf7935112012-12-03 18:12:45 +000078 TokenType Type;
79
Daniel Jasperf7935112012-12-03 18:12:45 +000080 bool SpaceRequiredBefore;
81 bool CanBreakBefore;
82 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000083
84 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000085
86 std::vector<AnnotatedToken> Children;
87 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000088};
89
Daniel Jasper7c85fde2013-01-08 14:56:18 +000090static prec::Level getPrecedence(const AnnotatedToken &Tok) {
91 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000092}
93
Daniel Jasperf7935112012-12-03 18:12:45 +000094using llvm::MutableArrayRef;
95
96FormatStyle getLLVMStyle() {
97 FormatStyle LLVMStyle;
98 LLVMStyle.ColumnLimit = 80;
99 LLVMStyle.MaxEmptyLinesToKeep = 1;
100 LLVMStyle.PointerAndReferenceBindToType = false;
101 LLVMStyle.AccessModifierOffset = -2;
102 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000103 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000104 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 return LLVMStyle;
106}
107
108FormatStyle getGoogleStyle() {
109 FormatStyle GoogleStyle;
110 GoogleStyle.ColumnLimit = 80;
111 GoogleStyle.MaxEmptyLinesToKeep = 1;
112 GoogleStyle.PointerAndReferenceBindToType = true;
113 GoogleStyle.AccessModifierOffset = -1;
114 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000115 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000116 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000117 return GoogleStyle;
118}
119
120struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000121 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000122 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000123 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000124};
125
126class UnwrappedLineFormatter {
127public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000128 UnwrappedLineFormatter(
129 const FormatStyle &Style, SourceManager &SourceMgr,
130 const UnwrappedLine &Line, unsigned PreviousEndOfLineColumn,
131 LineType CurrentLineType, const AnnotatedToken &RootToken,
132 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000133 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek1abf7892013-01-04 23:34:14 +0000134 PreviousEndOfLineColumn(PreviousEndOfLineColumn),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000135 CurrentLineType(CurrentLineType), RootToken(RootToken),
Daniel Jasperda16db32013-01-07 10:48:50 +0000136 Replaces(Replaces), StructuralError(StructuralError) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000137 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000138 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000139 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000140 }
141
Manuel Klimek1abf7892013-01-04 23:34:14 +0000142 /// \brief Formats an \c UnwrappedLine.
143 ///
144 /// \returns The column after the last token in the last line of the
145 /// \c UnwrappedLine.
146 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000147 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000148 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000149
150 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000151 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000152 State.Column = Indent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000153 State.NextToken = &RootToken;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000154 State.Indent.push_back(Indent + 4);
155 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000156 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000157 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000158 State.ForLoopVariablePos = 0;
159 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000160 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000161
162 // The first token has already been indented and thus consumed.
163 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000164
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000165 // Check whether the UnwrappedLine can be put onto a single line. If so,
166 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasperc0880a92013-01-04 18:52:56 +0000167 // need to analyze the entire solution space.
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000168 unsigned Columns = State.Column;
169 bool FitsOnALine = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000170 const AnnotatedToken *Tok = State.NextToken;
171 while (Tok != NULL) {
172 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
173 Tok->FormatTok.TokenLength;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000174 // A special case for the colon of a constructor initializer as this only
175 // needs to be put on a new line if the line needs to be split.
Manuel Klimek38ba11e2013-01-07 09:24:17 +0000176 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000177 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000178 FitsOnALine = false;
179 break;
180 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000181 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000182 }
183
Daniel Jasperf7935112012-12-03 18:12:45 +0000184 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000185 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000186 if (FitsOnALine) {
187 addTokenToState(false, false, State);
188 } else {
189 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
190 unsigned Break = calcPenalty(State, true, NoBreak);
191 addTokenToState(Break < NoBreak, false, State);
192 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000193 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000194 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000195 }
196
197private:
198 /// \brief The current state when indenting a unwrapped line.
199 ///
200 /// As the indenting tries different combinations this is copied by value.
201 struct IndentState {
202 /// \brief The number of used columns in the current line.
203 unsigned Column;
204
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000205 const AnnotatedToken *NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000206
Daniel Jasper6d822722012-12-24 16:43:00 +0000207 /// \brief The parenthesis level of the first token on the current line.
208 unsigned StartOfLineLevel;
209
Daniel Jasperf7935112012-12-03 18:12:45 +0000210 /// \brief The position to which a specific parenthesis level needs to be
211 /// indented.
212 std::vector<unsigned> Indent;
213
Daniel Jaspere9de2602012-12-06 09:56:08 +0000214 /// \brief The position of the last space on each level.
215 ///
216 /// Used e.g. to break like:
217 /// functionCall(Parameter, otherCall(
218 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000219 std::vector<unsigned> LastSpace;
220
Daniel Jaspere9de2602012-12-06 09:56:08 +0000221 /// \brief The position the first "<<" operator encountered on each level.
222 ///
223 /// Used to align "<<" operators. 0 if no such operator has been encountered
224 /// on a level.
225 std::vector<unsigned> FirstLessLess;
226
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000227 /// \brief Whether a newline needs to be inserted before the block's closing
228 /// brace.
229 ///
230 /// We only want to insert a newline before the closing brace if there also
231 /// was a newline after the beginning left brace.
232 std::vector<bool> BreakBeforeClosingBrace;
233
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000234 /// \brief The column of the first variable in a for-loop declaration.
235 ///
236 /// Used to align the second variable if necessary.
237 unsigned ForLoopVariablePos;
238
239 /// \brief \c true if this line contains a continued for-loop section.
240 bool LineContainsContinuedForLoopSection;
241
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 /// \brief Comparison operator to be able to used \c IndentState in \c map.
243 bool operator<(const IndentState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000244 if (Other.NextToken != NextToken)
245 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000246 if (Other.Column != Column)
247 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000248 if (Other.StartOfLineLevel != StartOfLineLevel)
249 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000250 if (Other.Indent.size() != Indent.size())
251 return Other.Indent.size() > Indent.size();
252 for (int i = 0, e = Indent.size(); i != e; ++i) {
253 if (Other.Indent[i] != Indent[i])
254 return Other.Indent[i] > Indent[i];
255 }
256 if (Other.LastSpace.size() != LastSpace.size())
257 return Other.LastSpace.size() > LastSpace.size();
258 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
259 if (Other.LastSpace[i] != LastSpace[i])
260 return Other.LastSpace[i] > LastSpace[i];
261 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000262 if (Other.FirstLessLess.size() != FirstLessLess.size())
263 return Other.FirstLessLess.size() > FirstLessLess.size();
264 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
265 if (Other.FirstLessLess[i] != FirstLessLess[i])
266 return Other.FirstLessLess[i] > FirstLessLess[i];
267 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000268 if (Other.ForLoopVariablePos != ForLoopVariablePos)
269 return Other.ForLoopVariablePos < ForLoopVariablePos;
270 if (Other.LineContainsContinuedForLoopSection !=
271 LineContainsContinuedForLoopSection)
272 return LineContainsContinuedForLoopSection;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000273 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
274 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 return false;
276 }
277 };
278
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000279 /// \brief Appends the next token to \p State and updates information
280 /// necessary for indentation.
281 ///
282 /// Puts the token on the current line if \p Newline is \c true and adds a
283 /// line break and necessary indentation otherwise.
284 ///
285 /// If \p DryRun is \c false, also creates and stores the required
286 /// \c Replacement.
287 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000288 const AnnotatedToken &Current = *State.NextToken;
289 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weber51306d22013-01-10 00:25:19 +0000290 assert(State.Indent.size());
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000291 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000292
293 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000294 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000295 if (Current.is(tok::r_brace)) {
296 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000297 } else if (Current.is(tok::string_literal) &&
298 Previous.is(tok::string_literal)) {
299 State.Column = State.Column - Previous.FormatTok.TokenLength;
300 } else if (Current.is(tok::lessless) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000301 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000302 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000303 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000304 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
305 Current.is(tok::period) || Previous.is(tok::question) ||
306 Previous.Type == TT_ConditionalExpr)) {
307 // Indent and extra 4 spaces after if we know the current expression is
308 // continued. Don't do that on the top level, as we already indent 4
309 // there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000310 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000311 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000312 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000313 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000314 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000315 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000316 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000317 }
318
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000319 // A line starting with a closing brace is assumed to be correct for the
320 // same level as before the opening brace.
321 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000322
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000323 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000324 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000325
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000326 if (!DryRun) {
327 if (!Line.InPPDirective)
Daniel Jasper399d24b2013-01-09 07:06:56 +0000328 replaceWhitespace(Current.FormatTok, 1, State.Column);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000329 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000330 replacePPWhitespace(Current.FormatTok, 1, State.Column,
331 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000332 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000333
Daniel Jasper89058942013-01-09 09:50:48 +0000334 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000335 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000336 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000337 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000338 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000339 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
340 State.ForLoopVariablePos = State.Column -
341 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000342
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000343 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
344 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000345 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000346
Daniel Jasperf7935112012-12-03 18:12:45 +0000347 if (!DryRun)
348 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000349
Daniel Jasperbcab4302013-01-09 10:40:23 +0000350 // FIXME: Do we need to do this for assignments nested in other
351 // expressions?
352 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000353 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000354 Previous.is(tok::kw_return)))
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000355 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000356 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000357 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000358 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000359 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000360
Daniel Jasper206df732013-01-07 13:08:40 +0000361 // Top-level spaces that are not part of assignments are exempt as that
362 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000363 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000364 if (Spaces > 0 &&
365 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000366 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000367 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000368 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000369 if (Newline && Previous.is(tok::l_brace)) {
370 State.BreakBeforeClosingBrace.back() = true;
371 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000372 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000373
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000374 /// \brief Mark the next token as consumed in \p State and modify its stacks
375 /// accordingly.
376 void moveStateToNextToken(IndentState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000377 const AnnotatedToken &Current = *State.NextToken;
Nico Weber51306d22013-01-10 00:25:19 +0000378 assert(State.Indent.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000379 unsigned ParenLevel = State.Indent.size() - 1;
380
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000381 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000382 State.FirstLessLess[ParenLevel] = State.Column;
383
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000384 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000385 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000386 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
387 Current.is(tok::l_brace) ||
388 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000389 if (Current.is(tok::l_brace)) {
390 // FIXME: This does not work with nested static initializers.
391 // Implement a better handling for static initializers and similar
392 // constructs.
393 State.Indent.push_back(Line.Level * 2 + 2);
394 } else {
395 State.Indent.push_back(4 + State.LastSpace.back());
396 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000397 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000398 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000399 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000400 }
401
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000402 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000403 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000404 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
405 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
406 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000407 State.Indent.pop_back();
408 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000409 State.FirstLessLess.pop_back();
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000410 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000412
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000413 if (State.NextToken->Children.empty())
414 State.NextToken = NULL;
415 else
416 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000417
418 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000419 }
420
Nico Weber49cbc2c2013-01-07 15:15:29 +0000421 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000422 unsigned splitPenalty(const AnnotatedToken &Tok) {
423 const AnnotatedToken &Left = Tok;
424 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000425
426 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000427 if (RootToken.is(tok::kw_for) &&
428 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000429 return 20;
430
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000431 if (Left.is(tok::semi) || Left.is(tok::comma) ||
432 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000433 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000434 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000435 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000436
Daniel Jasper399d24b2013-01-09 07:06:56 +0000437 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
438 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000439 prec::Level Level = getPrecedence(Left);
440
441 // Breaking after an assignment leads to a bad result as the two sides of
442 // the assignment are visually very close together.
443 if (Level == prec::Assignment)
444 return 50;
445
Daniel Jasperde5c2072012-12-24 00:13:23 +0000446 if (Level != prec::Unknown)
447 return Level;
448
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000449 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000450 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000451
Daniel Jasperf7935112012-12-03 18:12:45 +0000452 return 3;
453 }
454
Daniel Jasper2df93312013-01-09 10:16:05 +0000455 unsigned getColumnLimit() {
456 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
457 }
458
Daniel Jasperf7935112012-12-03 18:12:45 +0000459 /// \brief Calculate the number of lines needed to format the remaining part
460 /// of the unwrapped line.
461 ///
462 /// Assumes the formatting so far has led to
463 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
464 /// added after the previous token.
465 ///
466 /// \param StopAt is used for optimization. If we can determine that we'll
467 /// definitely need at least \p StopAt additional lines, we already know of a
468 /// better solution.
469 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
470 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000471 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000472 return 0;
473
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000474 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000475 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000476 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000477 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000478 if (!NewLine && State.NextToken->is(tok::r_brace) &&
479 State.BreakBeforeClosingBrace.back())
480 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000481 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000482 State.LineContainsContinuedForLoopSection)
483 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000484
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000485 unsigned CurrentPenalty = 0;
486 if (NewLine) {
487 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000488 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000489 } else {
490 if (State.Indent.size() < State.StartOfLineLevel)
491 CurrentPenalty += Parameters.PenaltyLevelDecrease *
492 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000493 }
494
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000495 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000496
Daniel Jasper2df93312013-01-09 10:16:05 +0000497 // Exceeding column limit is bad, assign penalty.
498 if (State.Column > getColumnLimit()) {
499 unsigned ExcessCharacters = State.Column - getColumnLimit();
500 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
501 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000502
Daniel Jasperf7935112012-12-03 18:12:45 +0000503 if (StopAt <= CurrentPenalty)
504 return UINT_MAX;
505 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000507 if (I != Memory.end()) {
508 // If this state has already been examined, we can safely return the
509 // previous result if we
510 // - have not hit the optimatization (and thus returned UINT_MAX) OR
511 // - are now computing for a smaller or equal StopAt.
512 unsigned SavedResult = I->second.first;
513 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000514 if (SavedResult != UINT_MAX)
515 return SavedResult + CurrentPenalty;
516 else if (StopAt <= SavedStopAt)
517 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000518 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000519
520 unsigned NoBreak = calcPenalty(State, false, StopAt);
521 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
522 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000523
524 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
525 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000526 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000527
528 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000529 }
530
531 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
532 /// each \c FormatToken.
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Daniel Jasperf7935112012-12-03 18:12:45 +0000534 unsigned Spaces) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000535 Replaces.insert(tooling::Replacement(
Daniel Jasper399d24b2013-01-09 07:06:56 +0000536 SourceMgr, Tok.FormatTok.WhiteSpaceStart,
537 Tok.FormatTok.WhiteSpaceLength,
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000538 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
539 }
540
541 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
542 /// backslashes to escape newlines inside a preprocessor directive.
543 ///
544 /// This function and \c replaceWhitespace have the same behavior if
545 /// \c Newlines == 0.
Daniel Jasper399d24b2013-01-09 07:06:56 +0000546 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000547 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000548 std::string NewLineText;
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000549 if (NewLines > 0) {
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000550 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
551 WhitespaceStartColumn);
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000552 for (unsigned i = 0; i < NewLines; ++i) {
553 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
554 NewLineText += "\\\n";
555 Offset = 0;
556 }
557 }
Daniel Jasper399d24b2013-01-09 07:06:56 +0000558 Replaces.insert(
559 tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
560 Tok.FormatTok.WhiteSpaceLength,
561 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperf7935112012-12-03 18:12:45 +0000562 }
563
564 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000565 /// of the \c UnwrappedLine if there was no structural parsing error.
566 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000567 unsigned formatFirstToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000568 const FormatToken &Tok = RootToken.FormatTok;
569 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
570 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000571
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 unsigned Newlines = std::min(Tok.NewlinesBefore,
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000573 Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000574 if (Newlines == 0 && !Tok.IsFirst)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000575 Newlines = 1;
576 unsigned Indent = Line.Level * 2;
Nico Weber04e9f1a2013-01-07 19:05:19 +0000577
578 bool IsAccessModifier = false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000579 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
580 RootToken.is(tok::kw_private))
Nico Weber04e9f1a2013-01-07 19:05:19 +0000581 IsAccessModifier = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000582 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
583 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
584 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
585 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
586 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
Nico Weber04e9f1a2013-01-07 19:05:19 +0000587 IsAccessModifier = true;
588
589 if (IsAccessModifier &&
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000590 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000591 Indent += Style.AccessModifierOffset;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000592 if (!Line.InPPDirective || Tok.HasUnescapedNewline)
593 replaceWhitespace(Tok, Newlines, Indent);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000594 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000595 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000596 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 }
598
599 FormatStyle Style;
600 SourceManager &SourceMgr;
601 const UnwrappedLine &Line;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000602 const unsigned PreviousEndOfLineColumn;
Daniel Jasperda16db32013-01-07 10:48:50 +0000603 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000604 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000605 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000606 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000607
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000608 // A map from an indent state to a pair (Result, Used-StopAt).
609 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
610 StateMap Memory;
611
Daniel Jasperf7935112012-12-03 18:12:45 +0000612 OptimizationParameters Parameters;
613};
614
615/// \brief Determines extra information about the tokens comprising an
616/// \c UnwrappedLine.
617class TokenAnnotator {
618public:
619 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000620 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000621 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
622 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 }
624
625 /// \brief A parser that gathers additional information about tokens.
626 ///
627 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
628 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
629 /// into template parameter lists.
630 class AnnotatingParser {
631 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000632 AnnotatingParser(AnnotatedToken &RootToken)
633 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000634 }
635
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000636 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000637 while (CurrentToken != NULL) {
638 if (CurrentToken->is(tok::greater)) {
639 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000640 next();
641 return true;
642 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000643 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
644 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000645 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000646 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
647 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000648 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000649 if (!consumeToken())
650 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000651 }
652 return false;
653 }
654
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000655 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000656 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
657 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000658 while (CurrentToken != NULL) {
659 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 next();
661 return true;
662 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000663 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000664 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000665 if (!consumeToken())
666 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000667 }
668 return false;
669 }
670
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000671 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000672 while (CurrentToken != NULL) {
673 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000674 next();
675 return true;
676 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000677 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000678 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000679 if (!consumeToken())
680 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 }
682 return false;
683 }
684
Daniel Jasper83a54d22013-01-10 09:26:47 +0000685 bool parseBrace() {
686 while (CurrentToken != NULL) {
687 if (CurrentToken->is(tok::r_brace)) {
688 next();
689 return true;
690 }
691 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
692 return false;
693 if (!consumeToken())
694 return false;
695 }
696 // Lines can currently end with '{'.
697 return true;
698 }
699
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000700 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000701 while (CurrentToken != NULL) {
702 if (CurrentToken->is(tok::colon)) {
703 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000704 next();
705 return true;
706 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000707 if (!consumeToken())
708 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000709 }
710 return false;
711 }
712
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000713 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000714 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
715 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000716 next();
717 if (!parseAngle())
718 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000719 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000720 parseLine();
721 return true;
722 }
723 return false;
724 }
725
Daniel Jasperc0880a92013-01-04 18:52:56 +0000726 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000727 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000728 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000729 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000730 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000731 if (!parseParens())
732 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000733 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
734 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000735 next();
736 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 break;
738 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000739 if (!parseSquare())
740 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000741 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000742 case tok::l_brace:
743 if (!parseBrace())
744 return false;
745 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000746 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000747 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000748 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000749 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000750 Tok->Type = TT_BinaryOperator;
751 CurrentToken = Tok;
752 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000753 }
754 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000755 case tok::r_paren:
756 case tok::r_square:
757 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000758 case tok::r_brace:
759 // Lines can start with '}'.
760 if (Tok->Parent != NULL)
761 return false;
762 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000763 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 break;
766 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000767 if (CurrentToken->is(tok::l_paren)) {
768 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000769 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000770 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
771 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000772 next();
773 }
774 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000775 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
776 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000777 next();
778 }
779 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 break;
781 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000782 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000783 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000784 case tok::kw_template:
785 parseTemplateDeclaration();
786 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000787 default:
788 break;
789 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000790 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000791 }
792
Daniel Jasper050948a52012-12-21 17:58:39 +0000793 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000794 while (CurrentToken != NULL) {
795 if (CurrentToken->is(tok::slash))
796 CurrentToken->Type = TT_DirectorySeparator;
797 else if (CurrentToken->is(tok::less))
798 CurrentToken->Type = TT_TemplateOpener;
799 else if (CurrentToken->is(tok::greater))
800 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000801 next();
802 }
803 }
804
805 void parsePreprocessorDirective() {
806 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000807 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000808 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000809 // Hashes in the middle of a line can lead to any strange token
810 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000811 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000812 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000813 switch (
814 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000815 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000816 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000817 parseIncludeDirective();
818 break;
819 default:
820 break;
821 }
822 }
823
Daniel Jasperda16db32013-01-07 10:48:50 +0000824 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000825 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000826 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000827 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000828 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000829 while (CurrentToken != NULL) {
830 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000831 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000832 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000833 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000834 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000835 if (KeywordVirtualFound)
836 return LT_VirtualFunctionDecl;
837 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 }
839
840 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000841 if (CurrentToken != NULL && !CurrentToken->Children.empty())
842 CurrentToken = &CurrentToken->Children[0];
843 else
844 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000845 }
846
847 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000848 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000849 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000850 };
851
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000852 void createAnnotatedTokens(AnnotatedToken &Current) {
853 if (!Current.FormatTok.Children.empty()) {
854 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
855 Current.Children.back().Parent = &Current;
856 createAnnotatedTokens(Current.Children.back());
857 }
858 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000859
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000860 void calculateExtraInformation(AnnotatedToken &Current) {
861 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
862
Manuel Klimek52b15152013-01-09 15:25:02 +0000863 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 Current.MustBreakBefore = true;
865 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000866 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
867 TT_LineComment || (Current.is(tok::string_literal) &&
868 Current.Parent->is(tok::string_literal))) {
869 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000870 } else {
871 Current.MustBreakBefore = false;
872 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000873 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000875 if (!Current.Children.empty())
876 calculateExtraInformation(Current.Children[0]);
877 }
878
879 bool annotate() {
880 createAnnotatedTokens(RootToken);
881
882 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000883 CurrentLineType = Parser.parseLine();
884 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000885 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000886
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000887 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000888
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000889 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000890 CurrentLineType = LT_ObjCMethodDecl;
891
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000892 if (!RootToken.Children.empty())
893 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000894 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000895 }
896
Daniel Jasperda16db32013-01-07 10:48:50 +0000897 LineType getLineType() {
898 return CurrentLineType;
899 }
900
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 const AnnotatedToken &getRootToken() {
902 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000903 }
904
905private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000906 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
907 if (getPrecedence(Current) == prec::Assignment ||
908 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
909 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000910
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000911 if (Current.Type == TT_Unknown) {
912 if (Current.is(tok::star) || Current.is(tok::amp)) {
913 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000914 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
915 Current.is(tok::caret)) {
916 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
918 Current.Type = determineIncrementUsage(Current);
919 } else if (Current.is(tok::exclaim)) {
920 Current.Type = TT_UnaryOperator;
921 } else if (isBinaryOperator(Current)) {
922 Current.Type = TT_BinaryOperator;
923 } else if (Current.is(tok::comment)) {
924 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
925 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000926 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000927 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000929 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000930 } else if (Current.is(tok::r_paren) &&
931 (Current.Parent->Type == TT_PointerOrReference ||
932 Current.Parent->Type == TT_TemplateCloser)) {
933 // FIXME: We need to get smarter and understand more cases of casts.
934 Current.Type = TT_CastRParen;
Daniel Jasperf7935112012-12-03 18:12:45 +0000935 }
936 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000937
938 if (!Current.Children.empty())
939 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000940 }
941
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000942 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000943 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000944 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000945 }
946
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000947 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
948 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000949 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000950 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000951 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000952 const FormatToken &PrevToken = Tok.Parent->FormatTok;
953 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000954
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000955 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
956 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000957 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
958 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000959 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000960
Daniel Jasper542de162013-01-02 15:46:59 +0000961 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000962 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
963 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
964 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
965 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000966 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000967
Daniel Jasper542de162013-01-02 15:46:59 +0000968 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
969 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000970 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000971
Daniel Jasper426702d2012-12-05 07:51:39 +0000972 // It is very unlikely that we are going to find a pointer or reference type
973 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000974 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000975 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000976
Daniel Jasperda16db32013-01-07 10:48:50 +0000977 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000978 }
979
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000980 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000981 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000982 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000983 return TT_ObjCMethodSpecifier;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000984
985 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000986 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
987 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
988 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
989 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case))
Daniel Jasperda16db32013-01-07 10:48:50 +0000990 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000991
992 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000993 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +0000994 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000995
996 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000997 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000998 }
999
1000 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001001 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
1002 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001003 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001004
Daniel Jasperda16db32013-01-07 10:48:50 +00001005 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006 }
1007
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001008 bool spaceRequiredBetween(const AnnotatedToken &Left,
1009 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001010 if (Right.is(tok::hashhash))
1011 return Left.is(tok::hash);
1012 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1013 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001014 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1015 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 if (Left.is(tok::kw_template) && Right.is(tok::less))
1017 return true;
1018 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1019 return false;
1020 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1021 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001022 if (Left.is(tok::at) &&
1023 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1024 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001025 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1026 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001027 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001028 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1029 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001030 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001032 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1033 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001034 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001035 return Right.FormatTok.Tok.isLiteral() ||
1036 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001037 if (Right.is(tok::star) && Left.is(tok::l_paren))
1038 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001039 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1040 Right.is(tok::r_square))
1041 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001042 if (Left.is(tok::coloncolon) ||
1043 (Right.is(tok::coloncolon) &&
1044 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001045 return false;
1046 if (Left.is(tok::period) || Right.is(tok::period))
1047 return false;
1048 if (Left.is(tok::colon) || Right.is(tok::colon))
1049 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001050 if (Left.is(tok::l_paren))
1051 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001053 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001054 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001055 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001056 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001057 if (Left.is(tok::at) &&
1058 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001059 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001060 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1061 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 return true;
1063 }
1064
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001065 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001066 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001067 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1068 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001069 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001070 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001071 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001072 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001073 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001074 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001075 // Don't space between ')' and <id>
1076 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001078 // Don't space between ':' and '('
1079 return false;
1080 }
1081
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001082 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001083 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001084 if (Tok.Type == TT_OverloadedOperator)
1085 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001086 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001087 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001088 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001089 if (Tok.is(tok::colon))
1090 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001091 if (Tok.Parent->Type == TT_UnaryOperator ||
1092 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001093 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001094 if (Tok.Type == TT_UnaryOperator)
1095 return Tok.Parent->isNot(tok::l_paren) &&
1096 Tok.Parent->isNot(tok::l_square);
1097 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1098 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001099 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1100 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001101 if (Tok.Type == TT_DirectorySeparator ||
1102 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001103 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001104 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001105 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001107 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001108 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001109 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001110 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001111 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001112 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001113 }
1114
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001115 bool canBreakBefore(const AnnotatedToken &Right) {
1116 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001117 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001118 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1119 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001120 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1122 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001123 // Don't break this identifier as ':' or identifier
1124 // before it will break.
1125 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1127 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001128 // Don't break at ':' if identifier before it can beak.
1129 return false;
1130 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001131 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001132 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001133 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001134 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001135 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001136 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001137 return false;
1138
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001139 if (Right.is(tok::comment))
1140 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001142 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001143 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001144 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1145 Left.is(tok::comma) || Right.is(tok::lessless) ||
1146 Right.is(tok::arrow) || Right.is(tok::period) ||
1147 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001148 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001149 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001150 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001151 }
1152
Daniel Jasperf7935112012-12-03 18:12:45 +00001153 FormatStyle Style;
1154 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001155 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001156 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001157 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001158};
1159
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001160class LexerBasedFormatTokenSource : public FormatTokenSource {
1161public:
1162 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001163 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001164 IdentTable(Lex.getLangOpts()) {
1165 Lex.SetKeepWhitespaceMode(true);
1166 }
1167
1168 virtual FormatToken getNextToken() {
1169 if (GreaterStashed) {
1170 FormatTok.NewlinesBefore = 0;
1171 FormatTok.WhiteSpaceStart =
1172 FormatTok.Tok.getLocation().getLocWithOffset(1);
1173 FormatTok.WhiteSpaceLength = 0;
1174 GreaterStashed = false;
1175 return FormatTok;
1176 }
1177
1178 FormatTok = FormatToken();
1179 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001180 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001181 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001182 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1183 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184
1185 // Consume and record whitespace until we find a significant token.
1186 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001187 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001188 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1189 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001190 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1191
1192 if (FormatTok.Tok.is(tok::eof))
1193 return FormatTok;
1194 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001195 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001196 }
Manuel Klimekef920692013-01-07 07:56:50 +00001197
1198 // Now FormatTok is the next non-whitespace token.
1199 FormatTok.TokenLength = Text.size();
1200
Manuel Klimek1abf7892013-01-04 23:34:14 +00001201 // In case the token starts with escaped newlines, we want to
1202 // take them into account as whitespace - this pattern is quite frequent
1203 // in macro definitions.
1204 // FIXME: What do we want to do with other escaped spaces, and escaped
1205 // spaces or newlines in the middle of tokens?
1206 // FIXME: Add a more explicit test.
1207 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001208 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001209 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001210 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001211 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001212 }
1213
1214 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001215 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001216 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001217 FormatTok.Tok.setKind(Info.getTokenID());
1218 }
1219
1220 if (FormatTok.Tok.is(tok::greatergreater)) {
1221 FormatTok.Tok.setKind(tok::greater);
1222 GreaterStashed = true;
1223 }
1224
1225 return FormatTok;
1226 }
1227
1228private:
1229 FormatToken FormatTok;
1230 bool GreaterStashed;
1231 Lexer &Lex;
1232 SourceManager &SourceMgr;
1233 IdentifierTable IdentTable;
1234
1235 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001236 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001237 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1238 Tok.getLength());
1239 }
1240};
1241
Daniel Jasperf7935112012-12-03 18:12:45 +00001242class Formatter : public UnwrappedLineConsumer {
1243public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001244 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1245 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001246 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001247 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
1248 Ranges(Ranges), StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001249 }
1250
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001251 virtual ~Formatter() {
1252 }
1253
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001255 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001256 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001257 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001258 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001259 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1260 E = UnwrappedLines.end();
1261 I != E; ++I)
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001262 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1263 PreviousEndOfLineColumn);
Daniel Jasperf7935112012-12-03 18:12:45 +00001264 return Replaces;
1265 }
1266
1267private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001268 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001269 UnwrappedLines.push_back(TheLine);
1270 }
1271
Manuel Klimek1abf7892013-01-04 23:34:14 +00001272 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1273 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001274 const FormatToken *First = &TheLine.RootToken;
1275 const FormatToken *Last = First;
1276 while (!Last->Children.empty())
1277 Last = &Last->Children.back();
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001278 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001279 First->Tok.getLocation(),
1280 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001281
1282 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1283 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1284 Ranges[i].getBegin()) ||
1285 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1286 LineRange.getBegin()))
1287 continue;
1288
Manuel Klimekc74d2922013-01-07 08:54:53 +00001289 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasperc0880a92013-01-04 18:52:56 +00001290 if (!Annotator.annotate())
Manuel Klimek1abf7892013-01-04 23:34:14 +00001291 break;
1292 UnwrappedLineFormatter Formatter(
1293 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001294 Annotator.getLineType(), Annotator.getRootToken(), Replaces,
Daniel Jasperda16db32013-01-07 10:48:50 +00001295 StructuralError);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001296 return Formatter.format();
Daniel Jasperf7935112012-12-03 18:12:45 +00001297 }
Manuel Klimek1abf7892013-01-04 23:34:14 +00001298 // If we did not reformat this unwrapped line, the column at the end of the
1299 // last token is unchanged - thus, we can calculate the end of the last
1300 // token, and return the result.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001301 return SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1302 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
Manuel Klimek1abf7892013-01-04 23:34:14 +00001303 Lex.getLangOpts()) -
1304 1;
Daniel Jasperf7935112012-12-03 18:12:45 +00001305 }
1306
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001307 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001308 FormatStyle Style;
1309 Lexer &Lex;
1310 SourceManager &SourceMgr;
1311 tooling::Replacements Replaces;
1312 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001313 std::vector<UnwrappedLine> UnwrappedLines;
1314 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001315};
1316
1317tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1318 SourceManager &SourceMgr,
1319 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001320 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1321 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1322 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1323 DiagnosticsEngine Diagnostics(
1324 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1325 &DiagnosticPrinter, false);
1326 Diagnostics.setSourceManager(&SourceMgr);
1327 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001328 return formatter.format();
1329}
1330
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001331LangOptions getFormattingLangOpts() {
1332 LangOptions LangOpts;
1333 LangOpts.CPlusPlus = 1;
1334 LangOpts.CPlusPlus11 = 1;
1335 LangOpts.Bool = 1;
1336 LangOpts.ObjC1 = 1;
1337 LangOpts.ObjC2 = 1;
1338 return LangOpts;
1339}
1340
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001341} // namespace format
1342} // namespace clang