blob: 3b3600fede97b8e86ace15ad8615bf66a4ba7efb [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) \
Martin Probst22b8d2692017-03-13 09:14:23 +000057 TYPE(JsNonNullAssertion) \
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000058 TYPE(JsTypeColon) \
Daniel Jasper91b1d1a2016-03-21 17:57:31 +000059 TYPE(JsTypeOperator) \
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000060 TYPE(JsTypeOptionalQuestion) \
61 TYPE(LambdaArrow) \
62 TYPE(LambdaLSquare) \
63 TYPE(LeadingJavaAnnotation) \
64 TYPE(LineComment) \
65 TYPE(MacroBlockBegin) \
66 TYPE(MacroBlockEnd) \
67 TYPE(ObjCBlockLBrace) \
68 TYPE(ObjCBlockLParen) \
69 TYPE(ObjCDecl) \
70 TYPE(ObjCForIn) \
71 TYPE(ObjCMethodExpr) \
72 TYPE(ObjCMethodSpecifier) \
73 TYPE(ObjCProperty) \
74 TYPE(ObjCStringLiteral) \
75 TYPE(OverloadedOperator) \
76 TYPE(OverloadedOperatorLParen) \
77 TYPE(PointerOrReference) \
78 TYPE(PureVirtualSpecifier) \
79 TYPE(RangeBasedForLoopColon) \
80 TYPE(RegexLiteral) \
81 TYPE(SelectorName) \
82 TYPE(StartOfName) \
83 TYPE(TemplateCloser) \
84 TYPE(TemplateOpener) \
85 TYPE(TemplateString) \
86 TYPE(TrailingAnnotation) \
87 TYPE(TrailingReturnArrow) \
88 TYPE(TrailingUnaryOperator) \
89 TYPE(UnaryOperator) \
90 TYPE(Unknown)
91
Alexander Kornienko4b672072013-06-03 16:45:03 +000092enum TokenType {
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000093#define TYPE(X) TT_##X,
94LIST_TOKEN_TYPES
95#undef TYPE
96 NUM_TOKEN_TYPES
Alexander Kornienko4b672072013-06-03 16:45:03 +000097};
98
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000099/// \brief Determines the name of a token type.
100const char *getTokenTypeName(TokenType Type);
101
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000102// Represents what type of block a set of braces open.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000103enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000104
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000105// The packing kind of a function's parameters.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000106enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000107
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000108enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
Manuel Klimek71814b42013-10-11 21:25:45 +0000109
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000110class TokenRole;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000111class AnnotatedLine;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000112
Alexander Kornienko4b672072013-06-03 16:45:03 +0000113/// \brief A wrapper around a \c Token storing information about the
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000114/// whitespace characters preceding it.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000115struct FormatToken {
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000116 FormatToken() {}
Alexander Kornienko4b672072013-06-03 16:45:03 +0000117
118 /// \brief The \c Token.
119 Token Tok;
120
121 /// \brief The number of newlines immediately before the \c Token.
122 ///
123 /// This can be used to determine what the user wrote in the original code
124 /// and thereby e.g. leave an empty line between two function definitions.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000125 unsigned NewlinesBefore = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000126
127 /// \brief Whether there is at least one unescaped newline before the \c
128 /// Token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000129 bool HasUnescapedNewline = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000130
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000131 /// \brief The range of the whitespace immediately preceding the \c Token.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000132 SourceRange WhitespaceRange;
133
134 /// \brief The offset just past the last '\n' in this token's leading
135 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000136 unsigned LastNewlineOffset = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000137
Alexander Kornienko39856b72013-09-10 09:38:25 +0000138 /// \brief The width of the non-whitespace parts of the token (or its first
139 /// line for multi-line tokens) in columns.
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000140 /// We need this to correctly measure number of columns a token spans.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000141 unsigned ColumnWidth = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000142
Alexander Kornienko39856b72013-09-10 09:38:25 +0000143 /// \brief Contains the width in columns of the last line of a multi-line
Alexander Kornienko632abb92013-09-02 13:58:14 +0000144 /// token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000145 unsigned LastLineColumnWidth = 0;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000146
Alexander Kornienko39856b72013-09-10 09:38:25 +0000147 /// \brief Whether the token text contains newlines (escaped or not).
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000148 bool IsMultiline = false;
Alexander Kornienko632abb92013-09-02 13:58:14 +0000149
Martin Probst7ea9b6d2016-05-29 14:41:36 +0000150 /// \brief Indicates that this is the first token of the file.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000151 bool IsFirst = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000152
153 /// \brief Whether there must be a line break before this token.
154 ///
155 /// This happens for example when a preprocessor directive ended directly
156 /// before the token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000157 bool MustBreakBefore = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000158
159 /// \brief The raw text of the token.
160 ///
161 /// Contains the raw token text without leading whitespace and without leading
162 /// escaped newlines.
163 StringRef TokenText;
164
Daniel Jasper8369aa52013-07-16 20:28:33 +0000165 /// \brief Set to \c true if this token is an unterminated literal.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000166 bool IsUnterminatedLiteral = 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000167
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000168 /// \brief Contains the kind of block if this token is a brace.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000169 BraceBlockKind BlockKind = BK_Unknown;
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000170
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000171 TokenType Type = TT_Unknown;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000172
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000173 /// \brief The number of spaces that should be inserted before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000174 unsigned SpacesRequiredBefore = 0;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000175
176 /// \brief \c true if it is allowed to break before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000177 bool CanBreakBefore = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000178
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000179 /// \brief \c true if this is the ">" of "template<..>".
180 bool ClosesTemplateDeclaration = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000181
182 /// \brief Number of parameters, if this is "(", "[" or "<".
183 ///
184 /// This is initialized to 1 as we don't need to distinguish functions with
185 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
186 /// the number of commas.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000187 unsigned ParameterCount = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000188
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000189 /// \brief Number of parameters that are nested blocks,
190 /// if this is "(", "[" or "<".
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000191 unsigned BlockParameterCount = 0;
Daniel Jasper114a2bc2014-06-03 12:02:45 +0000192
Daniel Jasperde7ca752015-05-04 07:39:00 +0000193 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
194 /// the surrounding bracket.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000195 tok::TokenKind ParentBracket = tok::unknown;
Daniel Jasperde7ca752015-05-04 07:39:00 +0000196
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000197 /// \brief A token can have a special role that can carry extra information
198 /// about the token's formatting.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000199 std::unique_ptr<TokenRole> Role;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000200
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000201 /// \brief If this is an opening parenthesis, how are the parameters packed?
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000202 ParameterPackingKind PackingKind = PPK_Inconclusive;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000203
Manuel Klimek31c85922013-08-29 15:21:40 +0000204 /// \brief The total length of the unwrapped line up to and including this
205 /// token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000206 unsigned TotalLength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000207
Alexander Kornienko39856b72013-09-10 09:38:25 +0000208 /// \brief The original 0-based column of this token, including expanded tabs.
209 /// The configured TabWidth is used as tab width.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000210 unsigned OriginalColumn = 0;
Manuel Klimek31c85922013-08-29 15:21:40 +0000211
Alexander Kornienko4b672072013-06-03 16:45:03 +0000212 /// \brief The length of following tokens until the next natural split point,
213 /// or the next token that can be broken.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000214 unsigned UnbreakableTailLength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000215
216 // FIXME: Come up with a 'cleaner' concept.
217 /// \brief The binding strength of a token. This is a combined value of
218 /// operator precedence, parenthesis nesting, etc.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000219 unsigned BindingStrength = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000220
Daniel Jasper63af7c42013-12-09 14:40:19 +0000221 /// \brief The nesting level of this token, i.e. the number of surrounding (),
222 /// [], {} or <>.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000223 unsigned NestingLevel = 0;
Daniel Jasper63af7c42013-12-09 14:40:19 +0000224
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000225 /// \brief The indent level of this token. Copied from the surrounding line.
226 unsigned IndentLevel = 0;
227
Alexander Kornienko4b672072013-06-03 16:45:03 +0000228 /// \brief Penalty for inserting a line break before this token.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000229 unsigned SplitPenalty = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000230
231 /// \brief If this is the first ObjC selector name in an ObjC method
232 /// definition or call, this contains the length of the longest name.
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000233 ///
234 /// This being set to 0 means that the selectors should not be colon-aligned,
235 /// e.g. because several of them are block-type.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000236 unsigned LongestObjCSelectorName = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000237
238 /// \brief Stores the number of required fake parentheses and the
239 /// corresponding operator precedence.
240 ///
241 /// If multiple fake parentheses start at a token, this vector stores them in
242 /// reverse order, i.e. inner fake parenthesis first.
243 SmallVector<prec::Level, 4> FakeLParens;
244 /// \brief Insert this many fake ) after this token for correct indentation.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000245 unsigned FakeRParens = 0;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000246
Daniel Jasper562ecd42013-09-06 08:08:14 +0000247 /// \brief \c true if this token starts a binary expression, i.e. has at least
248 /// one fake l_paren with a precedence greater than prec::Unknown.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000249 bool StartsBinaryExpression = false;
Daniel Jasper562ecd42013-09-06 08:08:14 +0000250 /// \brief \c true if this token ends a binary expression.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000251 bool EndsBinaryExpression = false;
Daniel Jasper562ecd42013-09-06 08:08:14 +0000252
Daniel Jasper0e617842014-04-16 12:26:54 +0000253 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
254 /// with the same precedence, contains the 0-based operator index.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000255 unsigned OperatorIndex = 0;
Daniel Jasper0e617842014-04-16 12:26:54 +0000256
Daniel Jasper00492f92016-01-05 13:03:50 +0000257 /// \brief If this is an operator (or "."/"->") in a sequence of operators
258 /// with the same precedence, points to the next operator.
259 FormatToken *NextOperator = nullptr;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000260
261 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
262 ///
263 /// Only set if \c Type == \c TT_StartOfName.
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000264 bool PartOfMultiVariableDeclStmt = false;
Alexander Kornienko4b672072013-06-03 16:45:03 +0000265
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000266 /// \brief Does this line comment continue a line comment section?
267 ///
268 /// Only set to true if \c Type == \c TT_LineComment.
269 bool ContinuesLineCommentSection = false;
270
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000271 /// \brief If this is a bracket, this points to the matching one.
272 FormatToken *MatchingParen = nullptr;
273
274 /// \brief The previous token in the unwrapped line.
275 FormatToken *Previous = nullptr;
276
277 /// \brief The next token in the unwrapped line.
278 FormatToken *Next = nullptr;
279
280 /// \brief If this token starts a block, this contains all the unwrapped lines
281 /// in it.
282 SmallVector<AnnotatedLine *, 1> Children;
283
284 /// \brief Stores the formatting decision for the token once it was made.
285 FormatDecision Decision = FD_Unformatted;
286
287 /// \brief If \c true, this token has been fully formatted (indented and
288 /// potentially re-formatted inside), and we do not allow further formatting
289 /// changes.
290 bool Finalized = false;
Daniel Jaspere1e43192014-04-01 12:55:11 +0000291
Alexander Kornienko4b672072013-06-03 16:45:03 +0000292 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
Daniel Jasper8354ea82014-11-21 12:14:12 +0000293 bool is(TokenType TT) const { return Type == TT; }
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000294 bool is(const IdentifierInfo *II) const {
295 return II && II == Tok.getIdentifierInfo();
296 }
Daniel Jasperd7884572015-08-14 12:44:06 +0000297 bool is(tok::PPKeywordKind Kind) const {
298 return Tok.getIdentifierInfo() &&
299 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
300 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000301 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000302 return is(K1) || is(K2);
303 }
Benjamin Kramerc5bc3cd2015-02-15 20:11:14 +0000304 template <typename A, typename B, typename... Ts>
305 bool isOneOf(A K1, B K2, Ts... Ks) const {
306 return is(K1) || isOneOf(K2, Ks...);
Aaron Ballman484ee9b2014-11-24 15:42:34 +0000307 }
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000308 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000309
Martin Probst1244ecb2016-05-29 14:41:02 +0000310 /// \c true if this token starts a sequence with the given tokens in order,
311 /// following the ``Next`` pointers, ignoring comments.
312 template <typename A, typename... Ts>
313 bool startsSequence(A K1, Ts... Tokens) const {
314 return startsSequenceInternal(K1, Tokens...);
315 }
316
317 /// \c true if this token ends a sequence with the given tokens in order,
318 /// following the ``Previous`` pointers, ignoring comments.
319 template <typename A, typename... Ts>
320 bool endsSequence(A K1, Ts... Tokens) const {
321 return endsSequenceInternal(K1, Tokens...);
322 }
323
Daniel Jasper04b6a082013-12-20 06:22:01 +0000324 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
Alexander Kornienko4b672072013-06-03 16:45:03 +0000325
326 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
327 return Tok.isObjCAtKeyword(Kind);
328 }
329
330 bool isAccessSpecifier(bool ColonRequired = true) const {
331 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
332 (!ColonRequired || (Next && Next->is(tok::colon)));
333 }
334
Daniel Jaspercb51cf42014-01-16 09:11:55 +0000335 /// \brief Determine whether the token is a simple-type-specifier.
336 bool isSimpleTypeSpecifier() const;
337
Alexander Kornienko4b672072013-06-03 16:45:03 +0000338 bool isObjCAccessSpecifier() const {
339 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
340 Next->isObjCAtKeyword(tok::objc_protected) ||
341 Next->isObjCAtKeyword(tok::objc_package) ||
342 Next->isObjCAtKeyword(tok::objc_private));
343 }
344
345 /// \brief Returns whether \p Tok is ([{ or a template opening <.
346 bool opensScope() const {
Daniel Jasper24de6fb2017-01-31 13:03:07 +0000347 if (is(TT_TemplateString) && TokenText.endswith("${"))
348 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000349 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
350 TT_TemplateOpener);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000351 }
Nico Weber0f987a62013-06-25 19:25:12 +0000352 /// \brief Returns whether \p Tok is )]} or a template closing >.
Alexander Kornienko4b672072013-06-03 16:45:03 +0000353 bool closesScope() const {
Daniel Jasper24de6fb2017-01-31 13:03:07 +0000354 if (is(TT_TemplateString) && TokenText.startswith("}"))
355 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000356 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
357 TT_TemplateCloser);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000358 }
359
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000360 /// \brief Returns \c true if this is a "." or "->" accessing a member.
361 bool isMemberAccess() const {
Daniel Jasper85bcadc2014-07-09 13:07:57 +0000362 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
Daniel Jasper05cd9292015-03-26 18:46:28 +0000363 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
364 TT_LambdaArrow);
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000365 }
366
Alexander Kornienko4b672072013-06-03 16:45:03 +0000367 bool isUnaryOperator() const {
368 switch (Tok.getKind()) {
369 case tok::plus:
370 case tok::plusplus:
371 case tok::minus:
372 case tok::minusminus:
373 case tok::exclaim:
374 case tok::tilde:
375 case tok::kw_sizeof:
376 case tok::kw_alignof:
377 return true;
378 default:
379 return false;
380 }
381 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000382
Alexander Kornienko4b672072013-06-03 16:45:03 +0000383 bool isBinaryOperator() const {
384 // Comma is a binary operator, but does not behave as such wrt. formatting.
385 return getPrecedence() > prec::Comma;
386 }
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000387
Alexander Kornienko4b672072013-06-03 16:45:03 +0000388 bool isTrailingComment() const {
Daniel Jasper610381f2014-08-26 09:37:52 +0000389 return is(tok::comment) &&
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000390 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
Alexander Kornienko4b672072013-06-03 16:45:03 +0000391 }
392
Daniel Jasper78b194992014-08-06 14:15:41 +0000393 /// \brief Returns \c true if this is a keyword that can be used
394 /// like a function call (e.g. sizeof, typeid, ...).
395 bool isFunctionLikeKeyword() const {
396 switch (Tok.getKind()) {
397 case tok::kw_throw:
398 case tok::kw_typeid:
399 case tok::kw_return:
400 case tok::kw_sizeof:
401 case tok::kw_alignof:
402 case tok::kw_alignas:
403 case tok::kw_decltype:
404 case tok::kw_noexcept:
405 case tok::kw_static_assert:
406 case tok::kw___attribute:
407 return true;
408 default:
409 return false;
410 }
411 }
412
Daniel Jasper7209bb92016-12-13 11:16:42 +0000413 /// \brief Returns \c true if this is a string literal that's like a label,
414 /// e.g. ends with "=" or ":".
415 bool isLabelString() const {
416 if (!is(tok::string_literal))
417 return false;
418 StringRef Content = TokenText;
419 if (Content.startswith("\"") || Content.startswith("'"))
420 Content = Content.drop_front(1);
421 if (Content.endswith("\"") || Content.endswith("'"))
422 Content = Content.drop_back(1);
423 Content = Content.trim();
424 return Content.size() > 1 &&
425 (Content.back() == ':' || Content.back() == '=');
426 }
427
Daniel Jasper3cea45d2015-05-04 08:51:40 +0000428 /// \brief Returns actual token start location without leading escaped
429 /// newlines and whitespace.
430 ///
431 /// This can be different to Tok.getLocation(), which includes leading escaped
432 /// newlines.
433 SourceLocation getStartOfNonWhitespace() const {
434 return WhitespaceRange.getEnd();
435 }
436
Alexander Kornienko4b672072013-06-03 16:45:03 +0000437 prec::Level getPrecedence() const {
438 return getBinOpPrecedence(Tok.getKind(), true, true);
439 }
440
441 /// \brief Returns the previous token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000442 FormatToken *getPreviousNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000443 FormatToken *Tok = Previous;
Craig Topper2145bc02014-05-09 08:15:10 +0000444 while (Tok && Tok->is(tok::comment))
Alexander Kornienko4b672072013-06-03 16:45:03 +0000445 Tok = Tok->Previous;
446 return Tok;
447 }
448
449 /// \brief Returns the next token ignoring comments.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000450 const FormatToken *getNextNonComment() const {
Alexander Kornienko4b672072013-06-03 16:45:03 +0000451 const FormatToken *Tok = Next;
Craig Topper2145bc02014-05-09 08:15:10 +0000452 while (Tok && Tok->is(tok::comment))
Alexander Kornienko4b672072013-06-03 16:45:03 +0000453 Tok = Tok->Next;
454 return Tok;
455 }
456
Daniel Jasperb8f61682013-10-22 15:45:58 +0000457 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
458 /// list that should be indented with a block indent.
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000459 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
Daniel Jasper98e0b122017-02-20 14:51:16 +0000460 if (is(TT_TemplateString) && opensScope())
461 return true;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000462 return is(TT_ArrayInitializerLSquare) ||
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000463 (is(tok::l_brace) &&
464 (BlockKind == BK_Block || is(TT_DictLiteral) ||
465 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
Daniel Jasperb8f61682013-10-22 15:45:58 +0000466 }
467
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000468 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
469 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
Daniel Jasper98e0b122017-02-20 14:51:16 +0000470 if (is(TT_TemplateString) && closesScope())
471 return true;
Daniel Jasperbd73bcf2015-10-27 13:42:08 +0000472 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
Daniel Jasper1db6c382013-10-22 15:30:28 +0000473 }
474
Alexander Kornienko4b672072013-06-03 16:45:03 +0000475private:
476 // Disallow copying.
Aaron Ballmanabc18922015-02-15 22:54:08 +0000477 FormatToken(const FormatToken &) = delete;
478 void operator=(const FormatToken &) = delete;
Martin Probst1244ecb2016-05-29 14:41:02 +0000479
480 template <typename A, typename... Ts>
481 bool startsSequenceInternal(A K1, Ts... Tokens) const {
482 if (is(tok::comment) && Next)
483 return Next->startsSequenceInternal(K1, Tokens...);
484 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
485 }
486
487 template <typename A>
488 bool startsSequenceInternal(A K1) const {
489 if (is(tok::comment) && Next)
490 return Next->startsSequenceInternal(K1);
491 return is(K1);
492 }
493
494 template <typename A, typename... Ts>
495 bool endsSequenceInternal(A K1) const {
496 if (is(tok::comment) && Previous)
497 return Previous->endsSequenceInternal(K1);
498 return is(K1);
499 }
500
501 template <typename A, typename... Ts>
502 bool endsSequenceInternal(A K1, Ts... Tokens) const {
503 if (is(tok::comment) && Previous)
504 return Previous->endsSequenceInternal(K1, Tokens...);
505 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
506 }
Alexander Kornienko4b672072013-06-03 16:45:03 +0000507};
508
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000509class ContinuationIndenter;
510struct LineState;
511
512class TokenRole {
513public:
514 TokenRole(const FormatStyle &Style) : Style(Style) {}
515 virtual ~TokenRole();
516
517 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
518 /// this function precomputes required information for formatting.
519 virtual void precomputeFormattingInfos(const FormatToken *Token);
520
521 /// \brief Apply the special formatting that the given role demands.
522 ///
Daniel Jasper01603472014-01-09 13:42:56 +0000523 /// Assumes that the token having this role is already formatted.
524 ///
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000525 /// Continues formatting from \p State leaving indentation to \p Indenter and
526 /// returns the total penalty that this formatting incurs.
Daniel Jasper01603472014-01-09 13:42:56 +0000527 virtual unsigned formatFromToken(LineState &State,
528 ContinuationIndenter *Indenter,
529 bool DryRun) {
530 return 0;
531 }
532
533 /// \brief Same as \c formatFromToken, but assumes that the first token has
534 /// already been set thereby deciding on the first line break.
535 virtual unsigned formatAfterToken(LineState &State,
536 ContinuationIndenter *Indenter,
537 bool DryRun) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000538 return 0;
539 }
540
541 /// \brief Notifies the \c Role that a comma was found.
542 virtual void CommaFound(const FormatToken *Token) {}
543
544protected:
545 const FormatStyle &Style;
546};
547
548class CommaSeparatedList : public TokenRole {
549public:
Daniel Jasper01603472014-01-09 13:42:56 +0000550 CommaSeparatedList(const FormatStyle &Style)
551 : TokenRole(Style), HasNestedBracedList(false) {}
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000552
Craig Topperfb6b25b2014-03-15 04:29:04 +0000553 void precomputeFormattingInfos(const FormatToken *Token) override;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000554
Craig Topperfb6b25b2014-03-15 04:29:04 +0000555 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
556 bool DryRun) override;
Daniel Jasper01603472014-01-09 13:42:56 +0000557
Craig Topperfb6b25b2014-03-15 04:29:04 +0000558 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
559 bool DryRun) override;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000560
561 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000562 void CommaFound(const FormatToken *Token) override {
563 Commas.push_back(Token);
564 }
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000565
566private:
567 /// \brief A struct that holds information on how to format a given list with
568 /// a specific number of columns.
569 struct ColumnFormat {
570 /// \brief The number of columns to use.
571 unsigned Columns;
572
573 /// \brief The total width in characters.
574 unsigned TotalWidth;
575
576 /// \brief The number of lines required for this format.
577 unsigned LineCount;
578
579 /// \brief The size of each column in characters.
580 SmallVector<unsigned, 8> ColumnSizes;
581 };
582
583 /// \brief Calculate which \c ColumnFormat fits best into
584 /// \p RemainingCharacters.
585 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
586
587 /// \brief The ordered \c FormatTokens making up the commas of this list.
588 SmallVector<const FormatToken *, 8> Commas;
589
590 /// \brief The length of each of the list's items in characters including the
591 /// trailing comma.
592 SmallVector<unsigned, 8> ItemLengths;
593
594 /// \brief Precomputed formats that can be used for this list.
595 SmallVector<ColumnFormat, 4> Formats;
Daniel Jasper01603472014-01-09 13:42:56 +0000596
597 bool HasNestedBracedList;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000598};
599
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000600/// \brief Encapsulates keywords that are context sensitive or for languages not
601/// properly supported by Clang's lexer.
602struct AdditionalKeywords {
603 AdditionalKeywords(IdentifierTable &IdentTable) {
Daniel Jasper5d7f06f2015-08-24 14:28:08 +0000604 kw_final = &IdentTable.get("final");
605 kw_override = &IdentTable.get("override");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000606 kw_in = &IdentTable.get("in");
Daniel Jasperb7fda112016-02-11 13:24:15 +0000607 kw_of = &IdentTable.get("of");
Daniel Jasper31f6c542014-12-05 10:42:21 +0000608 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
609 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000610 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
Daniel Jasper31f6c542014-12-05 10:42:21 +0000611 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000612
Martin Probstc4a0dd42016-05-20 11:24:24 +0000613 kw_as = &IdentTable.get("as");
Martin Probst5f8445b2016-04-24 22:05:09 +0000614 kw_async = &IdentTable.get("async");
615 kw_await = &IdentTable.get("await");
Martin Probst72fd75a2016-11-10 16:20:58 +0000616 kw_declare = &IdentTable.get("declare");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000617 kw_finally = &IdentTable.get("finally");
Daniel Jasper8fc7a1e2016-03-22 14:32:20 +0000618 kw_from = &IdentTable.get("from");
Martin Probst5f8445b2016-04-24 22:05:09 +0000619 kw_function = &IdentTable.get("function");
Martin Probst19c7de02017-04-26 12:34:15 +0000620 kw_get = &IdentTable.get("get");
Daniel Jasper354aa512015-02-19 16:07:32 +0000621 kw_import = &IdentTable.get("import");
Daniel Jasper779c66f2015-12-30 08:00:58 +0000622 kw_is = &IdentTable.get("is");
Daniel Jasper9f642f72015-09-28 14:28:08 +0000623 kw_let = &IdentTable.get("let");
Martin Probst72fd75a2016-11-10 16:20:58 +0000624 kw_module = &IdentTable.get("module");
Martin Probst19c7de02017-04-26 12:34:15 +0000625 kw_set = &IdentTable.get("set");
Martin Probst1b7f9802016-06-23 19:52:32 +0000626 kw_type = &IdentTable.get("type");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000627 kw_var = &IdentTable.get("var");
Martin Probst5f8445b2016-04-24 22:05:09 +0000628 kw_yield = &IdentTable.get("yield");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000629
Daniel Jasper82c92752014-11-21 12:19:07 +0000630 kw_abstract = &IdentTable.get("abstract");
Nico Weber4f113492015-09-15 23:48:17 +0000631 kw_assert = &IdentTable.get("assert");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000632 kw_extends = &IdentTable.get("extends");
633 kw_implements = &IdentTable.get("implements");
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000634 kw_instanceof = &IdentTable.get("instanceof");
Nico Webera644d7f2014-11-10 16:30:02 +0000635 kw_interface = &IdentTable.get("interface");
Nico Webered501662015-01-13 22:32:50 +0000636 kw_native = &IdentTable.get("native");
Daniel Jasper9b9e0762014-11-26 18:03:42 +0000637 kw_package = &IdentTable.get("package");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000638 kw_synchronized = &IdentTable.get("synchronized");
639 kw_throws = &IdentTable.get("throws");
Nico Weberfac23712015-02-04 15:26:27 +0000640 kw___except = &IdentTable.get("__except");
Nico Weber21088802017-02-10 19:36:52 +0000641 kw___has_include = &IdentTable.get("__has_include");
642 kw___has_include_next = &IdentTable.get("__has_include_next");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000643
Daniel Jasperee4a8a12015-04-22 09:45:42 +0000644 kw_mark = &IdentTable.get("mark");
645
Daniel Jasperd8d98392015-11-20 14:32:54 +0000646 kw_extend = &IdentTable.get("extend");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000647 kw_option = &IdentTable.get("option");
648 kw_optional = &IdentTable.get("optional");
649 kw_repeated = &IdentTable.get("repeated");
650 kw_required = &IdentTable.get("required");
651 kw_returns = &IdentTable.get("returns");
Daniel Jasper53395402015-04-07 15:04:40 +0000652
653 kw_signals = &IdentTable.get("signals");
Daniel Jaspera00de632015-12-01 12:05:04 +0000654 kw_qsignals = &IdentTable.get("Q_SIGNALS");
Daniel Jasper53395402015-04-07 15:04:40 +0000655 kw_slots = &IdentTable.get("slots");
656 kw_qslots = &IdentTable.get("Q_SLOTS");
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000657 }
658
Nico Weberfac23712015-02-04 15:26:27 +0000659 // Context sensitive keywords.
Daniel Jasper5d7f06f2015-08-24 14:28:08 +0000660 IdentifierInfo *kw_final;
661 IdentifierInfo *kw_override;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000662 IdentifierInfo *kw_in;
Daniel Jasperb7fda112016-02-11 13:24:15 +0000663 IdentifierInfo *kw_of;
Daniel Jasper31f6c542014-12-05 10:42:21 +0000664 IdentifierInfo *kw_CF_ENUM;
665 IdentifierInfo *kw_CF_OPTIONS;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000666 IdentifierInfo *kw_NS_ENUM;
Daniel Jasper31f6c542014-12-05 10:42:21 +0000667 IdentifierInfo *kw_NS_OPTIONS;
Nico Weberfac23712015-02-04 15:26:27 +0000668 IdentifierInfo *kw___except;
Nico Weber21088802017-02-10 19:36:52 +0000669 IdentifierInfo *kw___has_include;
670 IdentifierInfo *kw___has_include_next;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000671
672 // JavaScript keywords.
Martin Probstc4a0dd42016-05-20 11:24:24 +0000673 IdentifierInfo *kw_as;
Martin Probst5f8445b2016-04-24 22:05:09 +0000674 IdentifierInfo *kw_async;
675 IdentifierInfo *kw_await;
Martin Probst72fd75a2016-11-10 16:20:58 +0000676 IdentifierInfo *kw_declare;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000677 IdentifierInfo *kw_finally;
Daniel Jasper8fc7a1e2016-03-22 14:32:20 +0000678 IdentifierInfo *kw_from;
Martin Probst5f8445b2016-04-24 22:05:09 +0000679 IdentifierInfo *kw_function;
Martin Probst19c7de02017-04-26 12:34:15 +0000680 IdentifierInfo *kw_get;
Daniel Jasper354aa512015-02-19 16:07:32 +0000681 IdentifierInfo *kw_import;
Daniel Jasper779c66f2015-12-30 08:00:58 +0000682 IdentifierInfo *kw_is;
Daniel Jasper9f642f72015-09-28 14:28:08 +0000683 IdentifierInfo *kw_let;
Martin Probst72fd75a2016-11-10 16:20:58 +0000684 IdentifierInfo *kw_module;
Martin Probst19c7de02017-04-26 12:34:15 +0000685 IdentifierInfo *kw_set;
Martin Probst1b7f9802016-06-23 19:52:32 +0000686 IdentifierInfo *kw_type;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000687 IdentifierInfo *kw_var;
Martin Probst5f8445b2016-04-24 22:05:09 +0000688 IdentifierInfo *kw_yield;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000689
690 // Java keywords.
Daniel Jasper82c92752014-11-21 12:19:07 +0000691 IdentifierInfo *kw_abstract;
Nico Weber4f113492015-09-15 23:48:17 +0000692 IdentifierInfo *kw_assert;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000693 IdentifierInfo *kw_extends;
694 IdentifierInfo *kw_implements;
Daniel Jaspera98b7b02014-11-25 10:05:17 +0000695 IdentifierInfo *kw_instanceof;
Nico Webera644d7f2014-11-10 16:30:02 +0000696 IdentifierInfo *kw_interface;
Nico Webered501662015-01-13 22:32:50 +0000697 IdentifierInfo *kw_native;
Daniel Jasper9b9e0762014-11-26 18:03:42 +0000698 IdentifierInfo *kw_package;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000699 IdentifierInfo *kw_synchronized;
700 IdentifierInfo *kw_throws;
701
Daniel Jasperee4a8a12015-04-22 09:45:42 +0000702 // Pragma keywords.
703 IdentifierInfo *kw_mark;
704
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000705 // Proto keywords.
Daniel Jasperd8d98392015-11-20 14:32:54 +0000706 IdentifierInfo *kw_extend;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000707 IdentifierInfo *kw_option;
708 IdentifierInfo *kw_optional;
709 IdentifierInfo *kw_repeated;
710 IdentifierInfo *kw_required;
711 IdentifierInfo *kw_returns;
Daniel Jasper53395402015-04-07 15:04:40 +0000712
713 // QT keywords.
714 IdentifierInfo *kw_signals;
Daniel Jaspera00de632015-12-01 12:05:04 +0000715 IdentifierInfo *kw_qsignals;
Daniel Jasper53395402015-04-07 15:04:40 +0000716 IdentifierInfo *kw_slots;
717 IdentifierInfo *kw_qslots;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000718};
719
Alexander Kornienko4b672072013-06-03 16:45:03 +0000720} // namespace format
721} // namespace clang
722
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +0000723#endif