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