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