blob: 8492829abf0409002ecf7b48675bc332c2d0b52a [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
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +000016#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
17#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
Alexander Kornienko4b672072013-06-03 16:45:03 +000018
Daniel Jasperd0ec0d62014-11-04 12:41:02 +000019#include "clang/Basic/IdentifierTable.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000020#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000021#include "clang/Format/Format.h"
Alexander Kornienko4b672072013-06-03 16:45:03 +000022#include "clang/Lex/Lexer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000023#include <memory>
Alexander Kornienko4b672072013-06-03 16:45:03 +000024
25namespace clang {
26namespace format {
27
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000028#define LIST_TOKEN_TYPES \
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeParen) \
32 TYPE(BinaryOperator) \
33 TYPE(BitFieldColon) \
34 TYPE(BlockComment) \
35 TYPE(CastRParen) \
36 TYPE(ConditionalExpr) \
37 TYPE(ConflictAlternative) \
38 TYPE(ConflictEnd) \
39 TYPE(ConflictStart) \
40 TYPE(CtorInitializerColon) \
41 TYPE(CtorInitializerComma) \
42 TYPE(DesignatedInitializerPeriod) \
43 TYPE(DictLiteral) \
44 TYPE(ForEachMacro) \
45 TYPE(FunctionAnnotationRParen) \
46 TYPE(FunctionDeclarationName) \
47 TYPE(FunctionLBrace) \
48 TYPE(FunctionTypeLParen) \
49 TYPE(ImplicitStringLiteral) \
50 TYPE(InheritanceColon) \
Andi-Bogdan Postelnicu0ef8ee12017-03-10 15:10:37 +000051 TYPE(InheritanceComma) \
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000052 TYPE(InlineASMBrace) \
53 TYPE(InlineASMColon) \
54 TYPE(JavaAnnotation) \
55 TYPE(JsComputedPropertyName) \
56 TYPE(JsFatArrow) \
57 TYPE(JsTypeColon) \
Daniel Jasper91b1d1a2016-03-21 17:57:31 +000058 TYPE(JsTypeOperator) \
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000059 TYPE(JsTypeOptionalQuestion) \
60 TYPE(LambdaArrow) \
61 TYPE(LambdaLSquare) \
62 TYPE(LeadingJavaAnnotation) \
63 TYPE(LineComment) \
64 TYPE(MacroBlockBegin) \
65 TYPE(MacroBlockEnd) \
66 TYPE(ObjCBlockLBrace) \
67 TYPE(ObjCBlockLParen) \
68 TYPE(ObjCDecl) \
69 TYPE(ObjCForIn) \
70 TYPE(ObjCMethodExpr) \
71 TYPE(ObjCMethodSpecifier) \
72 TYPE(ObjCProperty) \
73 TYPE(ObjCStringLiteral) \
74 TYPE(OverloadedOperator) \
75 TYPE(OverloadedOperatorLParen) \
76 TYPE(PointerOrReference) \
77 TYPE(PureVirtualSpecifier) \
78 TYPE(RangeBasedForLoopColon) \
79 TYPE(RegexLiteral) \
80 TYPE(SelectorName) \
81 TYPE(StartOfName) \
82 TYPE(TemplateCloser) \
83 TYPE(TemplateOpener) \
84 TYPE(TemplateString) \
85 TYPE(TrailingAnnotation) \
86 TYPE(TrailingReturnArrow) \
87 TYPE(TrailingUnaryOperator) \
88 TYPE(UnaryOperator) \
89 TYPE(Unknown)
90
Alexander Kornienko4b672072013-06-03 16:45:03 +000091enum TokenType {
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000092#define TYPE(X) TT_##X,
93LIST_TOKEN_TYPES
94#undef TYPE
95 NUM_TOKEN_TYPES
Alexander Kornienko4b672072013-06-03 16:45:03 +000096};
97
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000098/// \brief Determines the name of a token type.
99const char *getTokenTypeName(TokenType Type);
100
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000101// Represents what type of block a set of braces open.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000102enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000103
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000104// The packing kind of a function's parameters.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000105enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000106
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000107enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
Manuel Klimek71814b42013-10-11 21:25:45 +0000108
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000109class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000110class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000111
Alexander Kornienko4b672072013-06-03 16:45:03 +0000112/// \brief A wrapper around a \c Token storing information about the
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000113/// whitespace characters preceding it.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000114struct FormatToken {
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000115 FormatToken() {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000116
117 /// \brief The \c Token.
118 Token Tok;
119
120 /// \brief The number of newlines immediately before the \c Token.
121 ///
122 /// This can be used to determine what the user wrote in the original code
123 /// and thereby e.g. leave an empty line between two function definitions.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000124 unsigned NewlinesBefore = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000125
126 /// \brief Whether there is at least one unescaped newline before the \c
127 /// Token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000128 bool HasUnescapedNewline = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000129
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000130 /// \brief The range of the whitespace immediately preceding the \c Token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000131 SourceRange WhitespaceRange;
132
133 /// \brief The offset just past the last '\n' in this token's leading
134 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000135 unsigned LastNewlineOffset = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000136
Alexander Kornienko39856b72013-09-10 09:38:25 +0000137 /// \brief The width of the non-whitespace parts of the token (or its first
138 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000139 /// We need this to correctly measure number of columns a token spans.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000140 unsigned ColumnWidth = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000141
Alexander Kornienko39856b72013-09-10 09:38:25 +0000142 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000143 /// token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000144 unsigned LastLineColumnWidth = 0;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000145
Alexander Kornienko39856b72013-09-10 09:38:25 +0000146 /// \brief Whether the token text contains newlines (escaped or not).
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000147 bool IsMultiline = false;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000148
Martin Probst7ea9b6d2016-05-29 14:41:36 +0000149 /// \brief Indicates that this is the first token of the file.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000150 bool IsFirst = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000151
152 /// \brief Whether there must be a line break before this token.
153 ///
154 /// This happens for example when a preprocessor directive ended directly
155 /// before the token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000156 bool MustBreakBefore = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000157
158 /// \brief The raw text of the token.
159 ///
160 /// Contains the raw token text without leading whitespace and without leading
161 /// escaped newlines.
162 StringRef TokenText;
163
Daniel Jasper8369aa52013-07-16 20:28:33 +0000164 /// \brief Set to \c true if this token is an unterminated literal.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000165 bool IsUnterminatedLiteral = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000166
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000167 /// \brief Contains the kind of block if this token is a brace.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000168 BraceBlockKind BlockKind = BK_Unknown;
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000169
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000170 TokenType Type = TT_Unknown;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000171
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000172 /// \brief The number of spaces that should be inserted before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000173 unsigned SpacesRequiredBefore = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000174
175 /// \brief \c true if it is allowed to break before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000176 bool CanBreakBefore = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000177
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000178 /// \brief \c true if this is the ">" of "template<..>".
179 bool ClosesTemplateDeclaration = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000180
181 /// \brief Number of parameters, if this is "(", "[" or "<".
182 ///
183 /// This is initialized to 1 as we don't need to distinguish functions with
184 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
185 /// the number of commas.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000186 unsigned ParameterCount = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000187
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000188 /// \brief Number of parameters that are nested blocks,
189 /// if this is "(", "[" or "<".
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000190 unsigned BlockParameterCount = 0;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000191
Daniel Jasperde7ca752015-05-04 07:39:00 +0000192 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
193 /// the surrounding bracket.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000194 tok::TokenKind ParentBracket = tok::unknown;
Daniel Jasperde7ca752015-05-04 07:39:00 +0000195
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000196 /// \brief A token can have a special role that can carry extra information
197 /// about the token's formatting.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000198 std::unique_ptr<TokenRole> Role;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000199
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000200 /// \brief If this is an opening parenthesis, how are the parameters packed?
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000201 ParameterPackingKind PackingKind = PPK_Inconclusive;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000202
Manuel Klimek31c85922013-08-29 15:21:40 +0000203 /// \brief The total length of the unwrapped line up to and including this
204 /// token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000205 unsigned TotalLength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000206
Alexander Kornienko39856b72013-09-10 09:38:25 +0000207 /// \brief The original 0-based column of this token, including expanded tabs.
208 /// The configured TabWidth is used as tab width.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000209 unsigned OriginalColumn = 0;
Manuel Klimek31c85922013-08-29 15:21:40 +0000210
Alexander Kornienko4b672072013-06-03 16:45:03 +0000211 /// \brief The length of following tokens until the next natural split point,
212 /// or the next token that can be broken.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000213 unsigned UnbreakableTailLength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000214
215 // FIXME: Come up with a 'cleaner' concept.
216 /// \brief The binding strength of a token. This is a combined value of
217 /// operator precedence, parenthesis nesting, etc.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000218 unsigned BindingStrength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000219
Daniel Jasper63af7c42013-12-09 14:40:19 +0000220 /// \brief The nesting level of this token, i.e. the number of surrounding (),
221 /// [], {} or <>.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000222 unsigned NestingLevel = 0;
Daniel Jasper63af7c42013-12-09 14:40:19 +0000223
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000224 /// \brief The indent level of this token. Copied from the surrounding line.
225 unsigned IndentLevel = 0;
226
Alexander Kornienko4b672072013-06-03 16:45:03 +0000227 /// \brief Penalty for inserting a line break before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000228 unsigned SplitPenalty = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000229
230 /// \brief If this is the first ObjC selector name in an ObjC method
231 /// definition or call, this contains the length of the longest name.
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000232 ///
233 /// This being set to 0 means that the selectors should not be colon-aligned,
234 /// e.g. because several of them are block-type.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000235 unsigned LongestObjCSelectorName = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000236
237 /// \brief Stores the number of required fake parentheses and the
238 /// corresponding operator precedence.
239 ///
240 /// If multiple fake parentheses start at a token, this vector stores them in
241 /// reverse order, i.e. inner fake parenthesis first.
242 SmallVector<prec::Level, 4> FakeLParens;
243 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000244 unsigned FakeRParens = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000245
Daniel Jasper562ecd42013-09-06 08:08:14 +0000246 /// \brief \c true if this token starts a binary expression, i.e. has at least
247 /// one fake l_paren with a precedence greater than prec::Unknown.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000248 bool StartsBinaryExpression = false;
Daniel Jasper562ecd42013-09-06 08:08:14 +0000249 /// \brief \c true if this token ends a binary expression.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000250 bool EndsBinaryExpression = false;
Daniel Jasper562ecd42013-09-06 08:08:14 +0000251
Daniel Jasper0e617842014-04-16 12:26:54 +0000252 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
253 /// with the same precedence, contains the 0-based operator index.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000254 unsigned OperatorIndex = 0;
Daniel Jasper0e617842014-04-16 12:26:54 +0000255
Daniel Jasper00492f92016-01-05 13:03:50 +0000256 /// \brief If this is an operator (or "."/"->") in a sequence of operators
257 /// with the same precedence, points to the next operator.
258 FormatToken *NextOperator = nullptr;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000259
260 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
261 ///
262 /// Only set if \c Type == \c TT_StartOfName.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000263 bool PartOfMultiVariableDeclStmt = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000264
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000265 /// \brief Does this line comment continue a line comment section?
266 ///
267 /// Only set to true if \c Type == \c TT_LineComment.
268 bool ContinuesLineCommentSection = false;
269
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000270 /// \brief If this is a bracket, this points to the matching one.
271 FormatToken *MatchingParen = nullptr;
272
273 /// \brief The previous token in the unwrapped line.
274 FormatToken *Previous = nullptr;
275
276 /// \brief The next token in the unwrapped line.
277 FormatToken *Next = nullptr;
278
279 /// \brief If this token starts a block, this contains all the unwrapped lines
280 /// in it.
281 SmallVector<AnnotatedLine *, 1> Children;
282
283 /// \brief Stores the formatting decision for the token once it was made.
284 FormatDecision Decision = FD_Unformatted;
285
286 /// \brief If \c true, this token has been fully formatted (indented and
287 /// potentially re-formatted inside), and we do not allow further formatting
288 /// changes.
289 bool Finalized = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000290
Alexander Kornienko4b672072013-06-03 16:45:03 +0000291 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
Daniel Jasper8354ea82014-11-21 12:14:12 +0000292 bool is(TokenType TT) const { return Type == TT; }
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000293 bool is(const IdentifierInfo *II) const {
294 return II && II == Tok.getIdentifierInfo();
295 }
Daniel Jasperd7884572015-08-14 12:44:06 +0000296 bool is(tok::PPKeywordKind Kind) const {
297 return Tok.getIdentifierInfo() &&
298 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
299 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000300 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000301 return is(K1) || is(K2);
302 }
Benjamin Kramerc5bc3cd2015-02-15 20:11:14 +0000303 template <typename A, typename B, typename... Ts>
304 bool isOneOf(A K1, B K2, Ts... Ks) const {
305 return is(K1) || isOneOf(K2, Ks...);
Aaron Ballman484ee9b2014-11-24 15:42:34 +0000306 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000307 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000308
Martin Probst1244ecb2016-05-29 14:41:02 +0000309 /// \c true if this token starts a sequence with the given tokens in order,
310 /// following the ``Next`` pointers, ignoring comments.
311 template <typename A, typename... Ts>
312 bool startsSequence(A K1, Ts... Tokens) const {
313 return startsSequenceInternal(K1, Tokens...);
314 }
315
316 /// \c true if this token ends a sequence with the given tokens in order,
317 /// following the ``Previous`` pointers, ignoring comments.
318 template <typename A, typename... Ts>
319 bool endsSequence(A K1, Ts... Tokens) const {
320 return endsSequenceInternal(K1, Tokens...);
321 }
322
Daniel Jasper04b6a082013-12-20 06:22:01 +0000323 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
Alexander Kornienko4b672072013-06-03 16:45:03 +0000324
325 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
326 return Tok.isObjCAtKeyword(Kind);
327 }
328
329 bool isAccessSpecifier(bool ColonRequired = true) const {
330 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
331 (!ColonRequired || (Next && Next->is(tok::colon)));
332 }
333
Daniel Jaspercb51cf42014-01-16 09:11:55 +0000334 /// \brief Determine whether the token is a simple-type-specifier.
335 bool isSimpleTypeSpecifier() const;
336
Alexander Kornienko4b672072013-06-03 16:45:03 +0000337 bool isObjCAccessSpecifier() const {
338 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
339 Next->isObjCAtKeyword(tok::objc_protected) ||
340 Next->isObjCAtKeyword(tok::objc_package) ||
341 Next->isObjCAtKeyword(tok::objc_private));
342 }
343
344 /// \brief Returns whether \p Tok is ([{ or a template opening <.
345 bool opensScope() const {
Daniel Jasper24de6fb2017-01-31 13:03:07 +0000346 if (is(TT_TemplateString) && TokenText.endswith("${"))
347 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000348 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
349 TT_TemplateOpener);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000350 }
Nico Weber0f987a62013-06-25 19:25:12 +0000351 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000352 bool closesScope() const {
Daniel Jasper24de6fb2017-01-31 13:03:07 +0000353 if (is(TT_TemplateString) && TokenText.startswith("}"))
354 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000355 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
356 TT_TemplateCloser);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000357 }
358
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000359 /// \brief Returns \c true if this is a "." or "->" accessing a member.
360 bool isMemberAccess() const {
Daniel Jasper85bcadc2014-07-09 13:07:57 +0000361 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
Daniel Jasper05cd9292015-03-26 18:46:28 +0000362 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
363 TT_LambdaArrow);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000364 }
365
Alexander Kornienko4b672072013-06-03 16:45:03 +0000366 bool isUnaryOperator() const {
367 switch (Tok.getKind()) {
368 case tok::plus:
369 case tok::plusplus:
370 case tok::minus:
371 case tok::minusminus:
372 case tok::exclaim:
373 case tok::tilde:
374 case tok::kw_sizeof:
375 case tok::kw_alignof:
376 return true;
377 default:
378 return false;
379 }
380 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000381
Alexander Kornienko4b672072013-06-03 16:45:03 +0000382 bool isBinaryOperator() const {
383 // Comma is a binary operator, but does not behave as such wrt. formatting.
384 return getPrecedence() > prec::Comma;
385 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000386
Alexander Kornienko4b672072013-06-03 16:45:03 +0000387 bool isTrailingComment() const {
Daniel Jasper610381f2014-08-26 09:37:52 +0000388 return is(tok::comment) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000389 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000390 }
391
Daniel Jasper78b194992014-08-06 14:15:41 +0000392 /// \brief Returns \c true if this is a keyword that can be used
393 /// like a function call (e.g. sizeof, typeid, ...).
394 bool isFunctionLikeKeyword() const {
395 switch (Tok.getKind()) {
396 case tok::kw_throw:
397 case tok::kw_typeid:
398 case tok::kw_return:
399 case tok::kw_sizeof:
400 case tok::kw_alignof:
401 case tok::kw_alignas:
402 case tok::kw_decltype:
403 case tok::kw_noexcept:
404 case tok::kw_static_assert:
405 case tok::kw___attribute:
406 return true;
407 default:
408 return false;
409 }
410 }
411
Daniel Jasper7209bb92016-12-13 11:16:42 +0000412 /// \brief Returns \c true if this is a string literal that's like a label,
413 /// e.g. ends with "=" or ":".
414 bool isLabelString() const {
415 if (!is(tok::string_literal))
416 return false;
417 StringRef Content = TokenText;
418 if (Content.startswith("\"") || Content.startswith("'"))
419 Content = Content.drop_front(1);
420 if (Content.endswith("\"") || Content.endswith("'"))
421 Content = Content.drop_back(1);
422 Content = Content.trim();
423 return Content.size() > 1 &&
424 (Content.back() == ':' || Content.back() == '=');
425 }
426
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000427 /// \brief Returns actual token start location without leading escaped
428 /// newlines and whitespace.
429 ///
430 /// This can be different to Tok.getLocation(), which includes leading escaped
431 /// newlines.
432 SourceLocation getStartOfNonWhitespace() const {
433 return WhitespaceRange.getEnd();
434 }
435
Alexander Kornienko4b672072013-06-03 16:45:03 +0000436 prec::Level getPrecedence() const {
437 return getBinOpPrecedence(Tok.getKind(), true, true);
438 }
439
440 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000441 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000442 FormatToken *Tok = Previous;
Craig Topper2145bc02014-05-09 08:15:10 +0000443 while (Tok && Tok->is(tok::comment))
Alexander Kornienko4b672072013-06-03 16:45:03 +0000444 Tok = Tok->Previous;
445 return Tok;
446 }
447
448 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000449 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000450 const FormatToken *Tok = Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000451 while (Tok && Tok->is(tok::comment))
Alexander Kornienko4b672072013-06-03 16:45:03 +0000452 Tok = Tok->Next;
453 return Tok;
454 }
455
Daniel Jasperb8f61682013-10-22 15:45:58 +0000456 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
457 /// list that should be indented with a block indent.
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000458 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
Daniel Jasper98e0b122017-02-20 14:51:16 +0000459 if (is(TT_TemplateString) && opensScope())
460 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000461 return is(TT_ArrayInitializerLSquare) ||
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000462 (is(tok::l_brace) &&
463 (BlockKind == BK_Block || is(TT_DictLiteral) ||
464 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
Daniel Jasperb8f61682013-10-22 15:45:58 +0000465 }
466
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000467 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
468 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
Daniel Jasper98e0b122017-02-20 14:51:16 +0000469 if (is(TT_TemplateString) && closesScope())
470 return true;
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000471 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
Daniel Jasper1db6c382013-10-22 15:30:28 +0000472 }
473
Alexander Kornienko4b672072013-06-03 16:45:03 +0000474private:
475 // Disallow copying.
Aaron Ballmanabc18922015-02-15 22:54:08 +0000476 FormatToken(const FormatToken &) = delete;
477 void operator=(const FormatToken &) = delete;
Martin Probst1244ecb2016-05-29 14:41:02 +0000478
479 template <typename A, typename... Ts>
480 bool startsSequenceInternal(A K1, Ts... Tokens) const {
481 if (is(tok::comment) && Next)
482 return Next->startsSequenceInternal(K1, Tokens...);
483 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
484 }
485
486 template <typename A>
487 bool startsSequenceInternal(A K1) const {
488 if (is(tok::comment) && Next)
489 return Next->startsSequenceInternal(K1);
490 return is(K1);
491 }
492
493 template <typename A, typename... Ts>
494 bool endsSequenceInternal(A K1) const {
495 if (is(tok::comment) && Previous)
496 return Previous->endsSequenceInternal(K1);
497 return is(K1);
498 }
499
500 template <typename A, typename... Ts>
501 bool endsSequenceInternal(A K1, Ts... Tokens) const {
502 if (is(tok::comment) && Previous)
503 return Previous->endsSequenceInternal(K1, Tokens...);
504 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
505 }
Alexander Kornienko4b672072013-06-03 16:45:03 +0000506};
507
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000508class ContinuationIndenter;
509struct LineState;
510
511class TokenRole {
512public:
513 TokenRole(const FormatStyle &Style) : Style(Style) {}
514 virtual ~TokenRole();
515
516 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
517 /// this function precomputes required information for formatting.
518 virtual void precomputeFormattingInfos(const FormatToken *Token);
519
520 /// \brief Apply the special formatting that the given role demands.
521 ///
Daniel Jasper01603472014-01-09 13:42:56 +0000522 /// Assumes that the token having this role is already formatted.
523 ///
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000524 /// Continues formatting from \p State leaving indentation to \p Indenter and
525 /// returns the total penalty that this formatting incurs.
Daniel Jasper01603472014-01-09 13:42:56 +0000526 virtual unsigned formatFromToken(LineState &State,
527 ContinuationIndenter *Indenter,
528 bool DryRun) {
529 return 0;
530 }
531
532 /// \brief Same as \c formatFromToken, but assumes that the first token has
533 /// already been set thereby deciding on the first line break.
534 virtual unsigned formatAfterToken(LineState &State,
535 ContinuationIndenter *Indenter,
536 bool DryRun) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000537 return 0;
538 }
539
540 /// \brief Notifies the \c Role that a comma was found.
541 virtual void CommaFound(const FormatToken *Token) {}
542
543protected:
544 const FormatStyle &Style;
545};
546
547class CommaSeparatedList : public TokenRole {
548public:
Daniel Jasper01603472014-01-09 13:42:56 +0000549 CommaSeparatedList(const FormatStyle &Style)
550 : TokenRole(Style), HasNestedBracedList(false) {}
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000551
Craig Topperfb6b25b2014-03-15 04:29:04 +0000552 void precomputeFormattingInfos(const FormatToken *Token) override;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000553
Craig Topperfb6b25b2014-03-15 04:29:04 +0000554 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
555 bool DryRun) override;
Daniel Jasper01603472014-01-09 13:42:56 +0000556
Craig Topperfb6b25b2014-03-15 04:29:04 +0000557 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
558 bool DryRun) override;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000559
560 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000561 void CommaFound(const FormatToken *Token) override {
562 Commas.push_back(Token);
563 }
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000564
565private:
566 /// \brief A struct that holds information on how to format a given list with
567 /// a specific number of columns.
568 struct ColumnFormat {
569 /// \brief The number of columns to use.
570 unsigned Columns;
571
572 /// \brief The total width in characters.
573 unsigned TotalWidth;
574
575 /// \brief The number of lines required for this format.
576 unsigned LineCount;
577
578 /// \brief The size of each column in characters.
579 SmallVector<unsigned, 8> ColumnSizes;
580 };
581
582 /// \brief Calculate which \c ColumnFormat fits best into
583 /// \p RemainingCharacters.
584 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
585
586 /// \brief The ordered \c FormatTokens making up the commas of this list.
587 SmallVector<const FormatToken *, 8> Commas;
588
589 /// \brief The length of each of the list's items in characters including the
590 /// trailing comma.
591 SmallVector<unsigned, 8> ItemLengths;
592
593 /// \brief Precomputed formats that can be used for this list.
594 SmallVector<ColumnFormat, 4> Formats;
Daniel Jasper01603472014-01-09 13:42:56 +0000595
596 bool HasNestedBracedList;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000597};
598
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000599/// \brief Encapsulates keywords that are context sensitive or for languages not
600/// properly supported by Clang's lexer.
601struct AdditionalKeywords {
602 AdditionalKeywords(IdentifierTable &IdentTable) {
Daniel Jasper5d7f06f2015-08-24 14:28:08 +0000603 kw_final = &IdentTable.get("final");
604 kw_override = &IdentTable.get("override");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000605 kw_in = &IdentTable.get("in");
Daniel Jasperb7fda112016-02-11 13:24:15 +0000606 kw_of = &IdentTable.get("of");
Daniel Jasper31f6c542014-12-05 10:42:21 +0000607 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
608 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000609 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
Daniel Jasper31f6c542014-12-05 10:42:21 +0000610 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000611
Martin Probstc4a0dd42016-05-20 11:24:24 +0000612 kw_as = &IdentTable.get("as");
Martin Probst5f8445b2016-04-24 22:05:09 +0000613 kw_async = &IdentTable.get("async");
614 kw_await = &IdentTable.get("await");
Martin Probst72fd75a2016-11-10 16:20:58 +0000615 kw_declare = &IdentTable.get("declare");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000616 kw_finally = &IdentTable.get("finally");
Daniel Jasper8fc7a1e2016-03-22 14:32:20 +0000617 kw_from = &IdentTable.get("from");
Martin Probst5f8445b2016-04-24 22:05:09 +0000618 kw_function = &IdentTable.get("function");
Daniel Jasper354aa512015-02-19 16:07:32 +0000619 kw_import = &IdentTable.get("import");
Daniel Jasper779c66f2015-12-30 08:00:58 +0000620 kw_is = &IdentTable.get("is");
Daniel Jasper9f642f72015-09-28 14:28:08 +0000621 kw_let = &IdentTable.get("let");
Martin Probst72fd75a2016-11-10 16:20:58 +0000622 kw_module = &IdentTable.get("module");
Martin Probst1b7f9802016-06-23 19:52:32 +0000623 kw_type = &IdentTable.get("type");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000624 kw_var = &IdentTable.get("var");
Martin Probst5f8445b2016-04-24 22:05:09 +0000625 kw_yield = &IdentTable.get("yield");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000626
Daniel Jasper82c92752014-11-21 12:19:07 +0000627 kw_abstract = &IdentTable.get("abstract");
Nico Weber4f113492015-09-15 23:48:17 +0000628 kw_assert = &IdentTable.get("assert");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000629 kw_extends = &IdentTable.get("extends");
630 kw_implements = &IdentTable.get("implements");
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000631 kw_instanceof = &IdentTable.get("instanceof");
Nico Webera644d7f2014-11-10 16:30:02 +0000632 kw_interface = &IdentTable.get("interface");
Nico Webered501662015-01-13 22:32:50 +0000633 kw_native = &IdentTable.get("native");
Daniel Jasper9b9e0762014-11-26 18:03:42 +0000634 kw_package = &IdentTable.get("package");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000635 kw_synchronized = &IdentTable.get("synchronized");
636 kw_throws = &IdentTable.get("throws");
Nico Weberfac23712015-02-04 15:26:27 +0000637 kw___except = &IdentTable.get("__except");
Nico Weber21088802017-02-10 19:36:52 +0000638 kw___has_include = &IdentTable.get("__has_include");
639 kw___has_include_next = &IdentTable.get("__has_include_next");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000640
Daniel Jasperee4a8a12015-04-22 09:45:42 +0000641 kw_mark = &IdentTable.get("mark");
642
Daniel Jasperd8d98392015-11-20 14:32:54 +0000643 kw_extend = &IdentTable.get("extend");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000644 kw_option = &IdentTable.get("option");
645 kw_optional = &IdentTable.get("optional");
646 kw_repeated = &IdentTable.get("repeated");
647 kw_required = &IdentTable.get("required");
648 kw_returns = &IdentTable.get("returns");
Daniel Jasper53395402015-04-07 15:04:40 +0000649
650 kw_signals = &IdentTable.get("signals");
Daniel Jaspera00de632015-12-01 12:05:04 +0000651 kw_qsignals = &IdentTable.get("Q_SIGNALS");
Daniel Jasper53395402015-04-07 15:04:40 +0000652 kw_slots = &IdentTable.get("slots");
653 kw_qslots = &IdentTable.get("Q_SLOTS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000654 }
655
Nico Weberfac23712015-02-04 15:26:27 +0000656 // Context sensitive keywords.
Daniel Jasper5d7f06f2015-08-24 14:28:08 +0000657 IdentifierInfo *kw_final;
658 IdentifierInfo *kw_override;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000659 IdentifierInfo *kw_in;
Daniel Jasperb7fda112016-02-11 13:24:15 +0000660 IdentifierInfo *kw_of;
Daniel Jasper31f6c542014-12-05 10:42:21 +0000661 IdentifierInfo *kw_CF_ENUM;
662 IdentifierInfo *kw_CF_OPTIONS;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000663 IdentifierInfo *kw_NS_ENUM;
Daniel Jasper31f6c542014-12-05 10:42:21 +0000664 IdentifierInfo *kw_NS_OPTIONS;
Nico Weberfac23712015-02-04 15:26:27 +0000665 IdentifierInfo *kw___except;
Nico Weber21088802017-02-10 19:36:52 +0000666 IdentifierInfo *kw___has_include;
667 IdentifierInfo *kw___has_include_next;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000668
669 // JavaScript keywords.
Martin Probstc4a0dd42016-05-20 11:24:24 +0000670 IdentifierInfo *kw_as;
Martin Probst5f8445b2016-04-24 22:05:09 +0000671 IdentifierInfo *kw_async;
672 IdentifierInfo *kw_await;
Martin Probst72fd75a2016-11-10 16:20:58 +0000673 IdentifierInfo *kw_declare;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000674 IdentifierInfo *kw_finally;
Daniel Jasper8fc7a1e2016-03-22 14:32:20 +0000675 IdentifierInfo *kw_from;
Martin Probst5f8445b2016-04-24 22:05:09 +0000676 IdentifierInfo *kw_function;
Daniel Jasper354aa512015-02-19 16:07:32 +0000677 IdentifierInfo *kw_import;
Daniel Jasper779c66f2015-12-30 08:00:58 +0000678 IdentifierInfo *kw_is;
Daniel Jasper9f642f72015-09-28 14:28:08 +0000679 IdentifierInfo *kw_let;
Martin Probst72fd75a2016-11-10 16:20:58 +0000680 IdentifierInfo *kw_module;
Martin Probst1b7f9802016-06-23 19:52:32 +0000681 IdentifierInfo *kw_type;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000682 IdentifierInfo *kw_var;
Martin Probst5f8445b2016-04-24 22:05:09 +0000683 IdentifierInfo *kw_yield;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000684
685 // Java keywords.
Daniel Jasper82c92752014-11-21 12:19:07 +0000686 IdentifierInfo *kw_abstract;
Nico Weber4f113492015-09-15 23:48:17 +0000687 IdentifierInfo *kw_assert;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000688 IdentifierInfo *kw_extends;
689 IdentifierInfo *kw_implements;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000690 IdentifierInfo *kw_instanceof;
Nico Webera644d7f2014-11-10 16:30:02 +0000691 IdentifierInfo *kw_interface;
Nico Webered501662015-01-13 22:32:50 +0000692 IdentifierInfo *kw_native;
Daniel Jasper9b9e0762014-11-26 18:03:42 +0000693 IdentifierInfo *kw_package;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000694 IdentifierInfo *kw_synchronized;
695 IdentifierInfo *kw_throws;
696
Daniel Jasperee4a8a12015-04-22 09:45:42 +0000697 // Pragma keywords.
698 IdentifierInfo *kw_mark;
699
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000700 // Proto keywords.
Daniel Jasperd8d98392015-11-20 14:32:54 +0000701 IdentifierInfo *kw_extend;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000702 IdentifierInfo *kw_option;
703 IdentifierInfo *kw_optional;
704 IdentifierInfo *kw_repeated;
705 IdentifierInfo *kw_required;
706 IdentifierInfo *kw_returns;
Daniel Jasper53395402015-04-07 15:04:40 +0000707
708 // QT keywords.
709 IdentifierInfo *kw_signals;
Daniel Jaspera00de632015-12-01 12:05:04 +0000710 IdentifierInfo *kw_qsignals;
Daniel Jasper53395402015-04-07 15:04:40 +0000711 IdentifierInfo *kw_slots;
712 IdentifierInfo *kw_qslots;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000713};
714
Alexander Kornienko4b672072013-06-03 16:45:03 +0000715} // namespace format
716} // namespace clang
717
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +0000718#endif