clang 24.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(AfterPPDirective) \
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeColon) \
32 TYPE(AttributeLParen) \
33 TYPE(AttributeLSquare) \
34 TYPE(AttributeMacro) \
35 TYPE(AttributeRParen) \
36 TYPE(AttributeRSquare) \
37 TYPE(BinaryOperator) \
38 TYPE(BitFieldColon) \
39 TYPE(BlockComment) \
40 /* l_brace of a block that is not the body of a (e.g. loop) statement. */ \
41 TYPE(BlockLBrace) \
42 TYPE(BracedListLBrace) \
43 TYPE(CaseLabelArrow) \
44 /* The colon at the end of a case label. */ \
45 TYPE(CaseLabelColon) \
46 TYPE(CastRParen) \
47 TYPE(ClassLBrace) \
48 /* Name of class/struct/union/interface definition. */ \
49 TYPE(ClassHeadName) \
50 TYPE(ClassRBrace) \
51 TYPE(CompoundRequirementLBrace) \
52 /* ternary ?: expression */ \
53 TYPE(ConditionalExpr) \
54 /* the condition in an if statement */ \
55 TYPE(ConditionLParen) \
56 TYPE(ConflictAlternative) \
57 TYPE(ConflictEnd) \
58 TYPE(ConflictStart) \
59 /* l_brace of if/for/while/switch/catch */ \
60 TYPE(ControlStatementLBrace) \
61 TYPE(ControlStatementRBrace) \
62 TYPE(CppCastLParen) \
63 TYPE(CSharpGenericTypeConstraint) \
64 TYPE(CSharpGenericTypeConstraintColon) \
65 TYPE(CSharpGenericTypeConstraintComma) \
66 TYPE(CSharpNamedArgumentColon) \
67 TYPE(CSharpNullable) \
68 TYPE(CSharpNullConditionalLSquare) \
69 TYPE(CSharpStringLiteral) \
70 TYPE(CtorInitializerColon) \
71 TYPE(CtorInitializerComma) \
72 TYPE(CtorDtorDeclName) \
73 TYPE(DesignatedInitializerLSquare) \
74 TYPE(DesignatedInitializerPeriod) \
75 TYPE(DictLiteral) \
76 TYPE(DoWhile) \
77 TYPE(ElseLBrace) \
78 TYPE(ElseRBrace) \
79 TYPE(EnumEqual) \
80 TYPE(EnumLBrace) \
81 TYPE(EnumRBrace) \
82 TYPE(EnumUnderlyingTypeColon) \
83 TYPE(ExportLBrace) \
84 TYPE(FatArrow) \
85 TYPE(ForEachMacro) \
86 TYPE(FunctionAnnotationRParen) \
87 TYPE(FunctionDeclarationName) \
88 TYPE(FunctionDeclarationLParen) \
89 TYPE(FunctionLBrace) \
90 TYPE(FunctionLikeMacro) \
91 TYPE(FunctionLikeOrFreestandingMacro) \
92 TYPE(FunctionTypeLParen) \
93 /* The colons as part of a C11 _Generic selection */ \
94 TYPE(GenericSelectionColon) \
95 /* The colon at the end of a goto label. */ \
96 TYPE(GotoLabelColon) \
97 TYPE(IfMacro) \
98 TYPE(ImplicitStringLiteral) \
99 TYPE(InheritanceColon) \
100 TYPE(InheritanceComma) \
101 TYPE(InlineASMBrace) \
102 TYPE(InlineASMColon) \
103 TYPE(InlineASMParen) \
104 TYPE(InlineASMSymbolicNameLSquare) \
105 TYPE(JavaAnnotation) \
106 TYPE(JsAndAndEqual) \
107 TYPE(JsComputedPropertyName) \
108 TYPE(JsExponentiation) \
109 TYPE(JsExponentiationEqual) \
110 TYPE(JsPipePipeEqual) \
111 TYPE(JsPrivateIdentifier) \
112 TYPE(JsTypeColon) \
113 TYPE(JsTypeOperator) \
114 TYPE(JsTypeOptionalQuestion) \
115 TYPE(LambdaArrow) \
116 TYPE(LambdaDefinitionLParen) \
117 TYPE(LambdaLBrace) \
118 TYPE(LambdaLSquare) \
119 TYPE(LeadingJavaAnnotation) \
120 TYPE(LineComment) \
121 TYPE(MacroBlockBegin) \
122 TYPE(MacroBlockEnd) \
123 TYPE(ModulePartitionColon) \
124 TYPE(NamespaceLBrace) \
125 TYPE(NamespaceMacro) \
126 TYPE(NamespaceRBrace) \
127 TYPE(NonNullAssertion) \
128 TYPE(NullCoalescingEqual) \
129 TYPE(NullCoalescingOperator) \
130 TYPE(NullPropagatingOperator) \
131 TYPE(ObjCBlockLBrace) \
132 TYPE(ObjCBlockLParen) \
133 TYPE(ObjCDecl) \
134 TYPE(ObjCForIn) \
135 /* The square brackets surrounding a method call, the colon separating the \
136 * method or parameter name and the argument inside the square brackets, and \
137 * the colon separating the method or parameter name and the type inside the \
138 * method declaration. */ \
139 TYPE(ObjCMethodExpr) \
140 /* The '+' or '-' at the start of the line. */ \
141 TYPE(ObjCMethodSpecifier) \
142 TYPE(ObjCProperty) \
143 /* The parentheses following '@selector' and the colon following the method \
144 * or parameter name inside the parentheses. */ \
145 TYPE(ObjCSelector) \
146 TYPE(ObjCStringLiteral) \
147 TYPE(OverloadedOperator) \
148 TYPE(OverloadedOperatorLParen) \
149 TYPE(PointerOrReference) \
150 TYPE(ProtoExtensionLSquare) \
151 TYPE(PureVirtualSpecifier) \
152 TYPE(QtProperty) \
153 TYPE(RangeBasedForLoopColon) \
154 TYPE(RecordLBrace) \
155 TYPE(RecordRBrace) \
156 TYPE(RegexLiteral) \
157 TYPE(RequiresClause) \
158 TYPE(RequiresClauseInARequiresExpression) \
159 TYPE(RequiresExpression) \
160 TYPE(RequiresExpressionLBrace) \
161 TYPE(RequiresExpressionLParen) \
162 /* The hash key in languages that have hash literals, not including the \
163 * field name in the C++ struct literal. Also the method or parameter name \
164 * in the Objective-C method declaration or call. */ \
165 TYPE(SelectorName) \
166 TYPE(StartOfName) \
167 TYPE(StatementAttributeLikeMacro) \
168 TYPE(StatementMacro) \
169 /* A string that is part of a string concatenation. For C#, JavaScript, and \
170 * Java, it is used for marking whether a string needs parentheses around it \
171 * if it is to be split into parts joined by `+`. For Verilog, whether \
172 * braces need to be added to split it. Not used for other languages. */ \
173 TYPE(StringInConcatenation) \
174 TYPE(StructLBrace) \
175 TYPE(StructRBrace) \
176 TYPE(StructuredBindingLSquare) \
177 TYPE(SwitchExpressionLabel) \
178 TYPE(SwitchExpressionLBrace) \
179 TYPE(TableGenBangOperator) \
180 TYPE(TableGenCondOperator) \
181 TYPE(TableGenCondOperatorColon) \
182 TYPE(TableGenCondOperatorComma) \
183 TYPE(TableGenDAGArgCloser) \
184 TYPE(TableGenDAGArgListColon) \
185 TYPE(TableGenDAGArgListColonToAlign) \
186 TYPE(TableGenDAGArgListComma) \
187 TYPE(TableGenDAGArgListCommaToBreak) \
188 TYPE(TableGenDAGArgOpener) \
189 TYPE(TableGenDAGArgOpenerToBreak) \
190 TYPE(TableGenDAGArgOperatorID) \
191 TYPE(TableGenDAGArgOperatorToBreak) \
192 TYPE(TableGenListCloser) \
193 TYPE(TableGenListOpener) \
194 TYPE(TableGenMultiLineString) \
195 TYPE(TableGenTrailingPasteOperator) \
196 TYPE(TableGenValueSuffix) \
197 TYPE(TemplateCloser) \
198 TYPE(TemplateOpener) \
199 TYPE(TemplateString) \
200 TYPE(TrailingAnnotation) \
201 TYPE(TrailingReturnArrow) \
202 TYPE(TrailingUnaryOperator) \
203 TYPE(TypeDeclarationParen) \
204 TYPE(TemplateName) \
205 TYPE(TypeName) \
206 TYPE(TypenameMacro) \
207 TYPE(UnaryOperator) \
208 TYPE(UnionLBrace) \
209 TYPE(UnionRBrace) \
210 TYPE(UntouchableMacroFunc) \
211 TYPE(VariableTemplate) \
212 /* Like in 'assign x = 0, y = 1;' . */ \
213 TYPE(VerilogAssignComma) \
214 /* like in begin : block */ \
215 TYPE(VerilogBlockLabelColon) \
216 /* The square bracket for the dimension part of the type name. \
217 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
218 * before the first bracket but not the second. */ \
219 TYPE(VerilogDimensionedTypeName) \
220 /* list of port connections or parameters in a module instantiation */ \
221 TYPE(VerilogInstancePortComma) \
222 TYPE(VerilogInstancePortLParen) \
223 /* A parenthesized list within which line breaks are inserted by the \
224 * formatter, for example the list of ports in a module header. */ \
225 TYPE(VerilogMultiLineListLParen) \
226 /* for the base in a number literal, not including the quote */ \
227 TYPE(VerilogNumberBase) \
228 /* The text that is in the opaque protected block. Like the text between \
229 * 'pragma protect data_block' and 'pragma protect end_protected'. */ \
230 TYPE(VerilogProtected) \
231 /* like `(strong1, pull0)` */ \
232 TYPE(VerilogStrength) \
233 /* Things inside the table in user-defined primitives. */ \
234 TYPE(VerilogTableItem) \
235 /* those that separate ports of different types */ \
236 TYPE(VerilogTypeComma) \
237 TYPE(Unknown)
238
239/// Determines the semantic type of a syntactic token, e.g. whether "<" is a
240/// template opener or binary operator.
241enum TokenType : uint8_t {
242#define TYPE(X) TT_##X,
244#undef TYPE
246};
248/// Determines the name of a token type.
249const char *getTokenTypeName(TokenType Type);
251// Represents what type of block a set of braces open.
254// The packing kind of a function's parameters.
258
259/// Roles a token can take in a configured macro expansion.
260enum MacroRole {
261 /// The token was expanded from a macro argument when formatting the expanded
262 /// token sequence.
264 /// The token is part of a macro argument that was previously formatted as
265 /// expansion when formatting the unexpanded macro call.
267 /// The token was expanded from a macro definition, and is not visible as part
268 /// of the macro call.
269 MR_Hidden,
270};
271
272struct FormatToken;
273
274/// Contains information on the token's role in a macro expansion.
275///
276/// Given the following definitions:
277/// A(X) = [ X ]
278/// B(X) = < X >
279/// C(X) = X
280///
281/// Consider the macro call:
282/// A({B(C(C(x)))}) -> [{<x>}]
283///
284/// In this case, the tokens of the unexpanded macro call will have the
285/// following relevant entries in their macro context (note that formatting
286/// the unexpanded macro call happens *after* formatting the expanded macro
287/// call):
288/// A( { B( C( C(x) ) ) } )
289/// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
290///
291/// [ { < x > } ]
292/// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
293/// ExpandedFrom[0]: A A A A A A A
294/// ExpandedFrom[1]: B B B
295/// ExpandedFrom[2]: C
296/// ExpandedFrom[3]: C
297/// StartOfExpansion: 1 0 1 2 0 0 0
298/// EndOfExpansion: 0 0 0 2 1 0 1
299struct MacroExpansion {
302 /// The token's role in the macro expansion.
303 /// When formatting an expanded macro, all tokens that are part of macro
304 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
305 /// the macro call will be MR_Hidden.
306 /// When formatting an unexpanded macro call, all tokens that are part of
307 /// macro arguments will be MR_UnexpandedArg.
309
310 /// The stack of macro call identifier tokens this token was expanded from.
312
313 /// The number of expansions of which this macro is the first entry.
314 unsigned StartOfExpansion = 0;
315
316 /// The number of currently open expansions in \c ExpandedFrom this macro is
317 /// the last token in.
318 unsigned EndOfExpansion = 0;
319};
320
321class TokenRole;
322class AnnotatedLine;
323
324/// A wrapper around a \c Token storing information about the
325/// whitespace characters preceding it.
326struct FormatToken {
336 Decision(FD_Unformatted), PackingKind(PPK_Inconclusive),
337 TypeIsFinalized(false), Type(TT_Unknown) {}
338
339 /// The \c Token.
340 Token Tok;
341
342 /// The raw text of the token.
343 ///
344 /// Contains the raw token text without leading whitespace and without leading
345 /// escaped newlines.
346 StringRef TokenText;
347
348 /// A token can have a special role that can carry extra information
349 /// about the token's formatting.
350 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
351 /// classes and make this a unique_ptr in the AnnotatedToken class.
352 std::shared_ptr<TokenRole> Role;
353
354 /// The range of the whitespace immediately preceding the \c Token.
356
357 /// Whether there is at least one unescaped newline before the \c
358 /// Token.
359 unsigned HasUnescapedNewline : 1;
360
361 /// Whether the token text contains newlines (escaped or not).
362 unsigned IsMultiline : 1;
363
364 /// Indicates that this is the first token of the file.
365 unsigned IsFirst : 1;
366
367 /// Whether there must be a line break before this token.
368 ///
369 /// This happens for example when a preprocessor directive ended directly
370 /// before the token.
371 unsigned MustBreakBefore : 1;
372
373 /// Whether MustBreakBefore is finalized during parsing and must not
374 /// be reset between runs.
376
377 /// Set to \c true if this token is an unterminated literal.
378 unsigned IsUnterminatedLiteral : 1;
379
380 /// \c true if it is allowed to break before this token.
381 unsigned CanBreakBefore : 1;
383 /// \c true if this is the ">" of "template<..>".
384 unsigned ClosesTemplateDeclaration : 1;
385
386 /// \c true if this token starts a binary expression, i.e. has at least
387 /// one fake l_paren with a precedence greater than prec::Unknown.
388 unsigned StartsBinaryExpression : 1;
389 /// \c true if this token ends a binary expression.
390 unsigned EndsBinaryExpression : 1;
391
392 /// Is this token part of a \c DeclStmt defining multiple variables?
393 ///
394 /// Only set if \c Type == \c TT_StartOfName.
396
397 /// Does this line comment continue a line comment section?
398 ///
399 /// Only set to true if \c Type == \c TT_LineComment.
400 unsigned ContinuesLineCommentSection : 1;
402 /// If \c true, this token has been fully formatted (indented and
403 /// potentially re-formatted inside), and we do not allow further formatting
404 /// changes.
405 unsigned Finalized : 1;
406
407 /// \c true if this is the last token within requires clause.
409
410 /// \c true if this token ends a group of C++ attributes.
412
413 /// \c true if a comma has been inserted or removed after the token.
414 unsigned HasEnumTrailingCommaHandled : 1;
415
416private:
417 /// Contains the kind of block if this token is a brace.
418 unsigned BlockKind : 2;
419
420public:
422 return static_cast<BraceBlockKind>(BlockKind);
423 }
425 BlockKind = BBK;
426 assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
427 }
428
429private:
430 /// Stores the formatting decision for the token once it was made.
431 unsigned Decision : 2;
432
433public:
435 return static_cast<FormatDecision>(Decision);
436 }
438 Decision = D;
439 assert(getDecision() == D && "FormatDecision overflow!");
440 }
441
442private:
443 /// If this is an opening parenthesis, how are the parameters packed?
444 unsigned PackingKind : 2;
445
446public:
448 return static_cast<ParameterPackingKind>(PackingKind);
451 PackingKind = K;
452 assert(getPackingKind() == K && "ParameterPackingKind overflow!");
453 }
454
455private:
456 unsigned TypeIsFinalized : 1;
458
459public:
460 /// Returns the token's type, e.g. whether "<" is a template opener or
461 /// binary operator.
462 TokenType getType() const { return Type; }
463 void setType(TokenType T) {
464 // If this token is a macro argument while formatting an unexpanded macro
465 // call, we do not change its type any more - the type was deduced from
466 // formatting the expanded macro stream already.
467 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
468 return;
469 assert((!TypeIsFinalized || T == Type) &&
470 "Please use overwriteFixedType to change a fixed type.");
471 Type = T;
472 }
473 /// Sets the type and also the finalized flag. This prevents the type to be
474 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
475 /// to another one please use overwriteFixedType, or even better remove the
476 /// need to reassign the type.
478 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
479 return;
480 Type = T;
481 TypeIsFinalized = true;
482 }
484 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
485 return;
486 TypeIsFinalized = false;
487 setType(T);
488 }
489 bool isTypeFinalized() const { return TypeIsFinalized; }
490
491 /// Used to set an operator precedence explicitly.
493
494 /// The number of newlines immediately before the \c Token.
495 ///
496 /// This can be used to determine what the user wrote in the original code
497 /// and thereby e.g. leave an empty line between two function definitions.
498 unsigned NewlinesBefore = 0;
499
500 /// The number of newlines immediately before the \c Token after formatting.
501 ///
502 /// This is used to avoid overlapping whitespace replacements when \c Newlines
503 /// is recomputed for a finalized preprocessor branching directive.
504 int Newlines = -1;
505
506 /// The offset just past the last '\n' in this token's leading
507 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
508 unsigned LastNewlineOffset = 0;
509
510 /// The width of the non-whitespace parts of the token (or its first
511 /// line for multi-line tokens) in columns.
512 /// We need this to correctly measure number of columns a token spans.
513 unsigned ColumnWidth = 0;
515 /// Contains the width in columns of the last line of a multi-line
516 /// token.
517 unsigned LastLineColumnWidth = 0;
519 /// The number of spaces that should be inserted before this token.
520 unsigned SpacesRequiredBefore = 0;
521
522 /// Number of parameters, if this is "(", "[" or "<".
523 unsigned ParameterCount = 0;
524
525 /// Number of parameters that are nested blocks,
526 /// if this is "(", "[" or "<".
527 unsigned BlockParameterCount = 0;
528
529 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
530 /// the surrounding bracket.
531 tok::TokenKind ParentBracket = tok::unknown;
532
533 /// The total length of the unwrapped line up to and including this
534 /// token.
535 unsigned TotalLength = 0;
536
537 /// The original 0-based column of this token, including expanded tabs.
538 /// The configured TabWidth is used as tab width.
539 unsigned OriginalColumn = 0;
540
541 /// The length of following tokens until the next natural split point,
542 /// or the next token that can be broken.
543 unsigned UnbreakableTailLength = 0;
544
545 // FIXME: Come up with a 'cleaner' concept.
546 /// The binding strength of a token. This is a combined value of
547 /// operator precedence, parenthesis nesting, etc.
548 unsigned BindingStrength = 0;
550 /// The nesting level of this token, i.e. the number of surrounding (),
551 /// [], {} or <>.
552 unsigned NestingLevel = 0;
553
554 /// The indent level of this token. Copied from the surrounding line.
555 unsigned IndentLevel = 0;
557 /// Block + continuation indent level, applied by the WhitespaceManager to
558 /// this token.
559 mutable unsigned AppliedIndentLevel = 0;
560
561 /// Penalty for inserting a line break before this token.
562 unsigned SplitPenalty = 0;
563
564 /// If this is the first ObjC selector name in an ObjC method
565 /// definition or call, this contains the length of the longest name.
566 ///
567 /// This being set to 0 means that the selectors should not be colon-aligned,
568 /// e.g. because several of them are block-type.
569 unsigned LongestObjCSelectorName = 0;
570
571 /// If this is the first ObjC selector name in an ObjC method
572 /// definition or call, this contains the number of parts that the whole
573 /// selector consist of.
574 unsigned ObjCSelectorNameParts = 0;
576 /// The 0-based index of the parameter/argument. For ObjC it is set
577 /// for the selector name token.
578 /// For now calculated only for ObjC.
579 unsigned ParameterIndex = 0;
580
581 /// Stores the number of required fake parentheses and the
582 /// corresponding operator precedence.
583 ///
584 /// If multiple fake parentheses start at a token, this vector stores them in
585 /// reverse order, i.e. inner fake parenthesis first.
587 /// Insert this many fake ) after this token for correct indentation.
588 unsigned FakeRParens = 0;
590 /// If this is an operator (or "."/"->") in a sequence of operators
591 /// with the same precedence, contains the 0-based operator index.
592 unsigned OperatorIndex = 0;
593
594 /// If this is an operator (or "."/"->") in a sequence of operators
595 /// with the same precedence, points to the next operator.
596 FormatToken *NextOperator = nullptr;
597
598 /// If this is a bracket, this points to the matching one.
599 FormatToken *MatchingParen = nullptr;
600
601 /// The previous token in the unwrapped line.
602 FormatToken *Previous = nullptr;
603
604 /// The next token in the unwrapped line.
605 FormatToken *Next = nullptr;
606
607 /// The first token in set of column elements.
608 bool StartsColumn = false;
609
610 /// This notes the start of the line of an array initializer.
611 bool ArrayInitializerLineStart = false;
612
613 /// This starts an array initializer.
614 bool IsArrayInitializer = false;
615
616 /// Is optional and can be removed.
617 bool Optional = false;
618
619 /// Might be function declaration open/closing paren.
620 bool MightBeFunctionDeclParen = false;
621
622 /// Has "\n\f\n" or "\n\f\r\n" before TokenText.
623 bool HasFormFeedBefore = false;
624
625 /// Is the first token after a preprocessor line.
626 bool FirstAfterPPLine = false;
628 /// Number of optional braces to be inserted after this token:
629 /// -1: a single left brace
630 /// 0: no braces
631 /// >0: number of right braces
632 int8_t BraceCount = 0;
633
634 /// Whether a left brace was already inserted after this token when an
635 /// earlier run was analyzed.
636 bool LBraceInserted = false;
637
638 /// If this token starts a block, this contains all the unwrapped lines
639 /// in it.
641
642 // Contains all attributes related to how this token takes part
643 // in a configured macro expansion.
644 std::optional<MacroExpansion> MacroCtx;
645
646 /// When macro expansion introduces nodes with children, those are marked as
647 /// \c MacroParent.
648 /// FIXME: The formatting code currently hard-codes the assumption that
649 /// child nodes are introduced by blocks following an opening brace.
650 /// This is deeply baked into the code and disentangling this will require
651 /// signficant refactorings. \c MacroParent allows us to special-case the
652 /// cases in which we treat parents as block-openers for now.
653 bool MacroParent = false;
655 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
656 bool is(tok::ObjCKeywordKind Kind) const {
657 return Tok.getObjCKeywordID() == Kind;
658 }
659 bool is(TokenType TT) const { return getType() == TT; }
660 bool is(const IdentifierInfo *II) const {
661 return II && II == Tok.getIdentifierInfo();
662 }
663 bool is(tok::PPKeywordKind Kind) const {
664 return Tok.getIdentifierInfo() &&
665 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
666 }
667 bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; }
668 bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; }
670 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
671 return is(K1) || is(K2);
672 }
673 template <typename A, typename B, typename... Ts>
674 bool isOneOf(A K1, B K2, Ts... Ks) const {
675 return is(K1) || isOneOf(K2, Ks...);
676 }
677 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
678 template <typename... Ts> bool isNoneOf(Ts... Ks) const {
679 return !isOneOf(Ks...);
681
682 bool isIf(bool AllowConstexprMacro = true) const {
683 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
684 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
685 }
686
687 bool isLoop(const FormatStyle &Style) const {
688 return isOneOf(tok::kw_for, tok::kw_while) ||
689 (Style.isJavaScript() && isNot(tok::l_paren) && Previous &&
690 Previous->is(tok::kw_for));
691 }
692
693 bool closesScopeAfterBlock() const {
694 if (getBlockKind() == BK_Block)
695 return true;
696 if (closesScope())
697 return Previous->closesScopeAfterBlock();
698 return false;
699 }
700
701 /// \c true if this token starts a sequence with the given tokens in order,
702 /// following the ``Next`` pointers, ignoring comments.
703 template <typename A, typename... Ts>
704 bool startsSequence(A K1, Ts... Tokens) const {
705 return startsSequenceInternal(K1, Tokens...);
706 }
707
708 /// \c true if this token ends a sequence with the given tokens in order,
709 /// following the ``Previous`` pointers, ignoring comments.
710 /// For example, given tokens [T1, T2, T3], the function returns true if
711 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
712 /// words, the tokens passed to this function need to the reverse of the
713 /// order the tokens appear in code.
714 template <typename A, typename... Ts>
715 bool endsSequence(A K1, Ts... Tokens) const {
716 return endsSequenceInternal(K1, Tokens...);
717 }
718
719 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
720
721 bool isAttribute() const {
722 return isOneOf(tok::kw___attribute, tok::kw___declspec, TT_AttributeMacro);
723 }
724
725 bool isAccessSpecifierKeyword() const {
726 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
727 }
728
729 bool isAccessSpecifier(bool ColonRequired = true) const {
730 if (!isAccessSpecifierKeyword())
731 return false;
732 if (!ColonRequired)
733 return true;
734 const auto *NextNonComment = getNextNonComment();
735 return NextNonComment && NextNonComment->is(tok::colon);
736 }
737
738 bool canBePointerOrReferenceQualifier() const {
739 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
740 tok::kw__Nonnull, tok::kw__Nullable,
741 tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64,
742 tok::kw___funcref) ||
743 isAttribute();
744 }
745
746 [[nodiscard]] bool isQtProperty() const;
747 [[nodiscard]] bool isTypeName(const LangOptions &LangOpts) const;
748 [[nodiscard]] bool isTypeOrIdentifier(const LangOptions &LangOpts) const;
749
750 bool isObjCAccessSpecifier() const {
751 return is(tok::at) && Next &&
752 Next->isOneOf(tok::objc_public, tok::objc_protected,
753 tok::objc_package, tok::objc_private);
754 }
755
756 bool isObjCLifetimeQualifier(const FormatStyle &Style) const {
757 if (Style.Language != FormatStyle::LK_ObjC || isNot(tok::identifier) ||
758 !TokenText.starts_with("__")) {
759 return false;
760 }
761 const auto Qualifier = TokenText.substr(2);
762 return Qualifier == "autoreleasing" || Qualifier == "strong" ||
763 Qualifier == "weak" || Qualifier == "unsafe_unretained";
764 }
765
766 /// Returns whether \p Tok is ([{ or an opening < of a template or in
767 /// protos.
768 bool opensScope() const {
769 if (is(TT_TemplateString) && TokenText.ends_with("${"))
770 return true;
771 if (is(TT_DictLiteral) && is(tok::less))
772 return true;
773 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
774 TT_TemplateOpener);
775 }
776 /// Returns whether \p Tok is )]} or a closing > of a template or in
777 /// protos.
778 bool closesScope() const {
779 if (is(TT_TemplateString) && TokenText.starts_with("}"))
780 return true;
781 if (is(TT_DictLiteral) && is(tok::greater))
782 return true;
783 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
784 TT_TemplateCloser);
785 }
786
787 /// Returns \c true if this is a "." or "->" accessing a member.
788 bool isMemberAccess() const {
789 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
790 isNoneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
791 TT_LambdaArrow, TT_LeadingJavaAnnotation);
792 }
793
794 bool isPointerOrReference() const {
795 return isOneOf(tok::star, tok::amp, tok::ampamp);
796 }
797
798 bool isPlacementOperator() const {
799 return isOneOf(tok::kw_new, tok::kw_delete);
800 }
801
802 bool isUnaryOperator() const {
803 switch (Tok.getKind()) {
804 case tok::plus:
805 case tok::plusplus:
806 case tok::minus:
807 case tok::minusminus:
808 case tok::exclaim:
809 case tok::tilde:
810 case tok::kw_sizeof:
811 case tok::kw_alignof:
812 return true;
813 default:
814 return false;
815 }
816 }
817
818 bool isBinaryOperator() const {
819 // Comma is a binary operator, but does not behave as such wrt. formatting.
820 return getPrecedence() > prec::Comma;
821 }
822
823 bool isTrailingComment() const {
824 return is(tok::comment) &&
825 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
826 }
827
828 /// Returns \c true if this is a keyword that can be used
829 /// like a function call (e.g. sizeof, typeid, ...).
830 bool isFunctionLikeKeyword() const {
831 if (isAttribute())
832 return true;
833
834 return isOneOf(tok::kw_throw, tok::kw_typeid, tok::kw_return,
835 tok::kw_sizeof, tok::kw_alignof, tok::kw_alignas,
836 tok::kw_decltype, tok::kw_noexcept, tok::kw_static_assert,
837 tok::kw__Atomic,
838#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
839#include "clang/Basic/BuiltinTraits.inc"
840 tok::kw_requires);
841 }
842
843 /// Returns \c true if this is a string literal that's like a label,
844 /// e.g. ends with "=" or ":".
845 bool isLabelString() const {
846 if (isNot(tok::string_literal))
847 return false;
848 StringRef Content = TokenText;
849 if (Content.starts_with("\"") || Content.starts_with("'"))
850 Content = Content.drop_front(1);
851 if (Content.ends_with("\"") || Content.ends_with("'"))
852 Content = Content.drop_back(1);
853 Content = Content.trim();
854 return Content.size() > 1 &&
855 (Content.back() == ':' || Content.back() == '=');
856 }
857
858 /// Returns actual token start location without leading escaped
859 /// newlines and whitespace.
860 ///
861 /// This can be different to Tok.getLocation(), which includes leading escaped
862 /// newlines.
863 SourceLocation getStartOfNonWhitespace() const {
864 return WhitespaceRange.getEnd();
865 }
866
867 /// Returns \c true if the range of whitespace immediately preceding the \c
868 /// Token is not empty.
869 bool hasWhitespaceBefore() const {
870 return WhitespaceRange.getBegin() != WhitespaceRange.getEnd();
871 }
872
873 prec::Level getPrecedence() const {
876 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
877 /*CPlusPlus11=*/true);
878 }
879
880 template <typename T> [[nodiscard]] FormatToken *getPrevious(T A1) const {
882 while (Tok && Tok->isNot(A1))
883 Tok = Tok->Previous;
884 return Tok;
885 }
886
887 template <typename... Ts>
888 [[nodiscard]] FormatToken *getPreviousOneOf(Ts... Ks) const {
890 while (Tok && (Tok->isNot(Ks) && ...))
891 Tok = Tok->Previous;
892 return Tok;
894
895 /// Returns the previous token ignoring comments.
896 [[nodiscard]] FormatToken *getPreviousNonComment() const {
898 while (Tok && Tok->is(tok::comment))
899 Tok = Tok->Previous;
900 return Tok;
901 }
903 /// Returns the next token ignoring comments.
904 [[nodiscard]] FormatToken *getNextNonComment() const {
906 while (Tok && Tok->is(tok::comment))
907 Tok = Tok->Next;
908 return Tok;
909 }
910
911 /// Returns \c true if this token likely names an object-like macro.
912 ///
913 /// If \p AllowFollowingColonColon is \c true, a following \c :: does not
914 /// disqualify the token from being considered macro-like.
915 bool isPossibleMacro(bool AllowFollowingColonColon = false) const {
916 if (isNot(tok::identifier))
917 return false;
918
919 assert(!TokenText.empty());
920
921 // T, K, U, V likely could be template arguments.
922 if (TokenText.size() == 1)
923 return false;
924
925 // It's unlikely that qualified names are object-like macros.
926 const auto *Prev = getPreviousNonComment();
927 if (Prev && Prev->is(tok::coloncolon))
928 return false;
929 if (!AllowFollowingColonColon) {
930 const auto *Next = getNextNonComment();
931 if (Next && Next->is(tok::coloncolon))
932 return false;
933 }
934
935 return TokenText == TokenText.upper();
937
938 /// Returns \c true if this token ends a block indented initializer list.
939 [[nodiscard]] bool isBlockIndentedInitRBrace(const FormatStyle &Style) const;
940
941 /// Returns \c true if a newline should exist between this token and a
942 /// preceding attribute.
943 [[nodiscard]] bool mustBreakAfterAttributes(const FormatStyle &Style) const;
944
945 /// Returns \c true if this tokens starts a block-type list, i.e. a
946 /// list that should be indented with a block indent.
947 [[nodiscard]] bool opensBlockOrBlockTypeList(const FormatStyle &Style) const;
948
949 /// Returns whether the token is the left square bracket of a C++
950 /// structured binding declaration.
951 bool isCppStructuredBinding(bool IsCpp) const {
952 if (!IsCpp || isNot(tok::l_square))
953 return false;
954 const FormatToken *T = this;
955 do {
956 T = T->getPreviousNonComment();
957 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
958 tok::ampamp));
959 return T && T->is(tok::kw_auto);
960 }
961
962 /// Same as opensBlockOrBlockTypeList, but for the closing token.
963 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
964 if (is(TT_TemplateString) && closesScope())
965 return true;
966 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
967 }
968
969 /// Return the actual namespace token, if this token starts a namespace
970 /// block.
972 const FormatToken *NamespaceTok = this;
973 if (is(tok::comment))
974 NamespaceTok = NamespaceTok->getNextNonComment();
975 // Detect "(inline|export)? namespace" in the beginning of a line.
976 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
977 NamespaceTok = NamespaceTok->getNextNonComment();
978 return NamespaceTok &&
979 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
980 ? NamespaceTok
981 : nullptr;
982 }
983
984 void copyFrom(const FormatToken &Tok) { *this = Tok; }
985
986private:
987 // Only allow copying via the explicit copyFrom method.
988 FormatToken(const FormatToken &) = delete;
989 FormatToken &operator=(const FormatToken &) = default;
990
991 template <typename A, typename... Ts>
992 bool startsSequenceInternal(A K1, Ts... Tokens) const {
993 if (is(tok::comment) && Next)
994 return Next->startsSequenceInternal(K1, Tokens...);
995 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
996 }
997
998 template <typename A> bool startsSequenceInternal(A K1) const {
999 if (is(tok::comment) && Next)
1000 return Next->startsSequenceInternal(K1);
1001 return is(K1);
1002 }
1004 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
1005 if (is(tok::comment) && Previous)
1006 return Previous->endsSequenceInternal(K1);
1007 return is(K1);
1009
1010 template <typename A, typename... Ts>
1011 bool endsSequenceInternal(A K1, Ts... Tokens) const {
1012 if (is(tok::comment) && Previous)
1013 return Previous->endsSequenceInternal(K1, Tokens...);
1014 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
1015 }
1016};
1017
1018class ContinuationIndenter;
1019struct LineState;
1020
1021class TokenRole {
1022public:
1024 virtual ~TokenRole();
1025
1026 /// After the \c TokenAnnotator has finished annotating all the tokens,
1027 /// this function precomputes required information for formatting.
1028 virtual void precomputeFormattingInfos(const FormatToken *Token);
1029
1030 /// Apply the special formatting that the given role demands.
1031 ///
1032 /// Assumes that the token having this role is already formatted.
1033 ///
1034 /// Continues formatting from \p State leaving indentation to \p Indenter and
1035 /// returns the total penalty that this formatting incurs.
1036 virtual unsigned formatFromToken(LineState &State,
1037 ContinuationIndenter *Indenter,
1038 bool DryRun) {
1039 return 0;
1041
1042 /// Same as \c formatFromToken, but assumes that the first token has
1043 /// already been set thereby deciding on the first line break.
1044 virtual unsigned formatAfterToken(LineState &State,
1045 ContinuationIndenter *Indenter,
1046 bool DryRun) {
1047 return 0;
1050 /// Notifies the \c Role that a comma was found.
1051 virtual void CommaFound(const FormatToken *Token) {}
1052
1053 virtual const FormatToken *lastComma() { return nullptr; }
1055protected:
1056 const FormatStyle &Style;
1057};
1059class CommaSeparatedList : public TokenRole {
1060public:
1061 CommaSeparatedList(const FormatStyle &Style)
1062 : TokenRole(Style), HasNestedBracedList(false) {}
1063
1065
1066 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
1067 bool DryRun) override;
1069 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
1070 bool DryRun) override;
1071
1072 /// Adds \p Token as the next comma to the \c CommaSeparated list.
1073 void CommaFound(const FormatToken *Token) override {
1074 Commas.push_back(Token);
1075 }
1077 const FormatToken *lastComma() override {
1078 if (Commas.empty())
1079 return nullptr;
1080 return Commas.back();
1081 }
1082
1083private:
1084 /// A struct that holds information on how to format a given list with
1085 /// a specific number of columns.
1086 struct ColumnFormat {
1087 /// The number of columns to use.
1088 unsigned Columns;
1090 /// The total width in characters.
1091 unsigned TotalWidth;
1092
1093 /// The number of lines required for this format.
1094 unsigned LineCount;
1095
1096 /// The size of each column in characters.
1097 SmallVector<unsigned, 8> ColumnSizes;
1098 };
1099
1100 /// Calculate which \c ColumnFormat fits best into
1101 /// \p RemainingCharacters.
1102 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
1104 /// The ordered \c FormatTokens making up the commas of this list.
1107 /// The length of each of the list's items in characters including the
1108 /// trailing comma.
1109 SmallVector<unsigned, 8> ItemLengths;
1111 /// Precomputed formats that can be used for this list.
1113
1114 bool HasNestedBracedList;
1116
1117/// Encapsulates keywords that are context sensitive or for languages not
1118/// properly supported by Clang's lexer.
1119struct AdditionalKeywords {
1120 AdditionalKeywords(IdentifierTable &IdentTable) {
1121 kw_final = &IdentTable.get("final");
1122 kw_override = &IdentTable.get("override");
1123 kw_in = &IdentTable.get("in");
1124 kw_of = &IdentTable.get("of");
1125 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
1126 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
1127 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
1128 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
1129 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
1130 kw_NS_ERROR_ENUM = &IdentTable.get("NS_ERROR_ENUM");
1131 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
1132
1133 kw_as = &IdentTable.get("as");
1134 kw_async = &IdentTable.get("async");
1135 kw_await = &IdentTable.get("await");
1136 kw_declare = &IdentTable.get("declare");
1137 kw_finally = &IdentTable.get("finally");
1138 kw_from = &IdentTable.get("from");
1139 kw_function = &IdentTable.get("function");
1140 kw_get = &IdentTable.get("get");
1141 kw_import = &IdentTable.get("import");
1142 kw_infer = &IdentTable.get("infer");
1143 kw_is = &IdentTable.get("is");
1144 kw_let = &IdentTable.get("let");
1145 kw_module = &IdentTable.get("module");
1146 kw_readonly = &IdentTable.get("readonly");
1147 kw_set = &IdentTable.get("set");
1148 kw_type = &IdentTable.get("type");
1149 kw_typeof = &IdentTable.get("typeof");
1150 kw_var = &IdentTable.get("var");
1151 kw_yield = &IdentTable.get("yield");
1153 kw_abstract = &IdentTable.get("abstract");
1154 kw_assert = &IdentTable.get("assert");
1155 kw_extends = &IdentTable.get("extends");
1156 kw_implements = &IdentTable.get("implements");
1157 kw_instanceof = &IdentTable.get("instanceof");
1158 kw_interface = &IdentTable.get("interface");
1159 kw_native = &IdentTable.get("native");
1160 kw_package = &IdentTable.get("package");
1161 kw_record = &IdentTable.get("record");
1162 kw_synchronized = &IdentTable.get("synchronized");
1163 kw_throws = &IdentTable.get("throws");
1164 kw___except = &IdentTable.get("__except");
1165 kw___has_include = &IdentTable.get("__has_include");
1166 kw___has_include_next = &IdentTable.get("__has_include_next");
1168 kw_mark = &IdentTable.get("mark");
1169 kw_region = &IdentTable.get("region");
1170
1171 kw_extend = &IdentTable.get("extend");
1172 kw_option = &IdentTable.get("option");
1173 kw_optional = &IdentTable.get("optional");
1174 kw_repeated = &IdentTable.get("repeated");
1175 kw_required = &IdentTable.get("required");
1176 kw_returns = &IdentTable.get("returns");
1178 kw_signals = &IdentTable.get("signals");
1179 kw_qsignals = &IdentTable.get("Q_SIGNALS");
1180 kw_slots = &IdentTable.get("slots");
1181 kw_qslots = &IdentTable.get("Q_SLOTS");
1182
1183 // For internal clang-format use.
1184 kw_internal_ident_after_define =
1185 &IdentTable.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
1186
1187 // C# keywords
1188 kw_dollar = &IdentTable.get("dollar");
1189 kw_base = &IdentTable.get("base");
1190 kw_byte = &IdentTable.get("byte");
1191 kw_checked = &IdentTable.get("checked");
1192 kw_decimal = &IdentTable.get("decimal");
1193 kw_delegate = &IdentTable.get("delegate");
1194 kw_event = &IdentTable.get("event");
1195 kw_fixed = &IdentTable.get("fixed");
1196 kw_foreach = &IdentTable.get("foreach");
1197 kw_init = &IdentTable.get("init");
1198 kw_implicit = &IdentTable.get("implicit");
1199 kw_internal = &IdentTable.get("internal");
1200 kw_lock = &IdentTable.get("lock");
1201 kw_null = &IdentTable.get("null");
1202 kw_object = &IdentTable.get("object");
1203 kw_out = &IdentTable.get("out");
1204 kw_params = &IdentTable.get("params");
1205 kw_ref = &IdentTable.get("ref");
1206 kw_string = &IdentTable.get("string");
1207 kw_stackalloc = &IdentTable.get("stackalloc");
1208 kw_sbyte = &IdentTable.get("sbyte");
1209 kw_sealed = &IdentTable.get("sealed");
1210 kw_uint = &IdentTable.get("uint");
1211 kw_ulong = &IdentTable.get("ulong");
1212 kw_unchecked = &IdentTable.get("unchecked");
1213 kw_unsafe = &IdentTable.get("unsafe");
1214 kw_ushort = &IdentTable.get("ushort");
1215 kw_when = &IdentTable.get("when");
1216 kw_where = &IdentTable.get("where");
1217
1218 // Verilog keywords
1219 kw_always = &IdentTable.get("always");
1220 kw_always_comb = &IdentTable.get("always_comb");
1221 kw_always_ff = &IdentTable.get("always_ff");
1222 kw_always_latch = &IdentTable.get("always_latch");
1223 kw_assign = &IdentTable.get("assign");
1224 kw_assume = &IdentTable.get("assume");
1225 kw_automatic = &IdentTable.get("automatic");
1226 kw_before = &IdentTable.get("before");
1227 kw_begin = &IdentTable.get("begin");
1228 kw_begin_keywords = &IdentTable.get("begin_keywords");
1229 kw_bins = &IdentTable.get("bins");
1230 kw_binsof = &IdentTable.get("binsof");
1231 kw_casex = &IdentTable.get("casex");
1232 kw_casez = &IdentTable.get("casez");
1233 kw_celldefine = &IdentTable.get("celldefine");
1234 kw_checker = &IdentTable.get("checker");
1235 kw_clocking = &IdentTable.get("clocking");
1236 kw_constraint = &IdentTable.get("constraint");
1237 kw_context = &IdentTable.get("context");
1238 kw_cover = &IdentTable.get("cover");
1239 kw_covergroup = &IdentTable.get("covergroup");
1240 kw_coverpoint = &IdentTable.get("coverpoint");
1241 kw_data_block = &IdentTable.get("data_block");
1242 kw_data_decrypt_key = &IdentTable.get("data_decrypt_key");
1243 kw_data_public_key = &IdentTable.get("data_public_key");
1244 kw_default_decay_time = &IdentTable.get("default_decay_time");
1245 kw_default_nettype = &IdentTable.get("default_nettype");
1246 kw_default_trireg_strength = &IdentTable.get("default_trireg_strength");
1247 kw_delay_mode_distributed = &IdentTable.get("delay_mode_distributed");
1248 kw_delay_mode_path = &IdentTable.get("delay_mode_path");
1249 kw_delay_mode_unit = &IdentTable.get("delay_mode_unit");
1250 kw_delay_mode_zero = &IdentTable.get("delay_mode_zero");
1251 kw_digest_block = &IdentTable.get("digest_block");
1252 kw_digest_decrypt_key = &IdentTable.get("digest_decrypt_key");
1253 kw_digest_public_key = &IdentTable.get("digest_public_key");
1254 kw_disable = &IdentTable.get("disable");
1255 kw_dist = &IdentTable.get("dist");
1256 kw_edge = &IdentTable.get("edge");
1257 kw_elsif = &IdentTable.get("elsif");
1258 kw_end = &IdentTable.get("end");
1259 kw_end_keywords = &IdentTable.get("end_keywords");
1260 kw_endcase = &IdentTable.get("endcase");
1261 kw_endcelldefine = &IdentTable.get("endcelldefine");
1262 kw_endchecker = &IdentTable.get("endchecker");
1263 kw_endclass = &IdentTable.get("endclass");
1264 kw_endclocking = &IdentTable.get("endclocking");
1265 kw_endfunction = &IdentTable.get("endfunction");
1266 kw_endgenerate = &IdentTable.get("endgenerate");
1267 kw_endgroup = &IdentTable.get("endgroup");
1268 kw_endinterface = &IdentTable.get("endinterface");
1269 kw_endmodule = &IdentTable.get("endmodule");
1270 kw_endpackage = &IdentTable.get("endpackage");
1271 kw_endprimitive = &IdentTable.get("endprimitive");
1272 kw_endprogram = &IdentTable.get("endprogram");
1273 kw_endproperty = &IdentTable.get("endproperty");
1274 kw_endsequence = &IdentTable.get("endsequence");
1275 kw_endspecify = &IdentTable.get("endspecify");
1276 kw_endtable = &IdentTable.get("endtable");
1277 kw_endtask = &IdentTable.get("endtask");
1278 kw_forever = &IdentTable.get("forever");
1279 kw_fork = &IdentTable.get("fork");
1280 kw_generate = &IdentTable.get("generate");
1281 kw_highz0 = &IdentTable.get("highz0");
1282 kw_highz1 = &IdentTable.get("highz1");
1283 kw_iff = &IdentTable.get("iff");
1284 kw_ifnone = &IdentTable.get("ifnone");
1285 kw_ignore_bins = &IdentTable.get("ignore_bins");
1286 kw_illegal_bins = &IdentTable.get("illegal_bins");
1287 kw_initial = &IdentTable.get("initial");
1288 kw_inout = &IdentTable.get("inout");
1289 kw_input = &IdentTable.get("input");
1290 kw_inside = &IdentTable.get("inside");
1291 kw_interconnect = &IdentTable.get("interconnect");
1292 kw_intersect = &IdentTable.get("intersect");
1293 kw_join = &IdentTable.get("join");
1294 kw_join_any = &IdentTable.get("join_any");
1295 kw_join_none = &IdentTable.get("join_none");
1296 kw_key_block = &IdentTable.get("key_block");
1297 kw_key_public_key = &IdentTable.get("key_public_key");
1298 kw_large = &IdentTable.get("large");
1299 kw_local = &IdentTable.get("local");
1300 kw_localparam = &IdentTable.get("localparam");
1301 kw_macromodule = &IdentTable.get("macromodule");
1302 kw_matches = &IdentTable.get("matches");
1303 kw_medium = &IdentTable.get("medium");
1304 kw_negedge = &IdentTable.get("negedge");
1305 kw_nounconnected_drive = &IdentTable.get("nounconnected_drive");
1306 kw_output = &IdentTable.get("output");
1307 kw_packed = &IdentTable.get("packed");
1308 kw_parameter = &IdentTable.get("parameter");
1309 kw_posedge = &IdentTable.get("posedge");
1310 kw_primitive = &IdentTable.get("primitive");
1311 kw_priority = &IdentTable.get("priority");
1312 kw_program = &IdentTable.get("program");
1313 kw_property = &IdentTable.get("property");
1314 kw_protect = &IdentTable.get("protect");
1315 kw_pull0 = &IdentTable.get("pull0");
1316 kw_pull1 = &IdentTable.get("pull1");
1317 kw_pure = &IdentTable.get("pure");
1318 kw_rand = &IdentTable.get("rand");
1319 kw_randc = &IdentTable.get("randc");
1320 kw_randcase = &IdentTable.get("randcase");
1321 kw_randsequence = &IdentTable.get("randsequence");
1322 kw_repeat = &IdentTable.get("repeat");
1323 kw_resetall = &IdentTable.get("resetall");
1324 kw_sample = &IdentTable.get("sample");
1325 kw_scalared = &IdentTable.get("scalared");
1326 kw_sequence = &IdentTable.get("sequence");
1327 kw_small = &IdentTable.get("small");
1328 kw_soft = &IdentTable.get("soft");
1329 kw_solve = &IdentTable.get("solve");
1330 kw_specify = &IdentTable.get("specify");
1331 kw_specparam = &IdentTable.get("specparam");
1332 kw_strong0 = &IdentTable.get("strong0");
1333 kw_strong1 = &IdentTable.get("strong1");
1334 kw_supply0 = &IdentTable.get("supply0");
1335 kw_supply1 = &IdentTable.get("supply1");
1336 kw_table = &IdentTable.get("table");
1337 kw_tagged = &IdentTable.get("tagged");
1338 kw_task = &IdentTable.get("task");
1339 kw_timescale = &IdentTable.get("timescale");
1340 kw_tri = &IdentTable.get("tri");
1341 kw_tri0 = &IdentTable.get("tri0");
1342 kw_tri1 = &IdentTable.get("tri1");
1343 kw_triand = &IdentTable.get("triand");
1344 kw_trior = &IdentTable.get("trior");
1345 kw_trireg = &IdentTable.get("trireg");
1346 kw_unconnected_drive = &IdentTable.get("unconnected_drive");
1347 kw_undefineall = &IdentTable.get("undefineall");
1348 kw_unique = &IdentTable.get("unique");
1349 kw_unique0 = &IdentTable.get("unique0");
1350 kw_uwire = &IdentTable.get("uwire");
1351 kw_vectored = &IdentTable.get("vectored");
1352 kw_wait = &IdentTable.get("wait");
1353 kw_wand = &IdentTable.get("wand");
1354 kw_weak0 = &IdentTable.get("weak0");
1355 kw_weak1 = &IdentTable.get("weak1");
1356 kw_wildcard = &IdentTable.get("wildcard");
1357 kw_wire = &IdentTable.get("wire");
1358 kw_with = &IdentTable.get("with");
1359 kw_wor = &IdentTable.get("wor");
1360
1361 // Symbols that are treated as keywords.
1362 kw_verilogHash = &IdentTable.get("#");
1363 kw_verilogHashHash = &IdentTable.get("##");
1364 kw_apostrophe = &IdentTable.get("\'");
1365
1366 // TableGen keywords.
1367 kw_bit = &IdentTable.get("bit");
1368 kw_bits = &IdentTable.get("bits");
1369 kw_code = &IdentTable.get("code");
1370 kw_dag = &IdentTable.get("dag");
1371 kw_def = &IdentTable.get("def");
1372 kw_defm = &IdentTable.get("defm");
1373 kw_defset = &IdentTable.get("defset");
1374 kw_defvar = &IdentTable.get("defvar");
1375 kw_dump = &IdentTable.get("dump");
1376 kw_include = &IdentTable.get("include");
1377 kw_list = &IdentTable.get("list");
1378 kw_multiclass = &IdentTable.get("multiclass");
1379 kw_then = &IdentTable.get("then");
1380
1381 // Keep this at the end of the constructor to make sure everything here is
1382 // already initialized.
1383 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
1384 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
1385 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override,
1386 kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield,
1387 // Keywords from the Java section.
1388 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
1389
1390 CSharpExtraKeywords = JsExtraKeywords;
1391 CSharpExtraKeywords.insert(
1392 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate,
1393 kw_event, kw_fixed, kw_foreach, kw_implicit, kw_in,
1394 kw_init, kw_internal, kw_lock, kw_null, kw_object,
1395 kw_out, kw_params, kw_ref, kw_string, kw_stackalloc,
1396 kw_sbyte, kw_sealed, kw_uint, kw_ulong, kw_unchecked,
1397 kw_unsafe, kw_ushort, kw_when, kw_where});
1398
1399 // Some keywords are not included here because they don't need special
1400 // treatment like `showcancelled` or they should be treated as identifiers
1401 // like `int` and `logic`.
1402 VerilogExtraKeywords =
1403 std::unordered_set<IdentifierInfo *>{kw_always,
1404 kw_always_comb,
1405 kw_always_ff,
1406 kw_always_latch,
1407 kw_assert,
1408 kw_assign,
1409 kw_assume,
1410 kw_automatic,
1411 kw_before,
1412 kw_begin,
1413 kw_bins,
1414 kw_binsof,
1415 kw_casex,
1416 kw_casez,
1417 kw_celldefine,
1418 kw_checker,
1419 kw_clocking,
1420 kw_constraint,
1421 kw_context,
1422 kw_cover,
1423 kw_covergroup,
1424 kw_coverpoint,
1425 kw_disable,
1426 kw_dist,
1427 kw_edge,
1428 kw_end,
1429 kw_endcase,
1430 kw_endchecker,
1431 kw_endclass,
1432 kw_endclocking,
1433 kw_endfunction,
1434 kw_endgenerate,
1435 kw_endgroup,
1436 kw_endinterface,
1437 kw_endmodule,
1438 kw_endpackage,
1439 kw_endprimitive,
1440 kw_endprogram,
1441 kw_endproperty,
1442 kw_endsequence,
1443 kw_endspecify,
1444 kw_endtable,
1445 kw_endtask,
1446 kw_extends,
1447 kw_final,
1448 kw_foreach,
1449 kw_forever,
1450 kw_fork,
1451 kw_function,
1452 kw_generate,
1453 kw_highz0,
1454 kw_highz1,
1455 kw_iff,
1456 kw_ifnone,
1457 kw_ignore_bins,
1458 kw_illegal_bins,
1459 kw_implements,
1460 kw_import,
1461 kw_initial,
1462 kw_inout,
1463 kw_input,
1464 kw_inside,
1465 kw_interconnect,
1466 kw_interface,
1467 kw_intersect,
1468 kw_join,
1469 kw_join_any,
1470 kw_join_none,
1471 kw_large,
1472 kw_let,
1473 kw_local,
1474 kw_localparam,
1475 kw_macromodule,
1476 kw_matches,
1477 kw_medium,
1478 kw_module,
1479 kw_negedge,
1480 kw_output,
1481 kw_package,
1482 kw_packed,
1483 kw_parameter,
1484 kw_posedge,
1485 kw_primitive,
1486 kw_priority,
1487 kw_program,
1488 kw_property,
1489 kw_pull0,
1490 kw_pull1,
1491 kw_pure,
1492 kw_rand,
1493 kw_randc,
1494 kw_randcase,
1495 kw_randsequence,
1496 kw_ref,
1497 kw_repeat,
1498 kw_sample,
1499 kw_scalared,
1500 kw_sequence,
1501 kw_small,
1502 kw_soft,
1503 kw_solve,
1504 kw_specify,
1505 kw_specparam,
1506 kw_strong0,
1507 kw_strong1,
1508 kw_supply0,
1509 kw_supply1,
1510 kw_table,
1511 kw_tagged,
1512 kw_task,
1513 kw_tri,
1514 kw_tri0,
1515 kw_tri1,
1516 kw_triand,
1517 kw_trior,
1518 kw_trireg,
1519 kw_unique,
1520 kw_unique0,
1521 kw_uwire,
1522 kw_var,
1523 kw_vectored,
1524 kw_wait,
1525 kw_wand,
1526 kw_weak0,
1527 kw_weak1,
1528 kw_wildcard,
1535 TableGenExtraKeywords = std::unordered_set<IdentifierInfo *>{
1541 // Context sensitive keywords.
1557 // JavaScript keywords.
1577
1578 // Java keywords.
1590
1591 // Pragma keywords.
1595 // Proto keywords.
1603 // QT keywords.
1609 // For internal use by clang-format.
1612 // C# keywords
1632
1646 // Verilog keywords
1789 // Workaround for hashes and backticks in Verilog.
1793 // Symbols in Verilog that don't exist in C++.
1796 // TableGen keywords
1811 /// Returns \c true if \p Tok is a keyword or an identifier.
1812 bool isWordLike(const FormatToken &Tok, bool IsVerilog = true) const {
1813 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1814 return Tok.Tok.getIdentifierInfo() &&
1815 (!IsVerilog || !isVerilogKeywordSymbol(Tok));
1816 }
1817
1818 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1819 /// \c false if it is a keyword or a pseudo keyword.
1820 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1821 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1822 // ``yield``.
1823 bool isJavaScriptIdentifier(const FormatToken &Tok,
1824 bool AcceptIdentifierName = true) const {
1825 // Based on the list of JavaScript & TypeScript keywords here:
1826 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1827 if (Tok.isAccessSpecifierKeyword())
1828 return false;
1829 switch (Tok.Tok.getKind()) {
1830 case tok::kw_break:
1831 case tok::kw_case:
1832 case tok::kw_catch:
1833 case tok::kw_class:
1834 case tok::kw_continue:
1835 case tok::kw_const:
1836 case tok::kw_default:
1837 case tok::kw_delete:
1838 case tok::kw_do:
1839 case tok::kw_else:
1840 case tok::kw_enum:
1841 case tok::kw_export:
1842 case tok::kw_false:
1843 case tok::kw_for:
1844 case tok::kw_if:
1845 case tok::kw_import:
1846 case tok::kw_module:
1847 case tok::kw_new:
1848 case tok::kw_return:
1849 case tok::kw_static:
1850 case tok::kw_switch:
1851 case tok::kw_this:
1852 case tok::kw_throw:
1853 case tok::kw_true:
1854 case tok::kw_try:
1855 case tok::kw_typeof:
1856 case tok::kw_void:
1857 case tok::kw_while:
1858 // These are JS keywords that are lexed by LLVM/clang as keywords.
1859 return false;
1860 case tok::identifier: {
1861 // For identifiers, make sure they are true identifiers, excluding the
1862 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1863 bool IsPseudoKeyword =
1864 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1865 JsExtraKeywords.end();
1866 return AcceptIdentifierName || !IsPseudoKeyword;
1867 }
1868 default:
1869 // Other keywords are handled in the switch below, to avoid problems due
1870 // to duplicate case labels when using the #include trick.
1871 break;
1872 }
1873
1874 switch (Tok.Tok.getKind()) {
1875 // Handle C++ keywords not included above: these are all JS identifiers.
1876#define KEYWORD(X, Y) case tok::kw_##X:
1877#include "clang/Basic/TokenKinds.def"
1878 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1879 // TokenKinds.def
1880 return true;
1881 default:
1882 // All other tokens (punctuation etc) are not JS identifiers.
1883 return false;
1884 }
1885 }
1886
1887 /// Returns \c true if \p Tok is a C# keyword, returns \c false if it is
1888 /// anything else.
1889 bool isCSharpKeyword(const FormatToken &Tok) const {
1890 if (Tok.isAccessSpecifierKeyword())
1891 return true;
1892 switch (Tok.Tok.getKind()) {
1893 case tok::kw_bool:
1894 case tok::kw_break:
1895 case tok::kw_case:
1896 case tok::kw_catch:
1897 case tok::kw_char:
1898 case tok::kw_class:
1899 case tok::kw_const:
1900 case tok::kw_continue:
1901 case tok::kw_default:
1902 case tok::kw_do:
1903 case tok::kw_double:
1904 case tok::kw_else:
1905 case tok::kw_enum:
1906 case tok::kw_explicit:
1907 case tok::kw_extern:
1908 case tok::kw_false:
1909 case tok::kw_float:
1910 case tok::kw_for:
1911 case tok::kw_goto:
1912 case tok::kw_if:
1913 case tok::kw_int:
1914 case tok::kw_long:
1915 case tok::kw_namespace:
1916 case tok::kw_new:
1917 case tok::kw_operator:
1918 case tok::kw_return:
1919 case tok::kw_short:
1920 case tok::kw_sizeof:
1921 case tok::kw_static:
1922 case tok::kw_struct:
1923 case tok::kw_switch:
1924 case tok::kw_this:
1925 case tok::kw_throw:
1926 case tok::kw_true:
1927 case tok::kw_try:
1928 case tok::kw_typeof:
1929 case tok::kw_using:
1930 case tok::kw_virtual:
1931 case tok::kw_void:
1932 case tok::kw_volatile:
1933 case tok::kw_while:
1934 return true;
1935 default:
1936 return Tok.is(tok::identifier) &&
1937 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1938 CSharpExtraKeywords.end();
1939 }
1940 }
1941
1942 bool isVerilogKeywordSymbol(const FormatToken &Tok) const {
1943 return Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe);
1944 }
1945
1946 bool isVerilogWordOperator(const FormatToken &Tok) const {
1947 return Tok.isOneOf(kw_before, kw_intersect, kw_dist, kw_iff, kw_inside,
1948 kw_with);
1949 }
1950
1951 bool isVerilogIdentifier(const FormatToken &Tok) const {
1952 switch (Tok.Tok.getKind()) {
1953 case tok::kw_case:
1954 case tok::kw_class:
1955 case tok::kw_const:
1956 case tok::kw_continue:
1957 case tok::kw_default:
1958 case tok::kw_do:
1959 case tok::kw_else:
1960 case tok::kw_enum:
1961 case tok::kw_export:
1962 case tok::kw_extern:
1963 case tok::kw_for:
1964 case tok::kw_if:
1965 case tok::kw_import:
1966 case tok::kw_protected:
1967 case tok::kw_restrict:
1968 case tok::kw_signed:
1969 case tok::kw_static:
1970 case tok::kw_struct:
1971 case tok::kw_typedef:
1972 case tok::kw_union:
1973 case tok::kw_unsigned:
1974 case tok::kw_virtual:
1975 case tok::kw_while:
1976 return false;
1977 case tok::identifier:
1978 return isWordLike(Tok) &&
1979 VerilogExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1980 VerilogExtraKeywords.end();
1981 default:
1982 // getIdentifierInfo returns non-null for both identifiers and keywords.
1983 return Tok.Tok.getIdentifierInfo();
1984 }
1985 }
1986
1987 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1988 /// needed because macro expansions start with a backtick as well and they
1989 /// need to be treated differently.
1990 bool isVerilogPPDirective(const FormatToken &Tok) const {
1991 auto Info = Tok.Tok.getIdentifierInfo();
1992 if (!Info)
1993 return false;
1994 switch (Info->getPPKeywordID()) {
1995 case tok::pp_define:
1996 case tok::pp_else:
1997 case tok::pp_endif:
1998 case tok::pp_ifdef:
1999 case tok::pp_ifndef:
2000 case tok::pp_include:
2001 case tok::pp_line:
2002 case tok::pp_pragma:
2003 case tok::pp_undef:
2013 }
2014 }
2016 /// Returns whether \p Tok is a Verilog keyword that opens a block.
2017 bool isVerilogBegin(const FormatToken &Tok) const {
2018 // `table` is not included since it needs to be treated specially.
2019 if (Tok.isOneOf(kw_begin, kw_generate, kw_specify))
2020 return true;
2021 if (Tok.isNot(kw_fork))
2022 return false;
2023 const auto *Prev = Tok.getPreviousNonComment();
2024 return !(Prev && Prev->isOneOf(kw_disable, kw_wait));
2025 }
2026
2027 /// Returns whether \p Tok is a Verilog keyword that closes a block.
2028 bool isVerilogEnd(const FormatToken &Tok) const {
2029 return !Tok.endsSequence(kw_join, kw_rand) &&
2030 Tok.isOneOf(TT_MacroBlockEnd, kw_end, kw_endcase, kw_endclass,
2037 }
2038
2039 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
2040 bool isVerilogHierarchy(const FormatToken &Tok) const {
2041 if (Tok.endsSequence(kw_function, kw_with))
2042 return false;
2043 if (Tok.is(kw_property)) {
2044 const FormatToken *Prev = Tok.getPreviousNonComment();
2045 return !(Prev &&
2046 Prev->isOneOf(tok::kw_restrict, kw_assert, kw_assume, kw_cover));
2047 }
2048 return Tok.isOneOf(tok::kw_case, tok::kw_class, kw_function, kw_module,
2049 kw_interface, kw_package, kw_casex, kw_casez, kw_checker,
2050 kw_clocking, kw_covergroup, kw_macromodule, kw_primitive,
2051 kw_program, kw_property, kw_randcase, kw_randsequence,
2052 kw_task);
2054
2055 bool isVerilogEndOfLabel(const FormatToken &Tok) const {
2056 const FormatToken *Next = Tok.getNextNonComment();
2057 // In Verilog the colon in a default label is optional.
2058 return Tok.is(TT_CaseLabelColon) ||
2059 (Tok.is(tok::kw_default) &&
2060 !(Next && Next->isOneOf(tok::colon, tok::semi, kw_clocking, kw_iff,
2062 }
2063
2064 /// Returns whether \p Tok is a Verilog keyword that starts a
2065 /// structured procedure like 'always'.
2066 bool isVerilogStructuredProcedure(const FormatToken &Tok) const {
2067 return Tok.isOneOf(kw_always, kw_always_comb, kw_always_ff, kw_always_latch,
2068 kw_final, kw_forever, kw_initial);
2069 }
2070
2071 bool isVerilogQualifier(const FormatToken &Tok) const {
2072 switch (Tok.Tok.getKind()) {
2073 case tok::kw_extern:
2074 case tok::kw_signed:
2075 case tok::kw_static:
2076 case tok::kw_unsigned:
2077 case tok::kw_virtual:
2078 return true;
2087 default:
2088 return false;
2089 }
2090 }
2091
2092 bool isTableGenDefinition(const FormatToken &Tok) const {
2093 return Tok.isOneOf(kw_def, kw_defm, kw_defset, kw_defvar, kw_multiclass,
2094 kw_let, tok::kw_class);
2095 }
2096
2097 bool isTableGenKeyword(const FormatToken &Tok) const {
2098 switch (Tok.Tok.getKind()) {
2099 case tok::kw_class:
2100 case tok::kw_else:
2101 case tok::kw_false:
2102 case tok::kw_if:
2103 case tok::kw_int:
2104 case tok::kw_true:
2105 return true;
2106 default:
2107 return Tok.is(tok::identifier) &&
2108 TableGenExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
2109 TableGenExtraKeywords.end();
2110 }
2111 }
2112
2113private:
2114 /// The JavaScript keywords beyond the C++ keyword set.
2115 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
2116
2117 /// The C# keywords beyond the C++ keyword set.
2118 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
2119
2120 /// The Verilog keywords beyond the C++ keyword set.
2121 std::unordered_set<IdentifierInfo *> VerilogExtraKeywords;
2122
2123 /// The TableGen keywords beyond the C++ keyword set.
2124 std::unordered_set<IdentifierInfo *> TableGenExtraKeywords;
2125};
2126
2127inline bool isLineComment(const FormatToken &FormatTok) {
2128 return FormatTok.is(tok::comment) && !FormatTok.TokenText.starts_with("/*");
2129}
2130
2131// Checks if \p FormatTok is a line comment that continues the line comment
2132// \p Previous. The original column of \p MinColumnToken is used to determine
2133// whether \p FormatTok is indented enough to the right to continue \p Previous.
2134inline bool continuesLineComment(const FormatToken &FormatTok,
2135 const FormatToken *Previous,
2136 const FormatToken *MinColumnToken) {
2137 if (!Previous || !MinColumnToken)
2138 return false;
2139 // Do not continue a comment section across a formatting-disabled boundary.
2140 if (FormatTok.Finalized != Previous->Finalized)
2141 return false;
2142 unsigned MinContinueColumn =
2143 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
2144 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
2146 FormatTok.OriginalColumn >= MinContinueColumn;
2147}
2148
2149// Returns \c true if \c Current starts a new parameter.
2150bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style);
2151
2152// Returns \c true if \c Tok is a function/storage specifier that may appear
2153// before a function return type (e.g. ``static``, ``inline``, ``constexpr``).
2154inline bool isReturnTypePrefixSpecifier(const FormatToken &Tok) {
2155 return Tok.isOneOf(tok::kw_static, tok::kw_extern, tok::kw_inline,
2156 tok::kw_virtual, tok::kw_constexpr, tok::kw_consteval,
2157 tok::kw_friend, tok::kw_export, tok::kw__Noreturn,
2158 tok::kw___forceinline);
2159}
2160
2161} // namespace format
2162} // namespace clang
2163
2164#endif
#define LIST_TOKEN_TYPES
Definition FormatToken.h:27
prec::Level ForcedPrecedence
Used to set an operator precedence explicitly.
StringRef TokenText
The raw text of the token.
FormatToken()
Token Tok
The Token.
std::optional< MacroExpansion > MacroCtx
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
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 unsigned getPrecedence(tok::TokenKind Kind)
getPrecedence - Return the precedence of the specified binary operator token.
static constexpr bool isOneOf()
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, _)
unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
void precomputeFormattingInfos(const FormatToken *Token) override
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
One of these records is kept for each identifier that is lexed.
Encodes a location in the source.
A trivial tuple used to represent a source range.
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...
TokenRole(const FormatStyle &Style)
const FormatStyle & Style
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The base class of the type hierarchy.
Definition TypeBase.h:1879
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
MacroRole
Roles a token can take in a configured macro expansion.
@ MR_UnexpandedArg
The token is part of a macro argument that was previously formatted as expansion when formatting the ...
@ MR_Hidden
The token was expanded from a macro definition, and is not visible as part of the macro call.
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const
Same as opensBlockOrBlockTypeList, but for the closing token.
void copyFrom(const FormatToken &Tok)
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
FormatToken * getPreviousOneOf(Ts... Ks) const
struct clang::format::FormatToken getPrevious(T A1) const
bool isPossibleMacro(bool AllowFollowingColonColon=false) const
Returns true if this token likely names an object-like macro.
bool mustBreakAfterAttributes(const FormatStyle &Style) const
Returns true if a newline should exist between this token and a preceding attribute.
bool isBlockIndentedInitRBrace(const FormatStyle &Style) const
Returns true if this token ends a block indented initializer list.
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e. a list that should be indented with a bloc...
bool isCppStructuredBinding(bool IsCpp) const
Returns whether the token is the left square bracket of a C++ structured binding declaration.
TokenType
Determines the semantic type of a syntactic token, e.g.
FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
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:101
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition TokenKinds.h:49
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition TokenKinds.h:41
Top level wrappers for InstallAPI frontend operations.
bool isLineComment(const FormatToken &FormatTok)
const FunctionProtoType * T
bool isReturnTypePrefixSpecifier(const FormatToken &Tok)
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 int8_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 __builtin_riscv_mqwacc_i64 uint8_t
#define false
Definition stdbool.h:26
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
LanguageKind Language
The language that this format style targets.
Definition Format.h:3922
IdentifierInfo * kw_signals
IdentifierInfo * kw_celldefine
IdentifierInfo * kw_delay_mode_distributed
IdentifierInfo * kw_pull0
IdentifierInfo * kw_instanceof
IdentifierInfo * kw_readonly
IdentifierInfo * kw___has_include
IdentifierInfo * kw_supply1
IdentifierInfo * kw_sealed
IdentifierInfo * kw_implements
IdentifierInfo * kw_infer
IdentifierInfo * kw_output
IdentifierInfo * kw_join
IdentifierInfo * kw_sbyte
IdentifierInfo * kw_override
IdentifierInfo * kw_always
IdentifierInfo * kw_endchecker
IdentifierInfo * kw___except
IdentifierInfo * kw_unchecked
IdentifierInfo * kw_vectored
IdentifierInfo * kw_specparam
IdentifierInfo * kw_decimal
IdentifierInfo * kw_default_decay_time
IdentifierInfo * kw_binsof
IdentifierInfo * kw_extend
IdentifierInfo * kw_await
IdentifierInfo * kw_def
IdentifierInfo * kw_extends
IdentifierInfo * kw_base
IdentifierInfo * kw_coverpoint
IdentifierInfo * kw_begin_keywords
IdentifierInfo * kw_assert
IdentifierInfo * kw_async
IdentifierInfo * kw_CF_ENUM
IdentifierInfo * kw_qslots
IdentifierInfo * kw_null
IdentifierInfo * kw_nounconnected_drive
IdentifierInfo * kw_trireg
IdentifierInfo * kw_join_any
IdentifierInfo * kw_from
IdentifierInfo * kw_solve
IdentifierInfo * kw_abstract
IdentifierInfo * kw_default_nettype
IdentifierInfo * kw_task
IdentifierInfo * kw_ifnone
IdentifierInfo * kw_highz1
IdentifierInfo * kw_unique0
IdentifierInfo * kw_input
IdentifierInfo * kw_randc
IdentifierInfo * kw_always_ff
IdentifierInfo * kw_byte
IdentifierInfo * kw_medium
IdentifierInfo * kw_weak0
IdentifierInfo * kw_protect
IdentifierInfo * kw_undefineall
IdentifierInfo * kw_sequence
IdentifierInfo * kw_event
IdentifierInfo * kw_foreach
IdentifierInfo * kw_apostrophe
IdentifierInfo * kw_weak1
IdentifierInfo * kw_program
IdentifierInfo * kw_required
IdentifierInfo * kw_fixed
IdentifierInfo * kw_assign
IdentifierInfo * kw_dist
IdentifierInfo * kw_var
IdentifierInfo * kw_initial
IdentifierInfo * kw_macromodule
IdentifierInfo * kw_code
bool isVerilogKeywordSymbol(const FormatToken &Tok) const
IdentifierInfo * kw_ref
IdentifierInfo * kw_property
bool isVerilogBegin(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a block.
IdentifierInfo * kw_CF_OPTIONS
IdentifierInfo * kw_tagged
IdentifierInfo * kw_interface
IdentifierInfo * kw_before
IdentifierInfo * kw_local
IdentifierInfo * kw___has_include_next
IdentifierInfo * kw_tri
IdentifierInfo * kw_synchronized
IdentifierInfo * kw_params
IdentifierInfo * kw_endtable
IdentifierInfo * kw_endpackage
IdentifierInfo * kw_function
IdentifierInfo * kw_list
IdentifierInfo * kw_yield
IdentifierInfo * kw_automatic
IdentifierInfo * kw_declare
IdentifierInfo * kw_endcelldefine
IdentifierInfo * kw_checker
IdentifierInfo * kw_verilogHash
IdentifierInfo * kw_digest_decrypt_key
IdentifierInfo * kw_multiclass
IdentifierInfo * kw_internal
IdentifierInfo * kw_soft
IdentifierInfo * kw_returns
IdentifierInfo * kw_supply0
IdentifierInfo * kw_when
IdentifierInfo * kw_large
IdentifierInfo * kw_endclocking
IdentifierInfo * kw_endfunction
IdentifierInfo * kw_endprimitive
IdentifierInfo * kw_implicit
IdentifierInfo * kw_where
IdentifierInfo * kw_randcase
IdentifierInfo * kw_rand
IdentifierInfo * kw_NS_OPTIONS
IdentifierInfo * kw_triand
IdentifierInfo * kw_inside
IdentifierInfo * kw_defm
IdentifierInfo * kw_native
IdentifierInfo * kw_get
IdentifierInfo * kw_clocking
IdentifierInfo * kw_typeof
IdentifierInfo * kw_join_none
IdentifierInfo * kw_wand
IdentifierInfo * kw_endcase
IdentifierInfo * kw_intersect
IdentifierInfo * kw_include
IdentifierInfo * kw_tri0
IdentifierInfo * kw_then
IdentifierInfo * kw_primitive
IdentifierInfo * kw_record
IdentifierInfo * kw_string
IdentifierInfo * kw_begin
IdentifierInfo * kw_throws
IdentifierInfo * kw_slots
IdentifierInfo * kw_elsif
IdentifierInfo * kw_NS_ENUM
IdentifierInfo * kw_end
IdentifierInfo * kw_set
IdentifierInfo * kw_key_block
IdentifierInfo * kw_parameter
IdentifierInfo * kw_fork
IdentifierInfo * kw_endtask
IdentifierInfo * kw_NS_CLOSED_ENUM
IdentifierInfo * kw_mark
IdentifierInfo * kw_unconnected_drive
IdentifierInfo * kw_option
IdentifierInfo * kw_negedge
IdentifierInfo * kw_unique
IdentifierInfo * kw_wire
IdentifierInfo * kw_timescale
IdentifierInfo * kw_package
IdentifierInfo * kw_generate
IdentifierInfo * kw_constraint
IdentifierInfo * kw_endprogram
IdentifierInfo * kw_iff
IdentifierInfo * kw_delay_mode_unit
IdentifierInfo * kw_always_comb
IdentifierInfo * kw_module
IdentifierInfo * kw_stackalloc
IdentifierInfo * kw_bins
IdentifierInfo * kw_delay_mode_path
IdentifierInfo * kw_let
bool isWordLike(const FormatToken &Tok, bool IsVerilog=true) const
Returns true if Tok is a keyword or an identifier.
IdentifierInfo * kw_trior
IdentifierInfo * kw_qsignals
IdentifierInfo * kw_dump
IdentifierInfo * kw_specify
IdentifierInfo * kw_out
IdentifierInfo * kw_endproperty
IdentifierInfo * kw_endclass
IdentifierInfo * kw_digest_block
IdentifierInfo * kw_data_public_key
IdentifierInfo * kw_uint
IdentifierInfo * kw_internal_ident_after_define
IdentifierInfo * kw_randsequence
IdentifierInfo * kw_data_block
IdentifierInfo * kw_checked
IdentifierInfo * kw_key_public_key
IdentifierInfo * kw_endmodule
IdentifierInfo * kw_ulong
IdentifierInfo * kw_casex
IdentifierInfo * kw_defvar
IdentifierInfo * kw_scalared
IdentifierInfo * kw_strong1
IdentifierInfo * kw_wor
IdentifierInfo * kw_wait
IdentifierInfo * kw_delegate
IdentifierInfo * kw_ignore_bins
IdentifierInfo * kw_type
IdentifierInfo * kw_lock
IdentifierInfo * kw_small
IdentifierInfo * kw_cover
IdentifierInfo * kw_disable
IdentifierInfo * kw_always_latch
IdentifierInfo * kw_final
IdentifierInfo * kw_posedge
IdentifierInfo * kw_region
IdentifierInfo * kw_wildcard
IdentifierInfo * kw_with
IdentifierInfo * kw_bits
IdentifierInfo * kw_edge
IdentifierInfo * kw_forever
IdentifierInfo * kw_optional
IdentifierInfo * kw_default_trireg_strength
IdentifierInfo * kw_assume
IdentifierInfo * kw_dollar
IdentifierInfo * kw_verilogHashHash
IdentifierInfo * kw_casez
IdentifierInfo * kw_init
IdentifierInfo * kw_pure
IdentifierInfo * kw_dag
IdentifierInfo * kw_endgroup
IdentifierInfo * kw_delay_mode_zero
IdentifierInfo * kw_strong0
IdentifierInfo * kw_illegal_bins
IdentifierInfo * kw_priority
IdentifierInfo * kw_ushort
IdentifierInfo * kw_localparam
IdentifierInfo * kw_object
IdentifierInfo * kw_context
IdentifierInfo * kw_endsequence
IdentifierInfo * kw_inout
IdentifierInfo * kw_defset
IdentifierInfo * kw_end_keywords
IdentifierInfo * kw_matches
IdentifierInfo * kw_uwire
IdentifierInfo * kw_endspecify
IdentifierInfo * kw_data_decrypt_key
IdentifierInfo * kw_CF_CLOSED_ENUM
IdentifierInfo * kw_digest_public_key
IdentifierInfo * kw_sample
IdentifierInfo * kw_packed
IdentifierInfo * kw_unsafe
IdentifierInfo * kw_interconnect
IdentifierInfo * kw_tri1
IdentifierInfo * kw_pull1
IdentifierInfo * kw_NS_ERROR_ENUM
IdentifierInfo * kw_covergroup
IdentifierInfo * kw_repeat
bool isVerilogEnd(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that closes a block.
IdentifierInfo * kw_endinterface
IdentifierInfo * kw_highz0
IdentifierInfo * kw_repeated
IdentifierInfo * kw_endgenerate
IdentifierInfo * kw_bit
IdentifierInfo * kw_table
IdentifierInfo * kw_import
IdentifierInfo * kw_resetall
IdentifierInfo * kw_finally
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3890
A wrapper around a Token storing information about the whitespace characters preceding it.
unsigned NestingLevel
The nesting level of this token, i.e.
unsigned MustBreakBeforeFinalized
Whether MustBreakBefore is finalized during parsing and must not be reset between runs.
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
bool ArrayInitializerLineStart
This notes the start of the line of an array initializer.
bool Optional
Is optional and can be removed.
bool MacroParent
When macro expansion introduces nodes with children, those are marked as MacroParent.
bool is(ParameterPackingKind PPK) const
int Newlines
The number of newlines immediately before the Token after formatting.
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
bool closesScopeAfterBlock() const
prec::Level ForcedPrecedence
Used to set an operator precedence explicitly.
unsigned BindingStrength
The binding strength of a token.
unsigned StartsBinaryExpression
true if this token starts a binary expression, i.e.
void setPackingKind(ParameterPackingKind K)
unsigned ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
unsigned OperatorIndex
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
bool MightBeFunctionDeclParen
Might be function declaration open/closing paren.
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
unsigned ContinuesLineCommentSection
Does this line comment continue a line comment section?
unsigned CanBreakBefore
true if it is allowed to break before this token.
bool isNot(T Kind) const
StringRef TokenText
The raw text of the token.
unsigned LongestObjCSelectorName
If this is the first ObjC selector name in an ObjC method definition or call, this contains the lengt...
ParameterPackingKind getPackingKind() const
unsigned HasEnumTrailingCommaHandled
true if a comma has been inserted or removed after the token.
tok::TokenKind ParentBracket
If this is a bracket ("<", "(", "[" or "{"), contains the kind of the surrounding bracket.
unsigned LastNewlineOffset
The offset just past the last ' ' in this token's leading whitespace (relative to WhiteSpaceStart).
unsigned SplitPenalty
Penalty for inserting a line break before this token.
void setDecision(FormatDecision D)
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
std::optional< MacroExpansion > MacroCtx
BraceBlockKind getBlockKind() const
bool isNoneOf(Ts... Ks) const
FormatToken * Next
The next token in the unwrapped line.
unsigned IsMultiline
Whether the token text contains newlines (escaped or not).
unsigned EndsCppAttributeGroup
true if this token ends a group of C++ attributes.
unsigned NewlinesBefore
The number of newlines immediately before the Token.
void setBlockKind(BraceBlockKind BBK)
bool isIf(bool AllowConstexprMacro=true) const
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
unsigned MustBreakBefore
Whether there must be a line break before this token.
unsigned HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
unsigned PartOfMultiVariableDeclStmt
Is this token part of a DeclStmt defining multiple variables?
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
unsigned ObjCSelectorNameParts
If this is the first ObjC selector name in an ObjC method definition or call, this contains the numbe...
bool FirstAfterPPLine
Is the first token after a preprocessor line.
void setType(TokenType T)
bool HasFormFeedBefore
Has "\n\f\n" or "\n\f\r\n" before TokenText.
bool IsArrayInitializer
This starts an array initializer.
bool LBraceInserted
Whether a left brace was already inserted after this token when an earlier run was analyzed.
unsigned EndsBinaryExpression
true if this token ends a binary expression.
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
FormatDecision getDecision() const
bool is(tok::TokenKind Kind) const
unsigned LastLineColumnWidth
Contains the width in columns of the last line of a multi-line token.
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
unsigned BlockParameterCount
Number of parameters that are nested blocks, if this is "(", "[" or "<".
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
bool isOneOf(A K1, B K2) const
TokenType getType() const
Returns the token's type, e.g.
unsigned IsFirst
Indicates that this is the first token of the file.
unsigned AppliedIndentLevel
Block + continuation indent level, applied by the WhitespaceManager to this token.
unsigned IsUnterminatedLiteral
Set to true if this token is an unterminated literal.
unsigned ClosesRequiresClause
true if this is the last token within requires clause.
unsigned ParameterIndex
The 0-based index of the parameter/argument.
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
bool StartsColumn
The first token in set of column elements.
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
bool isLoop(const FormatStyle &Style) const
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
void overwriteFixedType(TokenType T)
FormatToken * Previous
The previous token in the unwrapped line.
void setFinalizedType(TokenType T)
Sets the type and also the finalized flag.
llvm::SmallVector< FormatToken *, 1 > ExpandedFrom
The stack of macro call identifier tokens this token was expanded from.
unsigned StartOfExpansion
The number of expansions of which this macro is the first entry.
MacroRole Role
The token's role in the macro expansion.
unsigned EndOfExpansion
The number of currently open expansions in ExpandedFrom this macro is the last token in.