clang 19.0.0git
FormatToken.h
Go to the documentation of this file.
1//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains the declaration of the FormatToken, a wrapper
11/// around Token with additional information related to formatting.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
16#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
17
20#include "clang/Format/Format.h"
21#include "clang/Lex/Lexer.h"
22#include <unordered_set>
23
24namespace clang {
25namespace format {
26
27#define LIST_TOKEN_TYPES \
28 TYPE(ArrayInitializerLSquare) \
29 TYPE(ArraySubscriptLSquare) \
30 TYPE(AttributeColon) \
31 TYPE(AttributeLParen) \
32 TYPE(AttributeMacro) \
33 TYPE(AttributeRParen) \
34 TYPE(AttributeSquare) \
35 TYPE(BinaryOperator) \
36 TYPE(BitFieldColon) \
37 TYPE(BlockComment) \
38 /* l_brace of a block that is not the body of a (e.g. loop) statement. */ \
39 TYPE(BlockLBrace) \
40 TYPE(BracedListLBrace) \
41 /* The colon at the end of a case label. */ \
42 TYPE(CaseLabelColon) \
43 TYPE(CastRParen) \
44 TYPE(ClassLBrace) \
45 TYPE(ClassRBrace) \
46 /* ternary ?: expression */ \
47 TYPE(ConditionalExpr) \
48 /* the condition in an if statement */ \
49 TYPE(ConditionLParen) \
50 TYPE(ConflictAlternative) \
51 TYPE(ConflictEnd) \
52 TYPE(ConflictStart) \
53 /* l_brace of if/for/while */ \
54 TYPE(ControlStatementLBrace) \
55 TYPE(ControlStatementRBrace) \
56 TYPE(CppCastLParen) \
57 TYPE(CSharpGenericTypeConstraint) \
58 TYPE(CSharpGenericTypeConstraintColon) \
59 TYPE(CSharpGenericTypeConstraintComma) \
60 TYPE(CSharpNamedArgumentColon) \
61 TYPE(CSharpNullable) \
62 TYPE(CSharpNullConditionalLSquare) \
63 TYPE(CSharpStringLiteral) \
64 TYPE(CtorInitializerColon) \
65 TYPE(CtorInitializerComma) \
66 TYPE(CtorDtorDeclName) \
67 TYPE(DesignatedInitializerLSquare) \
68 TYPE(DesignatedInitializerPeriod) \
69 TYPE(DictLiteral) \
70 TYPE(DoWhile) \
71 TYPE(ElseLBrace) \
72 TYPE(ElseRBrace) \
73 TYPE(EnumLBrace) \
74 TYPE(EnumRBrace) \
75 TYPE(FatArrow) \
76 TYPE(ForEachMacro) \
77 TYPE(FunctionAnnotationRParen) \
78 TYPE(FunctionDeclarationName) \
79 TYPE(FunctionLBrace) \
80 TYPE(FunctionLikeOrFreestandingMacro) \
81 TYPE(FunctionTypeLParen) \
82 /* The colons as part of a C11 _Generic selection */ \
83 TYPE(GenericSelectionColon) \
84 /* The colon at the end of a goto label. */ \
85 TYPE(GotoLabelColon) \
86 TYPE(IfMacro) \
87 TYPE(ImplicitStringLiteral) \
88 TYPE(InheritanceColon) \
89 TYPE(InheritanceComma) \
90 TYPE(InlineASMBrace) \
91 TYPE(InlineASMColon) \
92 TYPE(InlineASMSymbolicNameLSquare) \
93 TYPE(JavaAnnotation) \
94 TYPE(JsAndAndEqual) \
95 TYPE(JsComputedPropertyName) \
96 TYPE(JsExponentiation) \
97 TYPE(JsExponentiationEqual) \
98 TYPE(JsPipePipeEqual) \
99 TYPE(JsPrivateIdentifier) \
100 TYPE(JsTypeColon) \
101 TYPE(JsTypeOperator) \
102 TYPE(JsTypeOptionalQuestion) \
103 TYPE(LambdaLBrace) \
104 TYPE(LambdaLSquare) \
105 TYPE(LeadingJavaAnnotation) \
106 TYPE(LineComment) \
107 TYPE(MacroBlockBegin) \
108 TYPE(MacroBlockEnd) \
109 TYPE(ModulePartitionColon) \
110 TYPE(NamespaceLBrace) \
111 TYPE(NamespaceMacro) \
112 TYPE(NamespaceRBrace) \
113 TYPE(NonNullAssertion) \
114 TYPE(NullCoalescingEqual) \
115 TYPE(NullCoalescingOperator) \
116 TYPE(NullPropagatingOperator) \
117 TYPE(ObjCBlockLBrace) \
118 TYPE(ObjCBlockLParen) \
119 TYPE(ObjCDecl) \
120 TYPE(ObjCForIn) \
121 TYPE(ObjCMethodExpr) \
122 TYPE(ObjCMethodSpecifier) \
123 TYPE(ObjCProperty) \
124 TYPE(ObjCStringLiteral) \
125 TYPE(OverloadedOperator) \
126 TYPE(OverloadedOperatorLParen) \
127 TYPE(PointerOrReference) \
128 TYPE(ProtoExtensionLSquare) \
129 TYPE(PureVirtualSpecifier) \
130 TYPE(RangeBasedForLoopColon) \
131 TYPE(RecordLBrace) \
132 TYPE(RecordRBrace) \
133 TYPE(RegexLiteral) \
134 TYPE(RequiresClause) \
135 TYPE(RequiresClauseInARequiresExpression) \
136 TYPE(RequiresExpression) \
137 TYPE(RequiresExpressionLBrace) \
138 TYPE(RequiresExpressionLParen) \
139 TYPE(SelectorName) \
140 TYPE(StartOfName) \
141 TYPE(StatementAttributeLikeMacro) \
142 TYPE(StatementMacro) \
143 /* A string that is part of a string concatenation. For C#, JavaScript, and \
144 * Java, it is used for marking whether a string needs parentheses around it \
145 * if it is to be split into parts joined by `+`. For Verilog, whether \
146 * braces need to be added to split it. Not used for other languages. */ \
147 TYPE(StringInConcatenation) \
148 TYPE(StructLBrace) \
149 TYPE(StructRBrace) \
150 TYPE(StructuredBindingLSquare) \
151 TYPE(TableGenBangOperator) \
152 TYPE(TableGenCondOperator) \
153 TYPE(TableGenCondOperatorColon) \
154 TYPE(TableGenCondOperatorComma) \
155 TYPE(TableGenDAGArgCloser) \
156 TYPE(TableGenDAGArgListColon) \
157 TYPE(TableGenDAGArgListColonToAlign) \
158 TYPE(TableGenDAGArgListComma) \
159 TYPE(TableGenDAGArgListCommaToBreak) \
160 TYPE(TableGenDAGArgOpener) \
161 TYPE(TableGenDAGArgOpenerToBreak) \
162 TYPE(TableGenDAGArgOperatorID) \
163 TYPE(TableGenDAGArgOperatorToBreak) \
164 TYPE(TableGenListCloser) \
165 TYPE(TableGenListOpener) \
166 TYPE(TableGenMultiLineString) \
167 TYPE(TableGenTrailingPasteOperator) \
168 TYPE(TableGenValueSuffix) \
169 TYPE(TemplateCloser) \
170 TYPE(TemplateOpener) \
171 TYPE(TemplateString) \
172 TYPE(TrailingAnnotation) \
173 TYPE(TrailingReturnArrow) \
174 TYPE(TrailingUnaryOperator) \
175 TYPE(TypeDeclarationParen) \
176 TYPE(TypeName) \
177 TYPE(TypenameMacro) \
178 TYPE(UnaryOperator) \
179 TYPE(UnionLBrace) \
180 TYPE(UnionRBrace) \
181 TYPE(UntouchableMacroFunc) \
182 /* Like in 'assign x = 0, y = 1;' . */ \
183 TYPE(VerilogAssignComma) \
184 /* like in begin : block */ \
185 TYPE(VerilogBlockLabelColon) \
186 /* The square bracket for the dimension part of the type name. \
187 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
188 * before the first bracket but not the second. */ \
189 TYPE(VerilogDimensionedTypeName) \
190 /* list of port connections or parameters in a module instantiation */ \
191 TYPE(VerilogInstancePortComma) \
192 TYPE(VerilogInstancePortLParen) \
193 /* A parenthesized list within which line breaks are inserted by the \
194 * formatter, for example the list of ports in a module header. */ \
195 TYPE(VerilogMultiLineListLParen) \
196 /* for the base in a number literal, not including the quote */ \
197 TYPE(VerilogNumberBase) \
198 /* like `(strong1, pull0)` */ \
199 TYPE(VerilogStrength) \
200 /* Things inside the table in user-defined primitives. */ \
201 TYPE(VerilogTableItem) \
202 /* those that separate ports of different types */ \
203 TYPE(VerilogTypeComma) \
204 TYPE(Unknown)
205
206/// Determines the semantic type of a syntactic token, e.g. whether "<" is a
207/// template opener or binary operator.
208enum TokenType : uint8_t {
209#define TYPE(X) TT_##X,
211#undef TYPE
214
215/// Determines the name of a token type.
217
218// Represents what type of block a set of braces open.
220
221// The packing kind of a function's parameters.
223
225
226/// Roles a token can take in a configured macro expansion.
228 /// The token was expanded from a macro argument when formatting the expanded
229 /// token sequence.
231 /// The token is part of a macro argument that was previously formatted as
232 /// expansion when formatting the unexpanded macro call.
234 /// The token was expanded from a macro definition, and is not visible as part
235 /// of the macro call.
236 MR_Hidden,
237};
238
239struct FormatToken;
240
241/// Contains information on the token's role in a macro expansion.
242///
243/// Given the following definitions:
244/// A(X) = [ X ]
245/// B(X) = < X >
246/// C(X) = X
247///
248/// Consider the macro call:
249/// A({B(C(C(x)))}) -> [{<x>}]
250///
251/// In this case, the tokens of the unexpanded macro call will have the
252/// following relevant entries in their macro context (note that formatting
253/// the unexpanded macro call happens *after* formatting the expanded macro
254/// call):
255/// A( { B( C( C(x) ) ) } )
256/// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
257///
258/// [ { < x > } ]
259/// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
260/// ExpandedFrom[0]: A A A A A A A
261/// ExpandedFrom[1]: B B B
262/// ExpandedFrom[2]: C
263/// ExpandedFrom[3]: C
264/// StartOfExpansion: 1 0 1 2 0 0 0
265/// EndOfExpansion: 0 0 0 2 1 0 1
266struct MacroExpansion {
268
269 /// The token's role in the macro expansion.
270 /// When formatting an expanded macro, all tokens that are part of macro
271 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
272 /// the macro call will be MR_Hidden.
273 /// When formatting an unexpanded macro call, all tokens that are part of
274 /// macro arguments will be MR_UnexpandedArg.
276
277 /// The stack of macro call identifier tokens this token was expanded from.
280 /// The number of expansions of which this macro is the first entry.
281 unsigned StartOfExpansion = 0;
282
283 /// The number of currently open expansions in \c ExpandedFrom this macro is
284 /// the last token in.
285 unsigned EndOfExpansion = 0;
286};
289class AnnotatedLine;
290
291/// A wrapper around a \c Token storing information about the
292/// whitespace characters preceding it.
293struct FormatToken {
302 BlockKind(BK_Unknown), Decision(FD_Unformatted),
303 PackingKind(PPK_Inconclusive), TypeIsFinalized(false),
304 Type(TT_Unknown) {}
305
306 /// The \c Token.
308
309 /// The raw text of the token.
310 ///
311 /// Contains the raw token text without leading whitespace and without leading
312 /// escaped newlines.
313 StringRef TokenText;
314
315 /// A token can have a special role that can carry extra information
316 /// about the token's formatting.
317 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
318 /// classes and make this a unique_ptr in the AnnotatedToken class.
319 std::shared_ptr<TokenRole> Role;
321 /// The range of the whitespace immediately preceding the \c Token.
324 /// Whether there is at least one unescaped newline before the \c
325 /// Token.
327
328 /// Whether the token text contains newlines (escaped or not).
329 unsigned IsMultiline : 1;
330
331 /// Indicates that this is the first token of the file.
332 unsigned IsFirst : 1;
333
334 /// Whether there must be a line break before this token.
335 ///
336 /// This happens for example when a preprocessor directive ended directly
337 /// before the token.
338 unsigned MustBreakBefore : 1;
340 /// Whether MustBreakBefore is finalized during parsing and must not
341 /// be reset between runs.
343
344 /// Set to \c true if this token is an unterminated literal.
346
347 /// \c true if it is allowed to break before this token.
348 unsigned CanBreakBefore : 1;
350 /// \c true if this is the ">" of "template<..>".
352
353 /// \c true if this token starts a binary expression, i.e. has at least
354 /// one fake l_paren with a precedence greater than prec::Unknown.
355 unsigned StartsBinaryExpression : 1;
356 /// \c true if this token ends a binary expression.
357 unsigned EndsBinaryExpression : 1;
358
359 /// Is this token part of a \c DeclStmt defining multiple variables?
360 ///
361 /// Only set if \c Type == \c TT_StartOfName.
362 unsigned PartOfMultiVariableDeclStmt : 1;
363
364 /// Does this line comment continue a line comment section?
365 ///
366 /// Only set to true if \c Type == \c TT_LineComment.
367 unsigned ContinuesLineCommentSection : 1;
368
369 /// If \c true, this token has been fully formatted (indented and
370 /// potentially re-formatted inside), and we do not allow further formatting
371 /// changes.
372 unsigned Finalized : 1;
373
374 /// \c true if this is the last token within requires clause.
375 unsigned ClosesRequiresClause : 1;
376
377 /// \c true if this token ends a group of C++ attributes.
378 unsigned EndsCppAttributeGroup : 1;
380private:
381 /// Contains the kind of block if this token is a brace.
382 unsigned BlockKind : 2;
383
384public:
386 return static_cast<BraceBlockKind>(BlockKind);
387 }
388 void setBlockKind(BraceBlockKind BBK) {
389 BlockKind = BBK;
390 assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
391 }
393private:
394 /// Stores the formatting decision for the token once it was made.
395 unsigned Decision : 2;
396
397public:
399 return static_cast<FormatDecision>(Decision);
400 }
402 Decision = D;
403 assert(getDecision() == D && "FormatDecision overflow!");
404 }
406private:
407 /// If this is an opening parenthesis, how are the parameters packed?
408 unsigned PackingKind : 2;
409
410public:
412 return static_cast<ParameterPackingKind>(PackingKind);
413 }
415 PackingKind = K;
416 assert(getPackingKind() == K && "ParameterPackingKind overflow!");
417 }
418
419private:
420 unsigned TypeIsFinalized : 1;
422
423public:
424 /// Returns the token's type, e.g. whether "<" is a template opener or
425 /// binary operator.
426 TokenType getType() const { return Type; }
427 void setType(TokenType T) {
428 // If this token is a macro argument while formatting an unexpanded macro
429 // call, we do not change its type any more - the type was deduced from
430 // formatting the expanded macro stream already.
431 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
432 return;
433 assert((!TypeIsFinalized || T == Type) &&
434 "Please use overwriteFixedType to change a fixed type.");
436 }
437 /// Sets the type and also the finalized flag. This prevents the type to be
438 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
439 /// to another one please use overwriteFixedType, or even better remove the
440 /// need to reassign the type.
442 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
443 return;
444 Type = T;
445 TypeIsFinalized = true;
446 }
448 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
449 return;
450 TypeIsFinalized = false;
451 setType(T);
452 }
453 bool isTypeFinalized() const { return TypeIsFinalized; }
454
455 /// Used to set an operator precedence explicitly.
457
458 /// The number of newlines immediately before the \c Token.
459 ///
460 /// This can be used to determine what the user wrote in the original code
461 /// and thereby e.g. leave an empty line between two function definitions.
462 unsigned NewlinesBefore = 0;
463
464 /// The number of newlines immediately before the \c Token after formatting.
465 ///
466 /// This is used to avoid overlapping whitespace replacements when \c Newlines
467 /// is recomputed for a finalized preprocessor branching directive.
468 int Newlines = -1;
469
470 /// The offset just past the last '\n' in this token's leading
471 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
472 unsigned LastNewlineOffset = 0;
473
474 /// The width of the non-whitespace parts of the token (or its first
475 /// line for multi-line tokens) in columns.
476 /// We need this to correctly measure number of columns a token spans.
477 unsigned ColumnWidth = 0;
479 /// Contains the width in columns of the last line of a multi-line
480 /// token.
482
483 /// The number of spaces that should be inserted before this token.
484 unsigned SpacesRequiredBefore = 0;
486 /// Number of parameters, if this is "(", "[" or "<".
487 unsigned ParameterCount = 0;
488
489 /// Number of parameters that are nested blocks,
490 /// if this is "(", "[" or "<".
491 unsigned BlockParameterCount = 0;
492
493 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
494 /// the surrounding bracket.
495 tok::TokenKind ParentBracket = tok::unknown;
496
497 /// The total length of the unwrapped line up to and including this
498 /// token.
499 unsigned TotalLength = 0;
500
501 /// The original 0-based column of this token, including expanded tabs.
502 /// The configured TabWidth is used as tab width.
503 unsigned OriginalColumn = 0;
504
505 /// The length of following tokens until the next natural split point,
506 /// or the next token that can be broken.
507 unsigned UnbreakableTailLength = 0;
508
509 // FIXME: Come up with a 'cleaner' concept.
510 /// The binding strength of a token. This is a combined value of
511 /// operator precedence, parenthesis nesting, etc.
512 unsigned BindingStrength = 0;
514 /// The nesting level of this token, i.e. the number of surrounding (),
515 /// [], {} or <>.
516 unsigned NestingLevel = 0;
517
518 /// The indent level of this token. Copied from the surrounding line.
519 unsigned IndentLevel = 0;
520
521 /// Penalty for inserting a line break before this token.
522 unsigned SplitPenalty = 0;
524 /// If this is the first ObjC selector name in an ObjC method
525 /// definition or call, this contains the length of the longest name.
526 ///
527 /// This being set to 0 means that the selectors should not be colon-aligned,
528 /// e.g. because several of them are block-type.
529 unsigned LongestObjCSelectorName = 0;
530
531 /// If this is the first ObjC selector name in an ObjC method
532 /// definition or call, this contains the number of parts that the whole
533 /// selector consist of.
534 unsigned ObjCSelectorNameParts = 0;
535
536 /// The 0-based index of the parameter/argument. For ObjC it is set
537 /// for the selector name token.
538 /// For now calculated only for ObjC.
539 unsigned ParameterIndex = 0;
541 /// Stores the number of required fake parentheses and the
542 /// corresponding operator precedence.
543 ///
544 /// If multiple fake parentheses start at a token, this vector stores them in
545 /// reverse order, i.e. inner fake parenthesis first.
547 /// Insert this many fake ) after this token for correct indentation.
548 unsigned FakeRParens = 0;
549
550 /// If this is an operator (or "."/"->") in a sequence of operators
551 /// with the same precedence, contains the 0-based operator index.
552 unsigned OperatorIndex = 0;
554 /// If this is an operator (or "."/"->") in a sequence of operators
555 /// with the same precedence, points to the next operator.
557
558 /// If this is a bracket, this points to the matching one.
560
561 /// The previous token in the unwrapped line.
563
564 /// The next token in the unwrapped line.
565 FormatToken *Next = nullptr;
566
567 /// The first token in set of column elements.
568 bool StartsColumn = false;
569
570 /// This notes the start of the line of an array initializer.
572
573 /// This starts an array initializer.
574 bool IsArrayInitializer = false;
575
576 /// Is optional and can be removed.
577 bool Optional = false;
578
579 /// Might be function declaration open/closing paren.
581
582 /// Number of optional braces to be inserted after this token:
583 /// -1: a single left brace
584 /// 0: no braces
585 /// >0: number of right braces
586 int8_t BraceCount = 0;
587
588 /// If this token starts a block, this contains all the unwrapped lines
589 /// in it.
591
592 // Contains all attributes related to how this token takes part
593 // in a configured macro expansion.
594 std::optional<MacroExpansion> MacroCtx;
595
596 /// When macro expansion introduces nodes with children, those are marked as
597 /// \c MacroParent.
598 /// FIXME: The formatting code currently hard-codes the assumption that
599 /// child nodes are introduced by blocks following an opening brace.
600 /// This is deeply baked into the code and disentangling this will require
601 /// signficant refactorings. \c MacroParent allows us to special-case the
602 /// cases in which we treat parents as block-openers for now.
603 bool MacroParent = false;
605 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
606 bool is(TokenType TT) const { return getType() == TT; }
607 bool is(const IdentifierInfo *II) const {
608 return II && II == Tok.getIdentifierInfo();
610 bool is(tok::PPKeywordKind Kind) const {
613 }
614 bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; }
615 bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; }
616
617 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
618 return is(K1) || is(K2);
619 }
620 template <typename A, typename B, typename... Ts>
621 bool isOneOf(A K1, B K2, Ts... Ks) const {
622 return is(K1) || isOneOf(K2, Ks...);
623 }
624 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
626 bool isIf(bool AllowConstexprMacro = true) const {
627 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
628 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
629 }
630
631 bool closesScopeAfterBlock() const {
632 if (getBlockKind() == BK_Block)
633 return true;
634 if (closesScope())
636 return false;
637 }
638
639 /// \c true if this token starts a sequence with the given tokens in order,
640 /// following the ``Next`` pointers, ignoring comments.
641 template <typename A, typename... Ts>
642 bool startsSequence(A K1, Ts... Tokens) const {
643 return startsSequenceInternal(K1, Tokens...);
644 }
645
646 /// \c true if this token ends a sequence with the given tokens in order,
647 /// following the ``Previous`` pointers, ignoring comments.
648 /// For example, given tokens [T1, T2, T3], the function returns true if
649 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
650 /// words, the tokens passed to this function need to the reverse of the
651 /// order the tokens appear in code.
652 template <typename A, typename... Ts>
653 bool endsSequence(A K1, Ts... Tokens) const {
654 return endsSequenceInternal(K1, Tokens...);
655 }
656
658
659 bool isAttribute() const {
660 return isOneOf(tok::kw___attribute, tok::kw___declspec, TT_AttributeMacro);
662
663 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
664 return Tok.isObjCAtKeyword(Kind);
665 }
666
667 bool isAccessSpecifier(bool ColonRequired = true) const {
668 if (!isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
669 return false;
670 if (!ColonRequired)
671 return true;
672 const auto NextNonComment = getNextNonComment();
673 return NextNonComment && NextNonComment->is(tok::colon);
674 }
675
677 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
678 tok::kw__Nonnull, tok::kw__Nullable,
679 tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64,
680 tok::kw___funcref) ||
681 isAttribute();
682 }
683
684 /// Determine whether the token is a simple-type-specifier.
685 [[nodiscard]] bool isSimpleTypeSpecifier() const;
686
687 [[nodiscard]] bool isTypeName(bool IsCpp) const;
688
689 [[nodiscard]] bool isTypeOrIdentifier(bool IsCpp) const;
690
691 bool isObjCAccessSpecifier() const {
692 return is(tok::at) && Next &&
693 (Next->isObjCAtKeyword(tok::objc_public) ||
694 Next->isObjCAtKeyword(tok::objc_protected) ||
695 Next->isObjCAtKeyword(tok::objc_package) ||
696 Next->isObjCAtKeyword(tok::objc_private));
697 }
698
699 /// Returns whether \p Tok is ([{ or an opening < of a template or in
700 /// protos.
701 bool opensScope() const {
702 if (is(TT_TemplateString) && TokenText.ends_with("${"))
703 return true;
704 if (is(TT_DictLiteral) && is(tok::less))
705 return true;
706 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
707 TT_TemplateOpener);
708 }
709 /// Returns whether \p Tok is )]} or a closing > of a template or in
710 /// protos.
711 bool closesScope() const {
712 if (is(TT_TemplateString) && TokenText.starts_with("}"))
713 return true;
714 if (is(TT_DictLiteral) && is(tok::greater))
715 return true;
716 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
717 TT_TemplateCloser);
718 }
719
720 /// Returns \c true if this is a "." or "->" accessing a member.
721 bool isMemberAccess() const {
722 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
723 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
724 TT_LeadingJavaAnnotation);
726
727 bool isPointerOrReference() const {
728 return isOneOf(tok::star, tok::amp, tok::ampamp);
729 }
730
731 bool isUnaryOperator() const {
732 switch (Tok.getKind()) {
733 case tok::plus:
734 case tok::plusplus:
735 case tok::minus:
736 case tok::minusminus:
737 case tok::exclaim:
738 case tok::tilde:
739 case tok::kw_sizeof:
740 case tok::kw_alignof:
741 return true;
742 default:
743 return false;
744 }
745 }
747 bool isBinaryOperator() const {
748 // Comma is a binary operator, but does not behave as such wrt. formatting.
749 return getPrecedence() > prec::Comma;
750 }
751
752 bool isTrailingComment() const {
753 return is(tok::comment) &&
754 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
755 }
756
757 /// Returns \c true if this is a keyword that can be used
758 /// like a function call (e.g. sizeof, typeid, ...).
759 bool isFunctionLikeKeyword() const {
760 if (isAttribute())
761 return true;
762
763 return isOneOf(tok::kw_throw, tok::kw_typeid, tok::kw_return,
764 tok::kw_sizeof, tok::kw_alignof, tok::kw_alignas,
765 tok::kw_decltype, tok::kw_noexcept, tok::kw_static_assert,
766 tok::kw__Atomic,
767#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
768#include "clang/Basic/TransformTypeTraits.def"
769 tok::kw_requires);
770 }
771
772 /// Returns \c true if this is a string literal that's like a label,
773 /// e.g. ends with "=" or ":".
774 bool isLabelString() const {
775 if (isNot(tok::string_literal))
776 return false;
777 StringRef Content = TokenText;
778 if (Content.starts_with("\"") || Content.starts_with("'"))
779 Content = Content.drop_front(1);
780 if (Content.ends_with("\"") || Content.ends_with("'"))
781 Content = Content.drop_back(1);
782 Content = Content.trim();
783 return Content.size() > 1 &&
784 (Content.back() == ':' || Content.back() == '=');
785 }
787 /// Returns actual token start location without leading escaped
788 /// newlines and whitespace.
789 ///
790 /// This can be different to Tok.getLocation(), which includes leading escaped
791 /// newlines.
793 return WhitespaceRange.getEnd();
794 }
795
796 /// Returns \c true if the range of whitespace immediately preceding the \c
797 /// Token is not empty.
798 bool hasWhitespaceBefore() const {
800 }
801
802 prec::Level getPrecedence() const {
805 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
806 /*CPlusPlus11=*/true);
807 }
808
809 /// Returns the previous token ignoring comments.
810 [[nodiscard]] FormatToken *getPreviousNonComment() const {
812 while (Tok && Tok->is(tok::comment))
813 Tok = Tok->Previous;
814 return Tok;
815 }
816
817 /// Returns the next token ignoring comments.
818 [[nodiscard]] FormatToken *getNextNonComment() const {
820 while (Tok && Tok->is(tok::comment))
821 Tok = Tok->Next;
822 return Tok;
823 }
824
825 /// Returns \c true if this token ends a block indented initializer list.
826 [[nodiscard]] bool isBlockIndentedInitRBrace(const FormatStyle &Style) const;
827
828 /// Returns \c true if this tokens starts a block-type list, i.e. a
829 /// list that should be indented with a block indent.
830 [[nodiscard]] bool opensBlockOrBlockTypeList(const FormatStyle &Style) const;
831
832 /// Returns whether the token is the left square bracket of a C++
833 /// structured binding declaration.
834 bool isCppStructuredBinding(bool IsCpp) const {
835 if (!IsCpp || isNot(tok::l_square))
836 return false;
837 const FormatToken *T = this;
838 do {
839 T = T->getPreviousNonComment();
840 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
841 tok::ampamp));
842 return T && T->is(tok::kw_auto);
843 }
844
845 /// Same as opensBlockOrBlockTypeList, but for the closing token.
846 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
847 if (is(TT_TemplateString) && closesScope())
848 return true;
850 }
851
852 /// Return the actual namespace token, if this token starts a namespace
853 /// block.
854 const FormatToken *getNamespaceToken() const {
855 const FormatToken *NamespaceTok = this;
856 if (is(tok::comment))
857 NamespaceTok = NamespaceTok->getNextNonComment();
858 // Detect "(inline|export)? namespace" in the beginning of a line.
859 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
860 NamespaceTok = NamespaceTok->getNextNonComment();
861 return NamespaceTok &&
862 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
863 ? NamespaceTok
864 : nullptr;
865 }
866
867 void copyFrom(const FormatToken &Tok) { *this = Tok; }
868
869private:
870 // Only allow copying via the explicit copyFrom method.
871 FormatToken(const FormatToken &) = delete;
872 FormatToken &operator=(const FormatToken &) = default;
873
874 template <typename A, typename... Ts>
875 bool startsSequenceInternal(A K1, Ts... Tokens) const {
876 if (is(tok::comment) && Next)
877 return Next->startsSequenceInternal(K1, Tokens...);
878 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
879 }
880
881 template <typename A> bool startsSequenceInternal(A K1) const {
882 if (is(tok::comment) && Next)
883 return Next->startsSequenceInternal(K1);
884 return is(K1);
885 }
886
887 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
888 if (is(tok::comment) && Previous)
889 return Previous->endsSequenceInternal(K1);
890 return is(K1);
891 }
892
893 template <typename A, typename... Ts>
894 bool endsSequenceInternal(A K1, Ts... Tokens) const {
895 if (is(tok::comment) && Previous)
896 return Previous->endsSequenceInternal(K1, Tokens...);
897 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
899};
902struct LineState;
903
904class TokenRole {
905public:
907 virtual ~TokenRole();
908
909 /// After the \c TokenAnnotator has finished annotating all the tokens,
910 /// this function precomputes required information for formatting.
911 virtual void precomputeFormattingInfos(const FormatToken *Token);
912
913 /// Apply the special formatting that the given role demands.
914 ///
915 /// Assumes that the token having this role is already formatted.
916 ///
917 /// Continues formatting from \p State leaving indentation to \p Indenter and
918 /// returns the total penalty that this formatting incurs.
919 virtual unsigned formatFromToken(LineState &State,
921 bool DryRun) {
922 return 0;
923 }
924
925 /// Same as \c formatFromToken, but assumes that the first token has
926 /// already been set thereby deciding on the first line break.
927 virtual unsigned formatAfterToken(LineState &State,
929 bool DryRun) {
930 return 0;
931 }
932
933 /// Notifies the \c Role that a comma was found.
934 virtual void CommaFound(const FormatToken *Token) {}
935
936 virtual const FormatToken *lastComma() { return nullptr; }
937
938protected:
939 const FormatStyle &Style;
940};
941
942class CommaSeparatedList : public TokenRole {
943public:
945 : TokenRole(Style), HasNestedBracedList(false) {}
946
947 void precomputeFormattingInfos(const FormatToken *Token) override;
948
949 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
950 bool DryRun) override;
951
953 bool DryRun) override;
955 /// Adds \p Token as the next comma to the \c CommaSeparated list.
956 void CommaFound(const FormatToken *Token) override {
957 Commas.push_back(Token);
958 }
959
960 const FormatToken *lastComma() override {
961 if (Commas.empty())
962 return nullptr;
963 return Commas.back();
964 }
965
966private:
967 /// A struct that holds information on how to format a given list with
968 /// a specific number of columns.
969 struct ColumnFormat {
970 /// The number of columns to use.
971 unsigned Columns;
972
973 /// The total width in characters.
974 unsigned TotalWidth;
975
976 /// The number of lines required for this format.
977 unsigned LineCount;
978
979 /// The size of each column in characters.
980 SmallVector<unsigned, 8> ColumnSizes;
981 };
982
983 /// Calculate which \c ColumnFormat fits best into
984 /// \p RemainingCharacters.
985 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
986
987 /// The ordered \c FormatTokens making up the commas of this list.
988 SmallVector<const FormatToken *, 8> Commas;
989
990 /// The length of each of the list's items in characters including the
991 /// trailing comma.
992 SmallVector<unsigned, 8> ItemLengths;
993
994 /// Precomputed formats that can be used for this list.
995 SmallVector<ColumnFormat, 4> Formats;
997 bool HasNestedBracedList;
998};
999
1000/// Encapsulates keywords that are context sensitive or for languages not
1001/// properly supported by Clang's lexer.
1002struct AdditionalKeywords {
1003 AdditionalKeywords(IdentifierTable &IdentTable) {
1004 kw_final = &IdentTable.get("final");
1005 kw_override = &IdentTable.get("override");
1006 kw_in = &IdentTable.get("in");
1007 kw_of = &IdentTable.get("of");
1008 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
1009 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
1010 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
1011 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
1012 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
1013 kw_NS_ERROR_ENUM = &IdentTable.get("NS_ERROR_ENUM");
1014 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
1015
1016 kw_as = &IdentTable.get("as");
1017 kw_async = &IdentTable.get("async");
1018 kw_await = &IdentTable.get("await");
1019 kw_declare = &IdentTable.get("declare");
1020 kw_finally = &IdentTable.get("finally");
1021 kw_from = &IdentTable.get("from");
1022 kw_function = &IdentTable.get("function");
1023 kw_get = &IdentTable.get("get");
1024 kw_import = &IdentTable.get("import");
1025 kw_infer = &IdentTable.get("infer");
1026 kw_is = &IdentTable.get("is");
1027 kw_let = &IdentTable.get("let");
1028 kw_module = &IdentTable.get("module");
1029 kw_readonly = &IdentTable.get("readonly");
1030 kw_set = &IdentTable.get("set");
1031 kw_type = &IdentTable.get("type");
1032 kw_typeof = &IdentTable.get("typeof");
1033 kw_var = &IdentTable.get("var");
1034 kw_yield = &IdentTable.get("yield");
1035
1036 kw_abstract = &IdentTable.get("abstract");
1037 kw_assert = &IdentTable.get("assert");
1038 kw_extends = &IdentTable.get("extends");
1039 kw_implements = &IdentTable.get("implements");
1040 kw_instanceof = &IdentTable.get("instanceof");
1041 kw_interface = &IdentTable.get("interface");
1042 kw_native = &IdentTable.get("native");
1043 kw_package = &IdentTable.get("package");
1044 kw_synchronized = &IdentTable.get("synchronized");
1045 kw_throws = &IdentTable.get("throws");
1046 kw___except = &IdentTable.get("__except");
1047 kw___has_include = &IdentTable.get("__has_include");
1048 kw___has_include_next = &IdentTable.get("__has_include_next");
1049
1050 kw_mark = &IdentTable.get("mark");
1051 kw_region = &IdentTable.get("region");
1052
1053 kw_extend = &IdentTable.get("extend");
1054 kw_option = &IdentTable.get("option");
1055 kw_optional = &IdentTable.get("optional");
1056 kw_repeated = &IdentTable.get("repeated");
1057 kw_required = &IdentTable.get("required");
1058 kw_returns = &IdentTable.get("returns");
1059
1060 kw_signals = &IdentTable.get("signals");
1061 kw_qsignals = &IdentTable.get("Q_SIGNALS");
1062 kw_slots = &IdentTable.get("slots");
1063 kw_qslots = &IdentTable.get("Q_SLOTS");
1064
1065 // For internal clang-format use.
1067 &IdentTable.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
1068
1069 // C# keywords
1070 kw_dollar = &IdentTable.get("dollar");
1071 kw_base = &IdentTable.get("base");
1072 kw_byte = &IdentTable.get("byte");
1073 kw_checked = &IdentTable.get("checked");
1074 kw_decimal = &IdentTable.get("decimal");
1075 kw_delegate = &IdentTable.get("delegate");
1076 kw_event = &IdentTable.get("event");
1077 kw_fixed = &IdentTable.get("fixed");
1078 kw_foreach = &IdentTable.get("foreach");
1079 kw_init = &IdentTable.get("init");
1080 kw_implicit = &IdentTable.get("implicit");
1081 kw_internal = &IdentTable.get("internal");
1082 kw_lock = &IdentTable.get("lock");
1083 kw_null = &IdentTable.get("null");
1084 kw_object = &IdentTable.get("object");
1085 kw_out = &IdentTable.get("out");
1086 kw_params = &IdentTable.get("params");
1087 kw_ref = &IdentTable.get("ref");
1088 kw_string = &IdentTable.get("string");
1089 kw_stackalloc = &IdentTable.get("stackalloc");
1090 kw_sbyte = &IdentTable.get("sbyte");
1091 kw_sealed = &IdentTable.get("sealed");
1092 kw_uint = &IdentTable.get("uint");
1093 kw_ulong = &IdentTable.get("ulong");
1094 kw_unchecked = &IdentTable.get("unchecked");
1095 kw_unsafe = &IdentTable.get("unsafe");
1096 kw_ushort = &IdentTable.get("ushort");
1097 kw_when = &IdentTable.get("when");
1098 kw_where = &IdentTable.get("where");
1099
1100 // Verilog keywords
1101 kw_always = &IdentTable.get("always");
1102 kw_always_comb = &IdentTable.get("always_comb");
1103 kw_always_ff = &IdentTable.get("always_ff");
1104 kw_always_latch = &IdentTable.get("always_latch");
1105 kw_assign = &IdentTable.get("assign");
1106 kw_assume = &IdentTable.get("assume");
1107 kw_automatic = &IdentTable.get("automatic");
1108 kw_before = &IdentTable.get("before");
1109 kw_begin = &IdentTable.get("begin");
1110 kw_begin_keywords = &IdentTable.get("begin_keywords");
1111 kw_bins = &IdentTable.get("bins");
1112 kw_binsof = &IdentTable.get("binsof");
1113 kw_casex = &IdentTable.get("casex");
1114 kw_casez = &IdentTable.get("casez");
1115 kw_celldefine = &IdentTable.get("celldefine");
1116 kw_checker = &IdentTable.get("checker");
1117 kw_clocking = &IdentTable.get("clocking");
1118 kw_constraint = &IdentTable.get("constraint");
1119 kw_cover = &IdentTable.get("cover");
1120 kw_covergroup = &IdentTable.get("covergroup");
1121 kw_coverpoint = &IdentTable.get("coverpoint");
1122 kw_default_decay_time = &IdentTable.get("default_decay_time");
1123 kw_default_nettype = &IdentTable.get("default_nettype");
1124 kw_default_trireg_strength = &IdentTable.get("default_trireg_strength");
1125 kw_delay_mode_distributed = &IdentTable.get("delay_mode_distributed");
1126 kw_delay_mode_path = &IdentTable.get("delay_mode_path");
1127 kw_delay_mode_unit = &IdentTable.get("delay_mode_unit");
1128 kw_delay_mode_zero = &IdentTable.get("delay_mode_zero");
1129 kw_disable = &IdentTable.get("disable");
1130 kw_dist = &IdentTable.get("dist");
1131 kw_edge = &IdentTable.get("edge");
1132 kw_elsif = &IdentTable.get("elsif");
1133 kw_end = &IdentTable.get("end");
1134 kw_end_keywords = &IdentTable.get("end_keywords");
1135 kw_endcase = &IdentTable.get("endcase");
1136 kw_endcelldefine = &IdentTable.get("endcelldefine");
1137 kw_endchecker = &IdentTable.get("endchecker");
1138 kw_endclass = &IdentTable.get("endclass");
1139 kw_endclocking = &IdentTable.get("endclocking");
1140 kw_endfunction = &IdentTable.get("endfunction");
1141 kw_endgenerate = &IdentTable.get("endgenerate");
1142 kw_endgroup = &IdentTable.get("endgroup");
1143 kw_endinterface = &IdentTable.get("endinterface");
1144 kw_endmodule = &IdentTable.get("endmodule");
1145 kw_endpackage = &IdentTable.get("endpackage");
1146 kw_endprimitive = &IdentTable.get("endprimitive");
1147 kw_endprogram = &IdentTable.get("endprogram");
1148 kw_endproperty = &IdentTable.get("endproperty");
1149 kw_endsequence = &IdentTable.get("endsequence");
1150 kw_endspecify = &IdentTable.get("endspecify");
1151 kw_endtable = &IdentTable.get("endtable");
1152 kw_endtask = &IdentTable.get("endtask");
1153 kw_forever = &IdentTable.get("forever");
1154 kw_fork = &IdentTable.get("fork");
1155 kw_generate = &IdentTable.get("generate");
1156 kw_highz0 = &IdentTable.get("highz0");
1157 kw_highz1 = &IdentTable.get("highz1");
1158 kw_iff = &IdentTable.get("iff");
1159 kw_ifnone = &IdentTable.get("ifnone");
1160 kw_ignore_bins = &IdentTable.get("ignore_bins");
1161 kw_illegal_bins = &IdentTable.get("illegal_bins");
1162 kw_initial = &IdentTable.get("initial");
1163 kw_inout = &IdentTable.get("inout");
1164 kw_input = &IdentTable.get("input");
1165 kw_inside = &IdentTable.get("inside");
1166 kw_interconnect = &IdentTable.get("interconnect");
1167 kw_intersect = &IdentTable.get("intersect");
1168 kw_join = &IdentTable.get("join");
1169 kw_join_any = &IdentTable.get("join_any");
1170 kw_join_none = &IdentTable.get("join_none");
1171 kw_large = &IdentTable.get("large");
1172 kw_local = &IdentTable.get("local");
1173 kw_localparam = &IdentTable.get("localparam");
1174 kw_macromodule = &IdentTable.get("macromodule");
1175 kw_matches = &IdentTable.get("matches");
1176 kw_medium = &IdentTable.get("medium");
1177 kw_negedge = &IdentTable.get("negedge");
1178 kw_nounconnected_drive = &IdentTable.get("nounconnected_drive");
1179 kw_output = &IdentTable.get("output");
1180 kw_packed = &IdentTable.get("packed");
1181 kw_parameter = &IdentTable.get("parameter");
1182 kw_posedge = &IdentTable.get("posedge");
1183 kw_primitive = &IdentTable.get("primitive");
1184 kw_priority = &IdentTable.get("priority");
1185 kw_program = &IdentTable.get("program");
1186 kw_property = &IdentTable.get("property");
1187 kw_pull0 = &IdentTable.get("pull0");
1188 kw_pull1 = &IdentTable.get("pull1");
1189 kw_pure = &IdentTable.get("pure");
1190 kw_rand = &IdentTable.get("rand");
1191 kw_randc = &IdentTable.get("randc");
1192 kw_randcase = &IdentTable.get("randcase");
1193 kw_randsequence = &IdentTable.get("randsequence");
1194 kw_repeat = &IdentTable.get("repeat");
1195 kw_resetall = &IdentTable.get("resetall");
1196 kw_sample = &IdentTable.get("sample");
1197 kw_scalared = &IdentTable.get("scalared");
1198 kw_sequence = &IdentTable.get("sequence");
1199 kw_small = &IdentTable.get("small");
1200 kw_soft = &IdentTable.get("soft");
1201 kw_solve = &IdentTable.get("solve");
1202 kw_specify = &IdentTable.get("specify");
1203 kw_specparam = &IdentTable.get("specparam");
1204 kw_strong0 = &IdentTable.get("strong0");
1205 kw_strong1 = &IdentTable.get("strong1");
1206 kw_supply0 = &IdentTable.get("supply0");
1207 kw_supply1 = &IdentTable.get("supply1");
1208 kw_table = &IdentTable.get("table");
1209 kw_tagged = &IdentTable.get("tagged");
1210 kw_task = &IdentTable.get("task");
1211 kw_timescale = &IdentTable.get("timescale");
1212 kw_tri = &IdentTable.get("tri");
1213 kw_tri0 = &IdentTable.get("tri0");
1214 kw_tri1 = &IdentTable.get("tri1");
1215 kw_triand = &IdentTable.get("triand");
1216 kw_trior = &IdentTable.get("trior");
1217 kw_trireg = &IdentTable.get("trireg");
1218 kw_unconnected_drive = &IdentTable.get("unconnected_drive");
1219 kw_undefineall = &IdentTable.get("undefineall");
1220 kw_unique = &IdentTable.get("unique");
1221 kw_unique0 = &IdentTable.get("unique0");
1222 kw_uwire = &IdentTable.get("uwire");
1223 kw_vectored = &IdentTable.get("vectored");
1224 kw_wand = &IdentTable.get("wand");
1225 kw_weak0 = &IdentTable.get("weak0");
1226 kw_weak1 = &IdentTable.get("weak1");
1227 kw_wildcard = &IdentTable.get("wildcard");
1228 kw_wire = &IdentTable.get("wire");
1229 kw_with = &IdentTable.get("with");
1230 kw_wor = &IdentTable.get("wor");
1231
1232 // Symbols that are treated as keywords.
1233 kw_verilogHash = &IdentTable.get("#");
1234 kw_verilogHashHash = &IdentTable.get("##");
1235 kw_apostrophe = &IdentTable.get("\'");
1236
1237 // TableGen keywords
1238 kw_bit = &IdentTable.get("bit");
1239 kw_bits = &IdentTable.get("bits");
1240 kw_code = &IdentTable.get("code");
1241 kw_dag = &IdentTable.get("dag");
1242 kw_def = &IdentTable.get("def");
1243 kw_defm = &IdentTable.get("defm");
1244 kw_defset = &IdentTable.get("defset");
1245 kw_defvar = &IdentTable.get("defvar");
1246 kw_dump = &IdentTable.get("dump");
1247 kw_include = &IdentTable.get("include");
1248 kw_list = &IdentTable.get("list");
1249 kw_multiclass = &IdentTable.get("multiclass");
1250 kw_then = &IdentTable.get("then");
1251
1252 // Keep this at the end of the constructor to make sure everything here
1253 // is
1254 // already initialized.
1255 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
1259 // Keywords from the Java section.
1261
1262 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
1269 // Keywords from the JavaScript section.
1273 // Keywords from the Java section.
1275
1276 // Some keywords are not included here because they don't need special
1277 // treatment like `showcancelled` or they should be treated as identifiers
1278 // like `int` and `logic`.
1279 VerilogExtraKeywords = std::unordered_set<IdentifierInfo *>(
1334 kw_tri, kw_tri0,
1342 kw_with, kw_wor,
1344
1345 TableGenExtraKeywords = std::unordered_set<IdentifierInfo *>({
1346 kw_assert,
1347 kw_bit,
1348 kw_bits,
1349 kw_code,
1350 kw_dag,
1351 kw_def,
1352 kw_defm,
1353 kw_defset,
1354 kw_defvar,
1355 kw_dump,
1356 kw_foreach,
1357 kw_in,
1358 kw_include,
1359 kw_let,
1360 kw_list,
1364 });
1367 // Context sensitive keywords.
1383 // JavaScript keywords.
1404 // Java keywords.
1416 // Pragma keywords.
1420 // Proto keywords.
1427
1428 // QT keywords.
1434 // For internal use by clang-format.
1437 // C# keywords
1471 // Verilog keywords
1603 // Workaround for hashes and backticks in Verilog.
1607 // Symbols in Verilog that don't exist in C++.
1610 // TableGen keywords
1624
1625 /// Returns \c true if \p Tok is a keyword or an identifier.
1626 bool isWordLike(const FormatToken &Tok) const {
1627 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1628 return Tok.Tok.getIdentifierInfo() &&
1630 }
1632 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1633 /// \c false if it is a keyword or a pseudo keyword.
1634 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1635 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1636 // ``yield``.
1637 bool IsJavaScriptIdentifier(const FormatToken &Tok,
1638 bool AcceptIdentifierName = true) const {
1639 // Based on the list of JavaScript & TypeScript keywords here:
1640 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1641 switch (Tok.Tok.getKind()) {
1642 case tok::kw_break:
1643 case tok::kw_case:
1644 case tok::kw_catch:
1645 case tok::kw_class:
1646 case tok::kw_continue:
1647 case tok::kw_const:
1648 case tok::kw_default:
1649 case tok::kw_delete:
1650 case tok::kw_do:
1651 case tok::kw_else:
1652 case tok::kw_enum:
1653 case tok::kw_export:
1654 case tok::kw_false:
1655 case tok::kw_for:
1656 case tok::kw_if:
1657 case tok::kw_import:
1658 case tok::kw_module:
1659 case tok::kw_new:
1660 case tok::kw_private:
1661 case tok::kw_protected:
1662 case tok::kw_public:
1663 case tok::kw_return:
1664 case tok::kw_static:
1665 case tok::kw_switch:
1666 case tok::kw_this:
1667 case tok::kw_throw:
1668 case tok::kw_true:
1669 case tok::kw_try:
1670 case tok::kw_typeof:
1671 case tok::kw_void:
1672 case tok::kw_while:
1673 // These are JS keywords that are lexed by LLVM/clang as keywords.
1674 return false;
1675 case tok::identifier: {
1676 // For identifiers, make sure they are true identifiers, excluding the
1677 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1678 bool IsPseudoKeyword =
1679 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1680 JsExtraKeywords.end();
1681 return AcceptIdentifierName || !IsPseudoKeyword;
1682 }
1683 default:
1684 // Other keywords are handled in the switch below, to avoid problems due
1685 // to duplicate case labels when using the #include trick.
1686 break;
1687 }
1688
1689 switch (Tok.Tok.getKind()) {
1690 // Handle C++ keywords not included above: these are all JS identifiers.
1691#define KEYWORD(X, Y) case tok::kw_##X:
1692#include "clang/Basic/TokenKinds.def"
1693 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1694 // TokenKinds.def
1695 return true;
1696 default:
1697 // All other tokens (punctuation etc) are not JS identifiers.
1698 return false;
1699 }
1700 }
1701
1702 /// Returns \c true if \p Tok is a C# keyword, returns
1703 /// \c false if it is a anything else.
1704 bool isCSharpKeyword(const FormatToken &Tok) const {
1705 switch (Tok.Tok.getKind()) {
1706 case tok::kw_bool:
1707 case tok::kw_break:
1708 case tok::kw_case:
1709 case tok::kw_catch:
1710 case tok::kw_char:
1711 case tok::kw_class:
1712 case tok::kw_const:
1713 case tok::kw_continue:
1714 case tok::kw_default:
1715 case tok::kw_do:
1716 case tok::kw_double:
1717 case tok::kw_else:
1718 case tok::kw_enum:
1719 case tok::kw_explicit:
1720 case tok::kw_extern:
1721 case tok::kw_false:
1722 case tok::kw_float:
1723 case tok::kw_for:
1724 case tok::kw_goto:
1725 case tok::kw_if:
1726 case tok::kw_int:
1727 case tok::kw_long:
1728 case tok::kw_namespace:
1729 case tok::kw_new:
1730 case tok::kw_operator:
1731 case tok::kw_private:
1732 case tok::kw_protected:
1733 case tok::kw_public:
1734 case tok::kw_return:
1735 case tok::kw_short:
1736 case tok::kw_sizeof:
1737 case tok::kw_static:
1738 case tok::kw_struct:
1739 case tok::kw_switch:
1740 case tok::kw_this:
1741 case tok::kw_throw:
1742 case tok::kw_true:
1743 case tok::kw_try:
1744 case tok::kw_typeof:
1745 case tok::kw_using:
1746 case tok::kw_virtual:
1747 case tok::kw_void:
1748 case tok::kw_volatile:
1749 case tok::kw_while:
1750 return true;
1751 default:
1752 return Tok.is(tok::identifier) &&
1753 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1754 CSharpExtraKeywords.end();
1755 }
1756 }
1758 bool isVerilogWordOperator(const FormatToken &Tok) const {
1760 kw_with);
1761 }
1762
1763 bool isVerilogIdentifier(const FormatToken &Tok) const {
1764 switch (Tok.Tok.getKind()) {
1765 case tok::kw_case:
1766 case tok::kw_class:
1767 case tok::kw_const:
1768 case tok::kw_continue:
1769 case tok::kw_default:
1770 case tok::kw_do:
1771 case tok::kw_extern:
1772 case tok::kw_else:
1773 case tok::kw_enum:
1774 case tok::kw_for:
1775 case tok::kw_if:
1776 case tok::kw_restrict:
1777 case tok::kw_signed:
1778 case tok::kw_static:
1779 case tok::kw_struct:
1780 case tok::kw_typedef:
1781 case tok::kw_union:
1782 case tok::kw_unsigned:
1783 case tok::kw_virtual:
1784 case tok::kw_while:
1785 return false;
1786 case tok::identifier:
1787 return isWordLike(Tok) &&
1788 VerilogExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1789 VerilogExtraKeywords.end();
1790 default:
1791 // getIdentifierInfo returns non-null for both identifiers and keywords.
1792 return Tok.Tok.getIdentifierInfo();
1794 }
1795
1796 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1797 /// needed because macro expansions start with a backtick as well and they
1798 /// need to be treated differently.
1799 bool isVerilogPPDirective(const FormatToken &Tok) const {
1800 auto Info = Tok.Tok.getIdentifierInfo();
1801 if (!Info)
1802 return false;
1803 switch (Info->getPPKeywordID()) {
1804 case tok::pp_define:
1805 case tok::pp_else:
1806 case tok::pp_endif:
1807 case tok::pp_ifdef:
1808 case tok::pp_ifndef:
1809 case tok::pp_include:
1810 case tok::pp_line:
1811 case tok::pp_pragma:
1812 case tok::pp_undef:
1813 return true;
1814 default:
1815 return Tok.isOneOf(kw_begin_keywords, kw_celldefine,
1822 }
1823 }
1824
1825 /// Returns whether \p Tok is a Verilog keyword that opens a block.
1826 bool isVerilogBegin(const FormatToken &Tok) const {
1827 // `table` is not included since it needs to be treated specially.
1828 return !Tok.endsSequence(kw_fork, kw_disable) &&
1829 Tok.isOneOf(kw_begin, kw_fork, kw_generate, kw_specify);
1830 }
1831
1832 /// Returns whether \p Tok is a Verilog keyword that closes a block.
1833 bool isVerilogEnd(const FormatToken &Tok) const {
1834 return !Tok.endsSequence(kw_join, kw_rand) &&
1835 Tok.isOneOf(TT_MacroBlockEnd, kw_end, kw_endcase, kw_endclass,
1842 }
1843
1844 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
1845 bool isVerilogHierarchy(const FormatToken &Tok) const {
1847 return false;
1848 if (Tok.is(kw_property)) {
1849 const FormatToken *Prev = Tok.getPreviousNonComment();
1850 return !(Prev &&
1851 Prev->isOneOf(tok::kw_restrict, kw_assert, kw_assume, kw_cover));
1852 }
1853 return Tok.isOneOf(tok::kw_case, tok::kw_class, kw_function, kw_module,
1857 kw_task);
1858 }
1859
1860 bool isVerilogEndOfLabel(const FormatToken &Tok) const {
1861 const FormatToken *Next = Tok.getNextNonComment();
1862 // In Verilog the colon in a default label is optional.
1863 return Tok.is(TT_CaseLabelColon) ||
1864 (Tok.is(tok::kw_default) &&
1865 !(Next && Next->isOneOf(tok::colon, tok::semi, kw_clocking, kw_iff,
1867 }
1868
1869 /// Returns whether \p Tok is a Verilog keyword that starts a
1870 /// structured procedure like 'always'.
1871 bool isVerilogStructuredProcedure(const FormatToken &Tok) const {
1874 }
1875
1876 bool isVerilogQualifier(const FormatToken &Tok) const {
1877 switch (Tok.Tok.getKind()) {
1878 case tok::kw_extern:
1879 case tok::kw_signed:
1880 case tok::kw_static:
1881 case tok::kw_unsigned:
1882 case tok::kw_virtual:
1883 return true;
1884 case tok::identifier:
1885 return Tok.isOneOf(
1892 default:
1893 return false;
1894 }
1895 }
1897 bool isTableGenDefinition(const FormatToken &Tok) const {
1899 kw_let, tok::kw_class);
1900 }
1901
1902 bool isTableGenKeyword(const FormatToken &Tok) const {
1903 switch (Tok.Tok.getKind()) {
1904 case tok::kw_class:
1905 case tok::kw_else:
1906 case tok::kw_false:
1907 case tok::kw_if:
1908 case tok::kw_int:
1909 case tok::kw_true:
1910 return true;
1911 default:
1912 return Tok.is(tok::identifier) &&
1913 TableGenExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1914 TableGenExtraKeywords.end();
1915 }
1916 }
1917
1918private:
1919 /// The JavaScript keywords beyond the C++ keyword set.
1920 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
1921
1922 /// The C# keywords beyond the C++ keyword set
1923 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
1924
1925 /// The Verilog keywords beyond the C++ keyword set.
1926 std::unordered_set<IdentifierInfo *> VerilogExtraKeywords;
1927
1928 /// The TableGen keywords beyond the C++ keyword set.
1929 std::unordered_set<IdentifierInfo *> TableGenExtraKeywords;
1930};
1931
1932inline bool isLineComment(const FormatToken &FormatTok) {
1933 return FormatTok.is(tok::comment) && !FormatTok.TokenText.starts_with("/*");
1934}
1935
1936// Checks if \p FormatTok is a line comment that continues the line comment
1937// \p Previous. The original column of \p MinColumnToken is used to determine
1938// whether \p FormatTok is indented enough to the right to continue \p Previous.
1939inline bool continuesLineComment(const FormatToken &FormatTok,
1940 const FormatToken *Previous,
1941 const FormatToken *MinColumnToken) {
1942 if (!Previous || !MinColumnToken)
1943 return false;
1944 unsigned MinContinueColumn =
1945 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
1946 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
1948 FormatTok.OriginalColumn >= MinContinueColumn;
1949}
1950
1951} // namespace format
1952} // namespace clang
1953
1954#endif
#define LIST_TOKEN_TYPES
Definition: FormatToken.h:27
Various functions to configurably format source code.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines and computes precedence levels for binary/ternary operators.
static constexpr bool isOneOf()
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, _)
Definition: Type.h:5465
StateNode * Previous
ContinuationIndenter * Indenter
One of these records is kept for each identifier that is lexed.
tok::PPKeywordKind getPPKeywordID() const
Return the preprocessor keyword ID for this identifier.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
tok::TokenKind getKind() const
Definition: Token.h:94
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:61
The base class of the type hierarchy.
Definition: Type.h:1813
unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Apply the special formatting that the given role demands.
void CommaFound(const FormatToken *Token) override
Adds Token as the next comma to the CommaSeparated list.
Definition: FormatToken.h:950
const FormatToken * lastComma() override
Definition: FormatToken.h:954
unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
void precomputeFormattingInfos(const FormatToken *Token) override
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
virtual unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
Definition: FormatToken.h:921
virtual void precomputeFormattingInfos(const FormatToken *Token)
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
const FormatStyle & Style
Definition: FormatToken.h:933
virtual void CommaFound(const FormatToken *Token)
Notifies the Role that a comma was found.
Definition: FormatToken.h:928
virtual const FormatToken * lastComma()
Definition: FormatToken.h:930
virtual unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Apply the special formatting that the given role demands.
Definition: FormatToken.h:913
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
Definition: FormatToken.cpp:24
MacroRole
Roles a token can take in a configured macro expansion.
Definition: FormatToken.h:221
@ MR_UnexpandedArg
The token is part of a macro argument that was previously formatted as expansion when formatting the ...
Definition: FormatToken.h:227
@ MR_Hidden
The token was expanded from a macro definition, and is not visible as part of the macro call.
Definition: FormatToken.h:230
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
Definition: FormatToken.h:224
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
Definition: FormatToken.h:1933
bool isLineComment(const FormatToken &FormatTok)
Definition: FormatToken.h:1926
TokenType
Determines the semantic type of a syntactic token, e.g.
Definition: FormatToken.h:202
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition: TokenKinds.h:33
The JSON file list parser is used to communicate input to InstallAPI.
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
const FunctionProtoType * T
#define false
Definition: stdbool.h:22
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:996
bool isVerilogEnd(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that closes a block.
Definition: FormatToken.h:1827
IdentifierInfo * kw_nounconnected_drive
Definition: FormatToken.h:1543
bool isVerilogBegin(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a block.
Definition: FormatToken.h:1820
bool isVerilogQualifier(const FormatToken &Tok) const
Definition: FormatToken.h:1870
bool isWordLike(const FormatToken &Tok) const
Returns true if Tok is a keyword or an identifier.
Definition: FormatToken.h:1620
IdentifierInfo * kw_default_trireg_strength
Definition: FormatToken.h:1489
bool isVerilogStructuredProcedure(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that starts a structured procedure like 'always'.
Definition: FormatToken.h:1865
bool isVerilogEndOfLabel(const FormatToken &Tok) const
Definition: FormatToken.h:1854
bool isVerilogWordOperator(const FormatToken &Tok) const
Definition: FormatToken.h:1752
IdentifierInfo * kw_delay_mode_distributed
Definition: FormatToken.h:1490
bool IsJavaScriptIdentifier(const FormatToken &Tok, bool AcceptIdentifierName=true) const
Returns true if Tok is a true JavaScript identifier, returns false if it is a keyword or a pseudo key...
Definition: FormatToken.h:1631
bool isTableGenKeyword(const FormatToken &Tok) const
Definition: FormatToken.h:1896
IdentifierInfo * kw_default_decay_time
Definition: FormatToken.h:1487
bool isCSharpKeyword(const FormatToken &Tok) const
Returns true if Tok is a C# keyword, returns false if it is a anything else.
Definition: FormatToken.h:1698
IdentifierInfo * kw___has_include_next
Definition: FormatToken.h:1375
bool isVerilogHierarchy(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a module, etc.
Definition: FormatToken.h:1839
bool isVerilogPPDirective(const FormatToken &Tok) const
Returns whether Tok is a Verilog preprocessor directive.
Definition: FormatToken.h:1793
IdentifierInfo * kw_unconnected_drive
Definition: FormatToken.h:1583
IdentifierInfo * kw_internal_ident_after_define
Definition: FormatToken.h:1429
bool isTableGenDefinition(const FormatToken &Tok) const
Definition: FormatToken.h:1891
bool isVerilogIdentifier(const FormatToken &Tok) const
Definition: FormatToken.h:1757
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:287
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:510
unsigned MustBreakBeforeFinalized
Whether MustBreakBefore is finalized during parsing and must not be reset between runs.
Definition: FormatToken.h:336
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:715
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
Definition: FormatToken.h:542
bool ArrayInitializerLineStart
This notes the start of the line of an array initializer.
Definition: FormatToken.h:565
bool isTypeFinalized() const
Definition: FormatToken.h:447
bool Optional
Is optional and can be removed.
Definition: FormatToken.h:571
bool MacroParent
When macro expansion introduces nodes with children, those are marked as MacroParent.
Definition: FormatToken.h:597
int Newlines
The number of newlines immediately before the Token after formatting.
Definition: FormatToken.h:462
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:584
bool closesScopeAfterBlock() const
Definition: FormatToken.h:625
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:657
prec::Level ForcedPrecedence
Used to set an operator precedence explicitly.
Definition: FormatToken.h:450
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const
Same as opensBlockOrBlockTypeList, but for the closing token.
Definition: FormatToken.h:840
unsigned BindingStrength
The binding strength of a token.
Definition: FormatToken.h:506
bool isObjCAccessSpecifier() const
Definition: FormatToken.h:685
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
Definition: FormatToken.h:848
unsigned StartsBinaryExpression
true if this token starts a binary expression, i.e.
Definition: FormatToken.h:349
void setPackingKind(ParameterPackingKind K)
Definition: FormatToken.h:408
unsigned ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
Definition: FormatToken.h:345
unsigned OperatorIndex
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:546
bool MightBeFunctionDeclParen
Might be function declaration open/closing paren.
Definition: FormatToken.h:574
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:497
unsigned ContinuesLineCommentSection
Does this line comment continue a line comment section?
Definition: FormatToken.h:361
unsigned CanBreakBefore
true if it is allowed to break before this token.
Definition: FormatToken.h:342
bool isNot(T Kind) const
Definition: FormatToken.h:618
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:307
unsigned LongestObjCSelectorName
If this is the first ObjC selector name in an ObjC method definition or call, this contains the lengt...
Definition: FormatToken.h:523
ParameterPackingKind getPackingKind() const
Definition: FormatToken.h:405
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:786
bool startsSequence(A K1, Ts... Tokens) const
true if this token starts a sequence with the given tokens in order, following the Next pointers,...
Definition: FormatToken.h:636
tok::TokenKind ParentBracket
If this is a bracket ("<", "(", "[" or "{"), contains the kind of the surrounding bracket.
Definition: FormatToken.h:489
unsigned LastNewlineOffset
The offset just past the last ' ' in this token's leading whitespace (relative to WhiteSpaceStart).
Definition: FormatToken.h:466
unsigned SplitPenalty
Penalty for inserting a line break before this token.
Definition: FormatToken.h:516
bool opensScope() const
Returns whether Tok is ([{ or an opening < of a template or in protos.
Definition: FormatToken.h:695
bool isPointerOrReference() const
Definition: FormatToken.h:721
FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:812
void setDecision(FormatDecision D)
Definition: FormatToken.h:395
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:804
bool isSimpleTypeSpecifier() const
Determine whether the token is a simple-type-specifier.
Definition: FormatToken.cpp:39
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
Definition: FormatToken.h:540
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
Definition: FormatToken.h:366
std::optional< MacroExpansion > MacroCtx
Definition: FormatToken.h:588
BraceBlockKind getBlockKind() const
Definition: FormatToken.h:379
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:559
unsigned IsMultiline
Whether the token text contains newlines (escaped or not).
Definition: FormatToken.h:323
unsigned EndsCppAttributeGroup
true if this token ends a group of C++ attributes.
Definition: FormatToken.h:372
bool isTypeOrIdentifier(bool IsCpp) const
Definition: FormatToken.cpp:88
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:456
bool isTypeName(bool IsCpp) const
Definition: FormatToken.cpp:81
void setBlockKind(BraceBlockKind BBK)
Definition: FormatToken.h:382
bool isIf(bool AllowConstexprMacro=true) const
Definition: FormatToken.h:620
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:478
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Definition: FormatToken.h:313
unsigned MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:332
unsigned HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
Definition: FormatToken.h:320
unsigned PartOfMultiVariableDeclStmt
Is this token part of a DeclStmt defining multiple variables?
Definition: FormatToken.h:356
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Definition: FormatToken.h:471
unsigned ObjCSelectorNameParts
If this is the first ObjC selector name in an ObjC method definition or call, this contains the numbe...
Definition: FormatToken.h:528
void setType(TokenType T)
Definition: FormatToken.h:421
bool isFunctionLikeKeyword() const
Returns true if this is a keyword that can be used like a function call (e.g.
Definition: FormatToken.h:753
bool isStringLiteral() const
Definition: FormatToken.h:651
bool IsArrayInitializer
This starts an array initializer.
Definition: FormatToken.h:568
bool isBlockIndentedInitRBrace(const FormatStyle &Style) const
Returns true if this token ends a block indented initializer list.
Definition: FormatToken.cpp:92
bool closesScope() const
Returns whether Tok is )]} or a closing > of a template or in protos.
Definition: FormatToken.h:705
unsigned EndsBinaryExpression
true if this token ends a binary expression.
Definition: FormatToken.h:351
bool isBinaryOperator() const
Definition: FormatToken.h:741
bool isCppStructuredBinding(bool IsCpp) const
Returns whether the token is the left square bracket of a C++ structured binding declaration.
Definition: FormatToken.h:828
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
Definition: FormatToken.h:501
prec::Level getPrecedence() const
Definition: FormatToken.h:796
FormatDecision getDecision() const
Definition: FormatToken.h:392
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:599
unsigned LastLineColumnWidth
Contains the width in columns of the last line of a multi-line token.
Definition: FormatToken.h:475
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
Definition: FormatToken.h:513
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e.
unsigned BlockParameterCount
Number of parameters that are nested blocks, if this is "(", "[" or "<".
Definition: FormatToken.h:485
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:493
bool hasWhitespaceBefore() const
Returns true if the range of whitespace immediately preceding the Token is not empty.
Definition: FormatToken.h:792
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:611
TokenType getType() const
Returns the token's type, e.g.
Definition: FormatToken.h:420
unsigned IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:326
bool isUnaryOperator() const
Definition: FormatToken.h:725
unsigned IsUnterminatedLiteral
Set to true if this token is an unterminated literal.
Definition: FormatToken.h:339
bool isTrailingComment() const
Definition: FormatToken.h:746
unsigned ClosesRequiresClause
true if this is the last token within requires clause.
Definition: FormatToken.h:369
unsigned ParameterIndex
The 0-based index of the parameter/argument.
Definition: FormatToken.h:533
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Definition: FormatToken.h:580
bool canBePointerOrReferenceQualifier() const
Definition: FormatToken.h:670
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
Definition: FormatToken.h:481
bool isAccessSpecifier(bool ColonRequired=true) const
Definition: FormatToken.h:661
bool StartsColumn
The first token in set of column elements.
Definition: FormatToken.h:562
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:316
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:550
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:553
void copyFrom(const FormatToken &Tok)
Definition: FormatToken.h:861
void overwriteFixedType(TokenType T)
Definition: FormatToken.h:441
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:556
bool isLabelString() const
Returns true if this is a string literal that's like a label, e.g.
Definition: FormatToken.h:768
bool endsSequence(A K1, Ts... Tokens) const
true if this token ends a sequence with the given tokens in order, following the Previous pointers,...
Definition: FormatToken.h:647
void setFinalizedType(TokenType T)
Sets the type and also the finalized flag.
Definition: FormatToken.h:435
The current state when indenting a unwrapped line.
Contains information on the token's role in a macro expansion.
Definition: FormatToken.h:260
llvm::SmallVector< FormatToken *, 1 > ExpandedFrom
The stack of macro call identifier tokens this token was expanded from.
Definition: FormatToken.h:272
unsigned StartOfExpansion
The number of expansions of which this macro is the first entry.
Definition: FormatToken.h:275
MacroRole Role
The token's role in the macro expansion.
Definition: FormatToken.h:269
unsigned EndOfExpansion
The number of currently open expansions in ExpandedFrom this macro is the last token in.
Definition: FormatToken.h:279