blob: fa676b39736efa951549885bc186393cf45ab662 [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,
Daniel Jasperb596fb22013-10-24 10:31:50 +000038 TT_DictLiteral,
Alexander Kornienko4b672072013-06-03 16:45:03 +000039 TT_ImplicitStringLiteral,
40 TT_InlineASMColon,
41 TT_InheritanceColon,
Alexander Kornienko3cfa9732013-11-20 16:33:05 +000042 TT_FunctionLBrace,
Alexander Kornienko4b672072013-06-03 16:45:03 +000043 TT_FunctionTypeLParen,
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000044 TT_LambdaLSquare,
Alexander Kornienko4b672072013-06-03 16:45:03 +000045 TT_LineComment,
Alexander Kornienko4b672072013-06-03 16:45:03 +000046 TT_ObjCBlockLParen,
47 TT_ObjCDecl,
Alexander Kornienko4b672072013-06-03 16:45:03 +000048 TT_ObjCForIn,
49 TT_ObjCMethodExpr,
50 TT_ObjCMethodSpecifier,
51 TT_ObjCProperty,
52 TT_ObjCSelectorName,
53 TT_OverloadedOperator,
54 TT_OverloadedOperatorLParen,
55 TT_PointerOrReference,
56 TT_PureVirtualSpecifier,
57 TT_RangeBasedForLoopColon,
58 TT_StartOfName,
59 TT_TemplateCloser,
60 TT_TemplateOpener,
Daniel Jasper6cdec7c2013-07-09 14:36:48 +000061 TT_TrailingReturnArrow,
Alexander Kornienko4b672072013-06-03 16:45:03 +000062 TT_TrailingUnaryOperator,
63 TT_UnaryOperator,
64 TT_Unknown
65};
66
Daniel Jasperb1f74a82013-07-09 09:06:29 +000067// Represents what type of block a set of braces open.
68enum BraceBlockKind {
69 BK_Unknown,
70 BK_Block,
71 BK_BracedInit
72};
73
Daniel Jasperb10cbc42013-07-10 14:02:49 +000074// The packing kind of a function's parameters.
75enum ParameterPackingKind {
76 PPK_BinPacked,
77 PPK_OnePerLine,
78 PPK_Inconclusive
79};
80
Manuel Klimek71814b42013-10-11 21:25:45 +000081enum FormatDecision {
82 FD_Unformatted,
83 FD_Continue,
84 FD_Break
85};
86
Daniel Jasper8de9ed02013-08-22 15:00:41 +000087class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000088class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000089
Alexander Kornienko4b672072013-06-03 16:45:03 +000090/// \brief A wrapper around a \c Token storing information about the
Alp Tokerf6a24ce2013-12-05 16:25:25 +000091/// whitespace characters preceding it.
Alexander Kornienko4b672072013-06-03 16:45:03 +000092struct FormatToken {
93 FormatToken()
Alexander Kornienko632abb92013-09-02 13:58:14 +000094 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
Alexander Kornienko39856b72013-09-10 09:38:25 +000095 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
Alexander Kornienko632abb92013-09-02 13:58:14 +000096 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
Alexander Kornienkod7b837e2013-08-29 17:32:57 +000097 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
98 CanBreakBefore(false), ClosesTemplateDeclaration(false),
99 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
Daniel Jasper63af7c42013-12-09 14:40:19 +0000100 UnbreakableTailLength(0), BindingStrength(0), NestingLevel(0),
101 SplitPenalty(0), LongestObjCSelectorName(0), FakeRParens(0),
Daniel Jasper562ecd42013-09-06 08:08:14 +0000102 StartsBinaryExpression(false), EndsBinaryExpression(false),
103 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
Manuel Klimek71814b42013-10-11 21:25:45 +0000104 MatchingParen(NULL), Previous(NULL), Next(NULL),
105 Decision(FD_Unformatted), Finalized(false) {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000106
107 /// \brief The \c Token.
108 Token Tok;
109
110 /// \brief The number of newlines immediately before the \c Token.
111 ///
112 /// This can be used to determine what the user wrote in the original code
113 /// and thereby e.g. leave an empty line between two function definitions.
114 unsigned NewlinesBefore;
115
116 /// \brief Whether there is at least one unescaped newline before the \c
117 /// Token.
118 bool HasUnescapedNewline;
119
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000120 /// \brief The range of the whitespace immediately preceding the \c Token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000121 SourceRange WhitespaceRange;
122
123 /// \brief The offset just past the last '\n' in this token's leading
124 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
125 unsigned LastNewlineOffset;
126
Alexander Kornienko39856b72013-09-10 09:38:25 +0000127 /// \brief The width of the non-whitespace parts of the token (or its first
128 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000129 /// We need this to correctly measure number of columns a token spans.
Alexander Kornienko39856b72013-09-10 09:38:25 +0000130 unsigned ColumnWidth;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000131
Alexander Kornienko39856b72013-09-10 09:38:25 +0000132 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000133 /// token.
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000134 unsigned LastLineColumnWidth;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000135
Alexander Kornienko39856b72013-09-10 09:38:25 +0000136 /// \brief Whether the token text contains newlines (escaped or not).
137 bool IsMultiline;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000138
Alexander Kornienko4b672072013-06-03 16:45:03 +0000139 /// \brief Indicates that this is the first token.
140 bool IsFirst;
141
142 /// \brief Whether there must be a line break before this token.
143 ///
144 /// This happens for example when a preprocessor directive ended directly
145 /// before the token.
146 bool MustBreakBefore;
147
148 /// \brief Returns actual token start location without leading escaped
149 /// newlines and whitespace.
150 ///
151 /// This can be different to Tok.getLocation(), which includes leading escaped
152 /// newlines.
153 SourceLocation getStartOfNonWhitespace() const {
154 return WhitespaceRange.getEnd();
155 }
156
157 /// \brief The raw text of the token.
158 ///
159 /// Contains the raw token text without leading whitespace and without leading
160 /// escaped newlines.
161 StringRef TokenText;
162
Daniel Jasper8369aa52013-07-16 20:28:33 +0000163 /// \brief Set to \c true if this token is an unterminated literal.
164 bool IsUnterminatedLiteral;
165
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000166 /// \brief Contains the kind of block if this token is a brace.
167 BraceBlockKind BlockKind;
168
Alexander Kornienko4b672072013-06-03 16:45:03 +0000169 TokenType Type;
170
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000171 /// \brief The number of spaces that should be inserted before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000172 unsigned SpacesRequiredBefore;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000173
174 /// \brief \c true if it is allowed to break before this token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000175 bool CanBreakBefore;
176
177 bool ClosesTemplateDeclaration;
178
179 /// \brief Number of parameters, if this is "(", "[" or "<".
180 ///
181 /// This is initialized to 1 as we don't need to distinguish functions with
182 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
183 /// the number of commas.
184 unsigned ParameterCount;
185
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000186 /// \brief A token can have a special role that can carry extra information
187 /// about the token's formatting.
188 llvm::OwningPtr<TokenRole> Role;
189
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000190 /// \brief If this is an opening parenthesis, how are the parameters packed?
191 ParameterPackingKind PackingKind;
192
Manuel Klimek31c85922013-08-29 15:21:40 +0000193 /// \brief The total length of the unwrapped line up to and including this
194 /// token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000195 unsigned TotalLength;
196
Alexander Kornienko39856b72013-09-10 09:38:25 +0000197 /// \brief The original 0-based column of this token, including expanded tabs.
198 /// The configured TabWidth is used as tab width.
Manuel Klimek31c85922013-08-29 15:21:40 +0000199 unsigned OriginalColumn;
200
Alexander Kornienko4b672072013-06-03 16:45:03 +0000201 /// \brief The length of following tokens until the next natural split point,
202 /// or the next token that can be broken.
203 unsigned UnbreakableTailLength;
204
205 // FIXME: Come up with a 'cleaner' concept.
206 /// \brief The binding strength of a token. This is a combined value of
207 /// operator precedence, parenthesis nesting, etc.
208 unsigned BindingStrength;
209
Daniel Jasper63af7c42013-12-09 14:40:19 +0000210 /// \brief The nesting level of this token, i.e. the number of surrounding (),
211 /// [], {} or <>.
212 unsigned NestingLevel;
213
Alexander Kornienko4b672072013-06-03 16:45:03 +0000214 /// \brief Penalty for inserting a line break before this token.
215 unsigned SplitPenalty;
216
217 /// \brief If this is the first ObjC selector name in an ObjC method
218 /// definition or call, this contains the length of the longest name.
219 unsigned LongestObjCSelectorName;
220
221 /// \brief Stores the number of required fake parentheses and the
222 /// corresponding operator precedence.
223 ///
224 /// If multiple fake parentheses start at a token, this vector stores them in
225 /// reverse order, i.e. inner fake parenthesis first.
226 SmallVector<prec::Level, 4> FakeLParens;
227 /// \brief Insert this many fake ) after this token for correct indentation.
228 unsigned FakeRParens;
229
Daniel Jasper562ecd42013-09-06 08:08:14 +0000230 /// \brief \c true if this token starts a binary expression, i.e. has at least
231 /// one fake l_paren with a precedence greater than prec::Unknown.
232 bool StartsBinaryExpression;
233 /// \brief \c true if this token ends a binary expression.
234 bool EndsBinaryExpression;
235
Alexander Kornienko4b672072013-06-03 16:45:03 +0000236 /// \brief Is this the last "." or "->" in a builder-type call?
237 bool LastInChainOfCalls;
238
239 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
240 ///
241 /// Only set if \c Type == \c TT_StartOfName.
242 bool PartOfMultiVariableDeclStmt;
243
244 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
245
246 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
247 return is(K1) || is(K2);
248 }
249
250 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
251 return is(K1) || is(K2) || is(K3);
252 }
253
254 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
255 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
256 tok::TokenKind K6 = tok::NUM_TOKENS,
257 tok::TokenKind K7 = tok::NUM_TOKENS,
258 tok::TokenKind K8 = tok::NUM_TOKENS,
259 tok::TokenKind K9 = tok::NUM_TOKENS,
260 tok::TokenKind K10 = tok::NUM_TOKENS,
261 tok::TokenKind K11 = tok::NUM_TOKENS,
262 tok::TokenKind K12 = tok::NUM_TOKENS) const {
263 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
264 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
265 }
266
267 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
268
269 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
270 return Tok.isObjCAtKeyword(Kind);
271 }
272
273 bool isAccessSpecifier(bool ColonRequired = true) const {
274 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
275 (!ColonRequired || (Next && Next->is(tok::colon)));
276 }
277
278 bool isObjCAccessSpecifier() const {
279 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
280 Next->isObjCAtKeyword(tok::objc_protected) ||
281 Next->isObjCAtKeyword(tok::objc_package) ||
282 Next->isObjCAtKeyword(tok::objc_private));
283 }
284
285 /// \brief Returns whether \p Tok is ([{ or a template opening <.
286 bool opensScope() const {
287 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
288 Type == TT_TemplateOpener;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000289 }
Nico Weber0f987a62013-06-25 19:25:12 +0000290 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000291 bool closesScope() const {
292 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
293 Type == TT_TemplateCloser;
294 }
295
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000296 /// \brief Returns \c true if this is a "." or "->" accessing a member.
297 bool isMemberAccess() const {
298 return isOneOf(tok::arrow, tok::period) &&
299 Type != TT_DesignatedInitializerPeriod;
300 }
301
Alexander Kornienko4b672072013-06-03 16:45:03 +0000302 bool isUnaryOperator() const {
303 switch (Tok.getKind()) {
304 case tok::plus:
305 case tok::plusplus:
306 case tok::minus:
307 case tok::minusminus:
308 case tok::exclaim:
309 case tok::tilde:
310 case tok::kw_sizeof:
311 case tok::kw_alignof:
312 return true;
313 default:
314 return false;
315 }
316 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000317
Alexander Kornienko4b672072013-06-03 16:45:03 +0000318 bool isBinaryOperator() const {
319 // Comma is a binary operator, but does not behave as such wrt. formatting.
320 return getPrecedence() > prec::Comma;
321 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000322
Alexander Kornienko4b672072013-06-03 16:45:03 +0000323 bool isTrailingComment() const {
324 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
325 }
326
327 prec::Level getPrecedence() const {
328 return getBinOpPrecedence(Tok.getKind(), true, true);
329 }
330
331 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000332 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000333 FormatToken *Tok = Previous;
334 while (Tok != NULL && Tok->is(tok::comment))
335 Tok = Tok->Previous;
336 return Tok;
337 }
338
339 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000340 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000341 const FormatToken *Tok = Next;
342 while (Tok != NULL && Tok->is(tok::comment))
343 Tok = Tok->Next;
344 return Tok;
345 }
346
Daniel Jasperb8f61682013-10-22 15:45:58 +0000347 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
348 /// list that should be indented with a block indent.
349 bool opensBlockTypeList(const FormatStyle &Style) const {
350 return Type == TT_ArrayInitializerLSquare ||
351 (is(tok::l_brace) &&
Daniel Jasperb596fb22013-10-24 10:31:50 +0000352 (BlockKind == BK_Block || Type == TT_DictLiteral ||
Daniel Jasperb8f61682013-10-22 15:45:58 +0000353 !Style.Cpp11BracedListStyle));
354 }
355
356 /// \brief Same as opensBlockTypeList, but for the closing token.
Daniel Jasper1db6c382013-10-22 15:30:28 +0000357 bool closesBlockTypeList(const FormatStyle &Style) const {
Daniel Jasperb8f61682013-10-22 15:45:58 +0000358 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
Daniel Jasper1db6c382013-10-22 15:30:28 +0000359 }
360
Alexander Kornienko4b672072013-06-03 16:45:03 +0000361 FormatToken *MatchingParen;
362
363 FormatToken *Previous;
364 FormatToken *Next;
365
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000366 SmallVector<AnnotatedLine *, 1> Children;
367
Manuel Klimek71814b42013-10-11 21:25:45 +0000368 /// \brief Stores the formatting decision for the token once it was made.
369 FormatDecision Decision;
370
371 /// \brief If \c true, this token has been fully formatted (indented and
372 /// potentially re-formatted inside), and we do not allow further formatting
373 /// changes.
374 bool Finalized;
375
Alexander Kornienko4b672072013-06-03 16:45:03 +0000376private:
377 // Disallow copying.
Craig Topper411294d2013-07-01 04:07:34 +0000378 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
379 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000380};
381
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000382class ContinuationIndenter;
383struct LineState;
384
385class TokenRole {
386public:
387 TokenRole(const FormatStyle &Style) : Style(Style) {}
388 virtual ~TokenRole();
389
390 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
391 /// this function precomputes required information for formatting.
392 virtual void precomputeFormattingInfos(const FormatToken *Token);
393
394 /// \brief Apply the special formatting that the given role demands.
395 ///
396 /// Continues formatting from \p State leaving indentation to \p Indenter and
397 /// returns the total penalty that this formatting incurs.
398 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
399 bool DryRun) {
400 return 0;
401 }
402
403 /// \brief Notifies the \c Role that a comma was found.
404 virtual void CommaFound(const FormatToken *Token) {}
405
406protected:
407 const FormatStyle &Style;
408};
409
410class CommaSeparatedList : public TokenRole {
411public:
412 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
413
414 virtual void precomputeFormattingInfos(const FormatToken *Token);
415
416 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
417 bool DryRun);
418
419 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
420 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
421
422private:
423 /// \brief A struct that holds information on how to format a given list with
424 /// a specific number of columns.
425 struct ColumnFormat {
426 /// \brief The number of columns to use.
427 unsigned Columns;
428
429 /// \brief The total width in characters.
430 unsigned TotalWidth;
431
432 /// \brief The number of lines required for this format.
433 unsigned LineCount;
434
435 /// \brief The size of each column in characters.
436 SmallVector<unsigned, 8> ColumnSizes;
437 };
438
439 /// \brief Calculate which \c ColumnFormat fits best into
440 /// \p RemainingCharacters.
441 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
442
443 /// \brief The ordered \c FormatTokens making up the commas of this list.
444 SmallVector<const FormatToken *, 8> Commas;
445
446 /// \brief The length of each of the list's items in characters including the
447 /// trailing comma.
448 SmallVector<unsigned, 8> ItemLengths;
449
450 /// \brief Precomputed formats that can be used for this list.
451 SmallVector<ColumnFormat, 4> Formats;
452};
453
Alexander Kornienko4b672072013-06-03 16:45:03 +0000454} // namespace format
455} // namespace clang
456
457#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H