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