blob: 52cc3ce530dc79b13b50ea3452f487df9251e2c6 [file] [log] [blame]
Alexander Kornienko4b672072013-06-03 16:45:03 +00001//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
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 contains the declaration of the FormatToken, a wrapper
12/// around Token with additional information related to formatting.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
17#define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
18
19#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000020#include "clang/Format/Format.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000021#include "clang/Lex/Lexer.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000022#include "llvm/ADT/OwningPtr.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000023
24namespace clang {
25namespace format {
26
27enum TokenType {
Daniel Jasper1db6c382013-10-22 15:30:28 +000028 TT_ArrayInitializerLSquare,
29 TT_ArraySubscriptLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000030 TT_BinaryOperator,
Alexander Kornienko60d1b042013-10-10 13:36:20 +000031 TT_BitFieldColon,
Alexander Kornienko4b672072013-06-03 16:45:03 +000032 TT_BlockComment,
33 TT_CastRParen,
34 TT_ConditionalExpr,
35 TT_CtorInitializerColon,
Daniel Jaspere33d4af2013-07-26 16:56:36 +000036 TT_CtorInitializerComma,
Alexander Kornienko4b672072013-06-03 16:45:03 +000037 TT_DesignatedInitializerPeriod,
38 TT_ImplicitStringLiteral,
39 TT_InlineASMColon,
40 TT_InheritanceColon,
41 TT_FunctionTypeLParen,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000042 TT_LambdaLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000043 TT_LineComment,
Alexander Kornienko4b672072013-06-03 16:45:03 +000044 TT_ObjCBlockLParen,
45 TT_ObjCDecl,
46 TT_ObjCDictLiteral,
47 TT_ObjCForIn,
48 TT_ObjCMethodExpr,
49 TT_ObjCMethodSpecifier,
50 TT_ObjCProperty,
51 TT_ObjCSelectorName,
52 TT_OverloadedOperator,
53 TT_OverloadedOperatorLParen,
54 TT_PointerOrReference,
55 TT_PureVirtualSpecifier,
56 TT_RangeBasedForLoopColon,
57 TT_StartOfName,
58 TT_TemplateCloser,
59 TT_TemplateOpener,
Daniel Jasper6cdec7c2013-07-09 14:36:48 +000060 TT_TrailingReturnArrow,
Alexander Kornienko4b672072013-06-03 16:45:03 +000061 TT_TrailingUnaryOperator,
62 TT_UnaryOperator,
63 TT_Unknown
64};
65
Daniel Jasperb1f74a82013-07-09 09:06:29 +000066// Represents what type of block a set of braces open.
67enum BraceBlockKind {
68 BK_Unknown,
69 BK_Block,
70 BK_BracedInit
71};
72
Daniel Jasperb10cbc42013-07-10 14:02:49 +000073// The packing kind of a function's parameters.
74enum ParameterPackingKind {
75 PPK_BinPacked,
76 PPK_OnePerLine,
77 PPK_Inconclusive
78};
79
Manuel Klimek71814b42013-10-11 21:25:45 +000080enum FormatDecision {
81 FD_Unformatted,
82 FD_Continue,
83 FD_Break
84};
85
Daniel Jasper8de9ed02013-08-22 15:00:41 +000086class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000087class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000088
Alexander Kornienko4b672072013-06-03 16:45:03 +000089/// \brief A wrapper around a \c Token storing information about the
90/// whitespace characters preceeding it.
91struct FormatToken {
92 FormatToken()
Alexander Kornienko632abb92013-09-02 13:58:14 +000093 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko39856b72013-09-10 09:38:25 +000094 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
Alexander Kornienko632abb92013-09-02 13:58:14 +000095 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
Alexander Kornienkod7b837e2013-08-29 17:32:57 +000096 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
97 CanBreakBefore(false), ClosesTemplateDeclaration(false),
98 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
99 UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
Daniel Jasper562ecd42013-09-06 08:08:14 +0000100 LongestObjCSelectorName(0), FakeRParens(0),
101 StartsBinaryExpression(false), EndsBinaryExpression(false),
102 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
Manuel Klimek71814b42013-10-11 21:25:45 +0000103 MatchingParen(NULL), Previous(NULL), Next(NULL),
104 Decision(FD_Unformatted), Finalized(false) {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000105
106 /// \brief The \c Token.
107 Token Tok;
108
109 /// \brief The number of newlines immediately before the \c Token.
110 ///
111 /// This can be used to determine what the user wrote in the original code
112 /// and thereby e.g. leave an empty line between two function definitions.
113 unsigned NewlinesBefore;
114
115 /// \brief Whether there is at least one unescaped newline before the \c
116 /// Token.
117 bool HasUnescapedNewline;
118
119 /// \brief The range of the whitespace immediately preceeding the \c Token.
120 SourceRange WhitespaceRange;
121
122 /// \brief The offset just past the last '\n' in this token's leading
123 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
124 unsigned LastNewlineOffset;
125
Alexander Kornienko39856b72013-09-10 09:38:25 +0000126 /// \brief The width of the non-whitespace parts of the token (or its first
127 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000128 /// We need this to correctly measure number of columns a token spans.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000129 unsigned ColumnWidth;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000130
Alexander Kornienko39856b72013-09-10 09:38:25 +0000131 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000132 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000133 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000134
Alexander Kornienko39856b72013-09-10 09:38:25 +0000135 /// \brief Whether the token text contains newlines (escaped or not).
136 bool IsMultiline;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000137
Alexander Kornienko4b672072013-06-03 16:45:03 +0000138 /// \brief Indicates that this is the first token.
139 bool IsFirst;
140
141 /// \brief Whether there must be a line break before this token.
142 ///
143 /// This happens for example when a preprocessor directive ended directly
144 /// before the token.
145 bool MustBreakBefore;
146
147 /// \brief Returns actual token start location without leading escaped
148 /// newlines and whitespace.
149 ///
150 /// This can be different to Tok.getLocation(), which includes leading escaped
151 /// newlines.
152 SourceLocation getStartOfNonWhitespace() const {
153 return WhitespaceRange.getEnd();
154 }
155
156 /// \brief The raw text of the token.
157 ///
158 /// Contains the raw token text without leading whitespace and without leading
159 /// escaped newlines.
160 StringRef TokenText;
161
Daniel Jasper8369aa52013-07-16 20:28:33 +0000162 /// \brief Set to \c true if this token is an unterminated literal.
163 bool IsUnterminatedLiteral;
164
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000165 /// \brief Contains the kind of block if this token is a brace.
166 BraceBlockKind BlockKind;
167
Alexander Kornienko4b672072013-06-03 16:45:03 +0000168 TokenType Type;
169
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000170 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000171 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000172
173 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000174 bool CanBreakBefore;
175
176 bool ClosesTemplateDeclaration;
177
178 /// \brief Number of parameters, if this is "(", "[" or "<".
179 ///
180 /// This is initialized to 1 as we don't need to distinguish functions with
181 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
182 /// the number of commas.
183 unsigned ParameterCount;
184
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000185 /// \brief A token can have a special role that can carry extra information
186 /// about the token's formatting.
187 llvm::OwningPtr<TokenRole> Role;
188
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000189 /// \brief If this is an opening parenthesis, how are the parameters packed?
190 ParameterPackingKind PackingKind;
191
Manuel Klimek31c85922013-08-29 15:21:40 +0000192 /// \brief The total length of the unwrapped line up to and including this
193 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000194 unsigned TotalLength;
195
Alexander Kornienko39856b72013-09-10 09:38:25 +0000196 /// \brief The original 0-based column of this token, including expanded tabs.
197 /// The configured TabWidth is used as tab width.
Manuel Klimek31c85922013-08-29 15:21:40 +0000198 unsigned OriginalColumn;
199
Alexander Kornienko4b672072013-06-03 16:45:03 +0000200 /// \brief The length of following tokens until the next natural split point,
201 /// or the next token that can be broken.
202 unsigned UnbreakableTailLength;
203
204 // FIXME: Come up with a 'cleaner' concept.
205 /// \brief The binding strength of a token. This is a combined value of
206 /// operator precedence, parenthesis nesting, etc.
207 unsigned BindingStrength;
208
209 /// \brief Penalty for inserting a line break before this token.
210 unsigned SplitPenalty;
211
212 /// \brief If this is the first ObjC selector name in an ObjC method
213 /// definition or call, this contains the length of the longest name.
214 unsigned LongestObjCSelectorName;
215
216 /// \brief Stores the number of required fake parentheses and the
217 /// corresponding operator precedence.
218 ///
219 /// If multiple fake parentheses start at a token, this vector stores them in
220 /// reverse order, i.e. inner fake parenthesis first.
221 SmallVector<prec::Level, 4> FakeLParens;
222 /// \brief Insert this many fake ) after this token for correct indentation.
223 unsigned FakeRParens;
224
Daniel Jasper562ecd42013-09-06 08:08:14 +0000225 /// \brief \c true if this token starts a binary expression, i.e. has at least
226 /// one fake l_paren with a precedence greater than prec::Unknown.
227 bool StartsBinaryExpression;
228 /// \brief \c true if this token ends a binary expression.
229 bool EndsBinaryExpression;
230
Alexander Kornienko4b672072013-06-03 16:45:03 +0000231 /// \brief Is this the last "." or "->" in a builder-type call?
232 bool LastInChainOfCalls;
233
234 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
235 ///
236 /// Only set if \c Type == \c TT_StartOfName.
237 bool PartOfMultiVariableDeclStmt;
238
239 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
240
241 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
242 return is(K1) || is(K2);
243 }
244
245 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
246 return is(K1) || is(K2) || is(K3);
247 }
248
249 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
250 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
251 tok::TokenKind K6 = tok::NUM_TOKENS,
252 tok::TokenKind K7 = tok::NUM_TOKENS,
253 tok::TokenKind K8 = tok::NUM_TOKENS,
254 tok::TokenKind K9 = tok::NUM_TOKENS,
255 tok::TokenKind K10 = tok::NUM_TOKENS,
256 tok::TokenKind K11 = tok::NUM_TOKENS,
257 tok::TokenKind K12 = tok::NUM_TOKENS) const {
258 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
259 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
260 }
261
262 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
263
264 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
265 return Tok.isObjCAtKeyword(Kind);
266 }
267
268 bool isAccessSpecifier(bool ColonRequired = true) const {
269 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
270 (!ColonRequired || (Next && Next->is(tok::colon)));
271 }
272
273 bool isObjCAccessSpecifier() const {
274 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
275 Next->isObjCAtKeyword(tok::objc_protected) ||
276 Next->isObjCAtKeyword(tok::objc_package) ||
277 Next->isObjCAtKeyword(tok::objc_private));
278 }
279
280 /// \brief Returns whether \p Tok is ([{ or a template opening <.
281 bool opensScope() const {
282 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
283 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000284 }
Nico Weber0f987a62013-06-25 19:25:12 +0000285 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000286 bool closesScope() const {
287 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
288 Type == TT_TemplateCloser;
289 }
290
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000291 /// \brief Returns \c true if this is a "." or "->" accessing a member.
292 bool isMemberAccess() const {
293 return isOneOf(tok::arrow, tok::period) &&
294 Type != TT_DesignatedInitializerPeriod;
295 }
296
Alexander Kornienko4b672072013-06-03 16:45:03 +0000297 bool isUnaryOperator() const {
298 switch (Tok.getKind()) {
299 case tok::plus:
300 case tok::plusplus:
301 case tok::minus:
302 case tok::minusminus:
303 case tok::exclaim:
304 case tok::tilde:
305 case tok::kw_sizeof:
306 case tok::kw_alignof:
307 return true;
308 default:
309 return false;
310 }
311 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000312
Alexander Kornienko4b672072013-06-03 16:45:03 +0000313 bool isBinaryOperator() const {
314 // Comma is a binary operator, but does not behave as such wrt. formatting.
315 return getPrecedence() > prec::Comma;
316 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000317
Alexander Kornienko4b672072013-06-03 16:45:03 +0000318 bool isTrailingComment() const {
319 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
320 }
321
322 prec::Level getPrecedence() const {
323 return getBinOpPrecedence(Tok.getKind(), true, true);
324 }
325
326 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000327 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000328 FormatToken *Tok = Previous;
329 while (Tok != NULL && Tok->is(tok::comment))
330 Tok = Tok->Previous;
331 return Tok;
332 }
333
334 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000335 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000336 const FormatToken *Tok = Next;
337 while (Tok != NULL && Tok->is(tok::comment))
338 Tok = Tok->Next;
339 return Tok;
340 }
341
Daniel Jasper1db6c382013-10-22 15:30:28 +0000342 bool closesBlockTypeList(const FormatStyle &Style) const {
343 if (is(tok::r_brace) && MatchingParen &&
344 (MatchingParen->BlockKind == BK_Block ||
345 !Style.Cpp11BracedListStyle))
346 return true;
347 if (is(tok::r_square) && MatchingParen &&
348 MatchingParen->Type == TT_ArrayInitializerLSquare)
349 return true;
350 return false;
351 }
352
Alexander Kornienko4b672072013-06-03 16:45:03 +0000353 FormatToken *MatchingParen;
354
355 FormatToken *Previous;
356 FormatToken *Next;
357
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000358 SmallVector<AnnotatedLine *, 1> Children;
359
Manuel Klimek71814b42013-10-11 21:25:45 +0000360 /// \brief Stores the formatting decision for the token once it was made.
361 FormatDecision Decision;
362
363 /// \brief If \c true, this token has been fully formatted (indented and
364 /// potentially re-formatted inside), and we do not allow further formatting
365 /// changes.
366 bool Finalized;
367
Alexander Kornienko4b672072013-06-03 16:45:03 +0000368private:
369 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000370 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
371 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000372};
373
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000374class ContinuationIndenter;
375struct LineState;
376
377class TokenRole {
378public:
379 TokenRole(const FormatStyle &Style) : Style(Style) {}
380 virtual ~TokenRole();
381
382 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
383 /// this function precomputes required information for formatting.
384 virtual void precomputeFormattingInfos(const FormatToken *Token);
385
386 /// \brief Apply the special formatting that the given role demands.
387 ///
388 /// Continues formatting from \p State leaving indentation to \p Indenter and
389 /// returns the total penalty that this formatting incurs.
390 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
391 bool DryRun) {
392 return 0;
393 }
394
395 /// \brief Notifies the \c Role that a comma was found.
396 virtual void CommaFound(const FormatToken *Token) {}
397
398protected:
399 const FormatStyle &Style;
400};
401
402class CommaSeparatedList : public TokenRole {
403public:
404 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
405
406 virtual void precomputeFormattingInfos(const FormatToken *Token);
407
408 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
409 bool DryRun);
410
411 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
412 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
413
414private:
415 /// \brief A struct that holds information on how to format a given list with
416 /// a specific number of columns.
417 struct ColumnFormat {
418 /// \brief The number of columns to use.
419 unsigned Columns;
420
421 /// \brief The total width in characters.
422 unsigned TotalWidth;
423
424 /// \brief The number of lines required for this format.
425 unsigned LineCount;
426
427 /// \brief The size of each column in characters.
428 SmallVector<unsigned, 8> ColumnSizes;
429 };
430
431 /// \brief Calculate which \c ColumnFormat fits best into
432 /// \p RemainingCharacters.
433 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
434
435 /// \brief The ordered \c FormatTokens making up the commas of this list.
436 SmallVector<const FormatToken *, 8> Commas;
437
438 /// \brief The length of each of the list's items in characters including the
439 /// trailing comma.
440 SmallVector<unsigned, 8> ItemLengths;
441
442 /// \brief Precomputed formats that can be used for this list.
443 SmallVector<ColumnFormat, 4> Formats;
444};
445
Alexander Kornienko4b672072013-06-03 16:45:03 +0000446} // namespace format
447} // namespace clang
448
449#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H