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 
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
22 #include <memory>
23 #include <unordered_set>
24 
25 namespace clang {
26 namespace format {
27 
28 #define LIST_TOKEN_TYPES                                                       \
29   TYPE(ArrayInitializerLSquare)                                                \
30   TYPE(ArraySubscriptLSquare)                                                  \
31   TYPE(AttributeColon)                                                         \
32   TYPE(AttributeMacro)                                                         \
33   TYPE(AttributeParen)                                                         \
34   TYPE(AttributeSquare)                                                        \
35   TYPE(BinaryOperator)                                                         \
36   TYPE(BitFieldColon)                                                          \
37   TYPE(BlockComment)                                                           \
38   TYPE(BracedListLBrace)                                                       \
39   TYPE(CastRParen)                                                             \
40   TYPE(ClassLBrace)                                                            \
41   TYPE(CompoundRequirementLBrace)                                              \
42   TYPE(ConditionalExpr)                                                        \
43   TYPE(ConflictAlternative)                                                    \
44   TYPE(ConflictEnd)                                                            \
45   TYPE(ConflictStart)                                                          \
46   TYPE(CppCastLParen)                                                          \
47   TYPE(CtorInitializerColon)                                                   \
48   TYPE(CtorInitializerComma)                                                   \
49   TYPE(DesignatedInitializerLSquare)                                           \
50   TYPE(DesignatedInitializerPeriod)                                            \
51   TYPE(DictLiteral)                                                            \
52   TYPE(EnumLBrace)                                                             \
53   TYPE(FatArrow)                                                               \
54   TYPE(ForEachMacro)                                                           \
55   TYPE(FunctionAnnotationRParen)                                               \
56   TYPE(FunctionDeclarationName)                                                \
57   TYPE(FunctionLBrace)                                                         \
58   TYPE(FunctionLikeOrFreestandingMacro)                                        \
59   TYPE(FunctionTypeLParen)                                                     \
60   TYPE(IfMacro)                                                                \
61   TYPE(ImplicitStringLiteral)                                                  \
62   TYPE(InheritanceColon)                                                       \
63   TYPE(InheritanceComma)                                                       \
64   TYPE(InlineASMBrace)                                                         \
65   TYPE(InlineASMColon)                                                         \
66   TYPE(InlineASMSymbolicNameLSquare)                                           \
67   TYPE(JavaAnnotation)                                                         \
68   TYPE(JsComputedPropertyName)                                                 \
69   TYPE(JsExponentiation)                                                       \
70   TYPE(JsExponentiationEqual)                                                  \
71   TYPE(JsPipePipeEqual)                                                        \
72   TYPE(JsPrivateIdentifier)                                                    \
73   TYPE(JsTypeColon)                                                            \
74   TYPE(JsTypeOperator)                                                         \
75   TYPE(JsTypeOptionalQuestion)                                                 \
76   TYPE(JsAndAndEqual)                                                          \
77   TYPE(LambdaArrow)                                                            \
78   TYPE(LambdaLBrace)                                                           \
79   TYPE(LambdaLSquare)                                                          \
80   TYPE(LeadingJavaAnnotation)                                                  \
81   TYPE(LineComment)                                                            \
82   TYPE(MacroBlockBegin)                                                        \
83   TYPE(MacroBlockEnd)                                                          \
84   TYPE(ModulePartitionColon)                                                   \
85   TYPE(NamespaceMacro)                                                         \
86   TYPE(NonNullAssertion)                                                       \
87   TYPE(NullCoalescingEqual)                                                    \
88   TYPE(NullCoalescingOperator)                                                 \
89   TYPE(NullPropagatingOperator)                                                \
90   TYPE(ObjCBlockLBrace)                                                        \
91   TYPE(ObjCBlockLParen)                                                        \
92   TYPE(ObjCDecl)                                                               \
93   TYPE(ObjCForIn)                                                              \
94   TYPE(ObjCMethodExpr)                                                         \
95   TYPE(ObjCMethodSpecifier)                                                    \
96   TYPE(ObjCProperty)                                                           \
97   TYPE(ObjCStringLiteral)                                                      \
98   TYPE(OverloadedOperator)                                                     \
99   TYPE(OverloadedOperatorLParen)                                               \
100   TYPE(PointerOrReference)                                                     \
101   TYPE(PureVirtualSpecifier)                                                   \
102   TYPE(RangeBasedForLoopColon)                                                 \
103   TYPE(RecordLBrace)                                                           \
104   TYPE(RegexLiteral)                                                           \
105   TYPE(RequiresClause)                                                         \
106   TYPE(RequiresClauseInARequiresExpression)                                    \
107   TYPE(RequiresExpression)                                                     \
108   TYPE(RequiresExpressionLBrace)                                               \
109   TYPE(RequiresExpressionLParen)                                               \
110   TYPE(SelectorName)                                                           \
111   TYPE(StartOfName)                                                            \
112   TYPE(StatementAttributeLikeMacro)                                            \
113   TYPE(StatementMacro)                                                         \
114   TYPE(StructLBrace)                                                           \
115   TYPE(StructuredBindingLSquare)                                               \
116   TYPE(TemplateCloser)                                                         \
117   TYPE(TemplateOpener)                                                         \
118   TYPE(TemplateString)                                                         \
119   TYPE(ProtoExtensionLSquare)                                                  \
120   TYPE(TrailingAnnotation)                                                     \
121   TYPE(TrailingReturnArrow)                                                    \
122   TYPE(TrailingUnaryOperator)                                                  \
123   TYPE(TypeDeclarationParen)                                                   \
124   TYPE(TypenameMacro)                                                          \
125   TYPE(UnaryOperator)                                                          \
126   TYPE(UnionLBrace)                                                            \
127   TYPE(UntouchableMacroFunc)                                                   \
128   TYPE(CSharpStringLiteral)                                                    \
129   TYPE(CSharpNamedArgumentColon)                                               \
130   TYPE(CSharpNullable)                                                         \
131   TYPE(CSharpNullConditionalLSquare)                                           \
132   TYPE(CSharpGenericTypeConstraint)                                            \
133   TYPE(CSharpGenericTypeConstraintColon)                                       \
134   TYPE(CSharpGenericTypeConstraintComma)                                       \
135   TYPE(Unknown)
136 
137 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
138 /// template opener or binary operator.
139 enum TokenType : uint8_t {
140 #define TYPE(X) TT_##X,
141   LIST_TOKEN_TYPES
142 #undef TYPE
143       NUM_TOKEN_TYPES
144 };
145 
146 /// Determines the name of a token type.
147 const char *getTokenTypeName(TokenType Type);
148 
149 // Represents what type of block a set of braces open.
150 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
151 
152 // The packing kind of a function's parameters.
153 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
154 
155 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
156 
157 /// Roles a token can take in a configured macro expansion.
158 enum MacroRole {
159   /// The token was expanded from a macro argument when formatting the expanded
160   /// token sequence.
161   MR_ExpandedArg,
162   /// The token is part of a macro argument that was previously formatted as
163   /// expansion when formatting the unexpanded macro call.
164   MR_UnexpandedArg,
165   /// The token was expanded from a macro definition, and is not visible as part
166   /// of the macro call.
167   MR_Hidden,
168 };
169 
170 struct FormatToken;
171 
172 /// Contains information on the token's role in a macro expansion.
173 ///
174 /// Given the following definitions:
175 /// A(X) = [ X ]
176 /// B(X) = < X >
177 /// C(X) = X
178 ///
179 /// Consider the macro call:
180 /// A({B(C(C(x)))}) -> [{<x>}]
181 ///
182 /// In this case, the tokens of the unexpanded macro call will have the
183 /// following relevant entries in their macro context (note that formatting
184 /// the unexpanded macro call happens *after* formatting the expanded macro
185 /// call):
186 ///                   A( { B( C( C(x) ) ) } )
187 /// Role:             NN U NN NN NNUN N N U N  (N=None, U=UnexpandedArg)
188 ///
189 ///                   [  { <       x    > } ]
190 /// Role:             H  E H       E    H E H  (H=Hidden, E=ExpandedArg)
191 /// ExpandedFrom[0]:  A  A A       A    A A A
192 /// ExpandedFrom[1]:       B       B    B
193 /// ExpandedFrom[2]:               C
194 /// ExpandedFrom[3]:               C
195 /// StartOfExpansion: 1  0 1       2    0 0 0
196 /// EndOfExpansion:   0  0 0       2    1 0 1
197 struct MacroExpansion {
198   MacroExpansion(MacroRole Role) : Role(Role) {}
199 
200   /// The token's role in the macro expansion.
201   /// When formatting an expanded macro, all tokens that are part of macro
202   /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
203   /// the macro call will be MR_Hidden.
204   /// When formatting an unexpanded macro call, all tokens that are part of
205   /// macro arguments will be MR_UnexpandedArg.
206   MacroRole Role;
207 
208   /// The stack of macro call identifier tokens this token was expanded from.
209   llvm::SmallVector<FormatToken *, 1> ExpandedFrom;
210 
211   /// The number of expansions of which this macro is the first entry.
212   unsigned StartOfExpansion = 0;
213 
214   /// The number of currently open expansions in \c ExpandedFrom this macro is
215   /// the last token in.
216   unsigned EndOfExpansion = 0;
217 };
218 
219 class TokenRole;
220 class AnnotatedLine;
221 
222 /// A wrapper around a \c Token storing information about the
223 /// whitespace characters preceding it.
224 struct FormatToken {
225   FormatToken()
226       : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false),
227         MustBreakBefore(false), IsUnterminatedLiteral(false),
228         CanBreakBefore(false), ClosesTemplateDeclaration(false),
229         StartsBinaryExpression(false), EndsBinaryExpression(false),
230         PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false),
231         Finalized(false), ClosesRequiresClause(false), BlockKind(BK_Unknown),
232         Decision(FD_Unformatted), PackingKind(PPK_Inconclusive),
233         TypeIsFinalized(false), Type(TT_Unknown) {}
234 
235   /// The \c Token.
236   Token Tok;
237 
238   /// The raw text of the token.
239   ///
240   /// Contains the raw token text without leading whitespace and without leading
241   /// escaped newlines.
242   StringRef TokenText;
243 
244   /// A token can have a special role that can carry extra information
245   /// about the token's formatting.
246   /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
247   /// classes and make this a unique_ptr in the AnnotatedToken class.
248   std::shared_ptr<TokenRole> Role;
249 
250   /// The range of the whitespace immediately preceding the \c Token.
251   SourceRange WhitespaceRange;
252 
253   /// Whether there is at least one unescaped newline before the \c
254   /// Token.
255   unsigned HasUnescapedNewline : 1;
256 
257   /// Whether the token text contains newlines (escaped or not).
258   unsigned IsMultiline : 1;
259 
260   /// Indicates that this is the first token of the file.
261   unsigned IsFirst : 1;
262 
263   /// Whether there must be a line break before this token.
264   ///
265   /// This happens for example when a preprocessor directive ended directly
266   /// before the token.
267   unsigned MustBreakBefore : 1;
268 
269   /// Set to \c true if this token is an unterminated literal.
270   unsigned IsUnterminatedLiteral : 1;
271 
272   /// \c true if it is allowed to break before this token.
273   unsigned CanBreakBefore : 1;
274 
275   /// \c true if this is the ">" of "template<..>".
276   unsigned ClosesTemplateDeclaration : 1;
277 
278   /// \c true if this token starts a binary expression, i.e. has at least
279   /// one fake l_paren with a precedence greater than prec::Unknown.
280   unsigned StartsBinaryExpression : 1;
281   /// \c true if this token ends a binary expression.
282   unsigned EndsBinaryExpression : 1;
283 
284   /// Is this token part of a \c DeclStmt defining multiple variables?
285   ///
286   /// Only set if \c Type == \c TT_StartOfName.
287   unsigned PartOfMultiVariableDeclStmt : 1;
288 
289   /// Does this line comment continue a line comment section?
290   ///
291   /// Only set to true if \c Type == \c TT_LineComment.
292   unsigned ContinuesLineCommentSection : 1;
293 
294   /// If \c true, this token has been fully formatted (indented and
295   /// potentially re-formatted inside), and we do not allow further formatting
296   /// changes.
297   unsigned Finalized : 1;
298 
299   /// \c true if this is the last token within requires clause.
300   unsigned ClosesRequiresClause : 1;
301 
302 private:
303   /// Contains the kind of block if this token is a brace.
304   unsigned BlockKind : 2;
305 
306 public:
307   BraceBlockKind getBlockKind() const {
308     return static_cast<BraceBlockKind>(BlockKind);
309   }
310   void setBlockKind(BraceBlockKind BBK) {
311     BlockKind = BBK;
312     assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
313   }
314 
315 private:
316   /// Stores the formatting decision for the token once it was made.
317   unsigned Decision : 2;
318 
319 public:
320   FormatDecision getDecision() const {
321     return static_cast<FormatDecision>(Decision);
322   }
323   void setDecision(FormatDecision D) {
324     Decision = D;
325     assert(getDecision() == D && "FormatDecision overflow!");
326   }
327 
328 private:
329   /// If this is an opening parenthesis, how are the parameters packed?
330   unsigned PackingKind : 2;
331 
332 public:
333   ParameterPackingKind getPackingKind() const {
334     return static_cast<ParameterPackingKind>(PackingKind);
335   }
336   void setPackingKind(ParameterPackingKind K) {
337     PackingKind = K;
338     assert(getPackingKind() == K && "ParameterPackingKind overflow!");
339   }
340 
341 private:
342   unsigned TypeIsFinalized : 1;
343   TokenType Type;
344 
345 public:
346   /// Returns the token's type, e.g. whether "<" is a template opener or
347   /// binary operator.
348   TokenType getType() const { return Type; }
349   void setType(TokenType T) {
350     assert((!TypeIsFinalized || T == Type) &&
351            "Please use overwriteFixedType to change a fixed type.");
352     Type = T;
353   }
354   /// Sets the type and also the finalized flag. This prevents the type to be
355   /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
356   /// to another one please use overwriteFixedType, or even better remove the
357   /// need to reassign the type.
358   void setFinalizedType(TokenType T) {
359     Type = T;
360     TypeIsFinalized = true;
361   }
362   void overwriteFixedType(TokenType T) {
363     TypeIsFinalized = false;
364     setType(T);
365   }
366   bool isTypeFinalized() const { return TypeIsFinalized; }
367 
368   /// The number of newlines immediately before the \c Token.
369   ///
370   /// This can be used to determine what the user wrote in the original code
371   /// and thereby e.g. leave an empty line between two function definitions.
372   unsigned NewlinesBefore = 0;
373 
374   /// The offset just past the last '\n' in this token's leading
375   /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
376   unsigned LastNewlineOffset = 0;
377 
378   /// The width of the non-whitespace parts of the token (or its first
379   /// line for multi-line tokens) in columns.
380   /// We need this to correctly measure number of columns a token spans.
381   unsigned ColumnWidth = 0;
382 
383   /// Contains the width in columns of the last line of a multi-line
384   /// token.
385   unsigned LastLineColumnWidth = 0;
386 
387   /// The number of spaces that should be inserted before this token.
388   unsigned SpacesRequiredBefore = 0;
389 
390   /// Number of parameters, if this is "(", "[" or "<".
391   unsigned ParameterCount = 0;
392 
393   /// Number of parameters that are nested blocks,
394   /// if this is "(", "[" or "<".
395   unsigned BlockParameterCount = 0;
396 
397   /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
398   /// the surrounding bracket.
399   tok::TokenKind ParentBracket = tok::unknown;
400 
401   /// The total length of the unwrapped line up to and including this
402   /// token.
403   unsigned TotalLength = 0;
404 
405   /// The original 0-based column of this token, including expanded tabs.
406   /// The configured TabWidth is used as tab width.
407   unsigned OriginalColumn = 0;
408 
409   /// The length of following tokens until the next natural split point,
410   /// or the next token that can be broken.
411   unsigned UnbreakableTailLength = 0;
412 
413   // FIXME: Come up with a 'cleaner' concept.
414   /// The binding strength of a token. This is a combined value of
415   /// operator precedence, parenthesis nesting, etc.
416   unsigned BindingStrength = 0;
417 
418   /// The nesting level of this token, i.e. the number of surrounding (),
419   /// [], {} or <>.
420   unsigned NestingLevel = 0;
421 
422   /// The indent level of this token. Copied from the surrounding line.
423   unsigned IndentLevel = 0;
424 
425   /// Penalty for inserting a line break before this token.
426   unsigned SplitPenalty = 0;
427 
428   /// If this is the first ObjC selector name in an ObjC method
429   /// definition or call, this contains the length of the longest name.
430   ///
431   /// This being set to 0 means that the selectors should not be colon-aligned,
432   /// e.g. because several of them are block-type.
433   unsigned LongestObjCSelectorName = 0;
434 
435   /// If this is the first ObjC selector name in an ObjC method
436   /// definition or call, this contains the number of parts that the whole
437   /// selector consist of.
438   unsigned ObjCSelectorNameParts = 0;
439 
440   /// The 0-based index of the parameter/argument. For ObjC it is set
441   /// for the selector name token.
442   /// For now calculated only for ObjC.
443   unsigned ParameterIndex = 0;
444 
445   /// Stores the number of required fake parentheses and the
446   /// corresponding operator precedence.
447   ///
448   /// If multiple fake parentheses start at a token, this vector stores them in
449   /// reverse order, i.e. inner fake parenthesis first.
450   SmallVector<prec::Level, 4> FakeLParens;
451   /// Insert this many fake ) after this token for correct indentation.
452   unsigned FakeRParens = 0;
453 
454   /// If this is an operator (or "."/"->") in a sequence of operators
455   /// with the same precedence, contains the 0-based operator index.
456   unsigned OperatorIndex = 0;
457 
458   /// If this is an operator (or "."/"->") in a sequence of operators
459   /// with the same precedence, points to the next operator.
460   FormatToken *NextOperator = nullptr;
461 
462   /// If this is a bracket, this points to the matching one.
463   FormatToken *MatchingParen = nullptr;
464 
465   /// The previous token in the unwrapped line.
466   FormatToken *Previous = nullptr;
467 
468   /// The next token in the unwrapped line.
469   FormatToken *Next = nullptr;
470 
471   /// The first token in set of column elements.
472   bool StartsColumn = false;
473 
474   /// This notes the start of the line of an array initializer.
475   bool ArrayInitializerLineStart = false;
476 
477   /// This starts an array initializer.
478   bool IsArrayInitializer = false;
479 
480   /// Is optional and can be removed.
481   bool Optional = false;
482 
483   /// Number of optional braces to be inserted after this token:
484   ///   -1: a single left brace
485   ///    0: no braces
486   ///   >0: number of right braces
487   int8_t BraceCount = 0;
488 
489   /// If this token starts a block, this contains all the unwrapped lines
490   /// in it.
491   SmallVector<AnnotatedLine *, 1> Children;
492 
493   // Contains all attributes related to how this token takes part
494   // in a configured macro expansion.
495   llvm::Optional<MacroExpansion> MacroCtx;
496 
497   bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
498   bool is(TokenType TT) const { return getType() == TT; }
499   bool is(const IdentifierInfo *II) const {
500     return II && II == Tok.getIdentifierInfo();
501   }
502   bool is(tok::PPKeywordKind Kind) const {
503     return Tok.getIdentifierInfo() &&
504            Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
505   }
506   bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; }
507   bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; }
508 
509   template <typename A, typename B> bool isOneOf(A K1, B K2) const {
510     return is(K1) || is(K2);
511   }
512   template <typename A, typename B, typename... Ts>
513   bool isOneOf(A K1, B K2, Ts... Ks) const {
514     return is(K1) || isOneOf(K2, Ks...);
515   }
516   template <typename T> bool isNot(T Kind) const { return !is(Kind); }
517 
518   bool isIf(bool AllowConstexprMacro = true) const {
519     return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
520            (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
521   }
522 
523   bool closesScopeAfterBlock() const {
524     if (getBlockKind() == BK_Block)
525       return true;
526     if (closesScope())
527       return Previous->closesScopeAfterBlock();
528     return false;
529   }
530 
531   /// \c true if this token starts a sequence with the given tokens in order,
532   /// following the ``Next`` pointers, ignoring comments.
533   template <typename A, typename... Ts>
534   bool startsSequence(A K1, Ts... Tokens) const {
535     return startsSequenceInternal(K1, Tokens...);
536   }
537 
538   /// \c true if this token ends a sequence with the given tokens in order,
539   /// following the ``Previous`` pointers, ignoring comments.
540   /// For example, given tokens [T1, T2, T3], the function returns true if
541   /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
542   /// words, the tokens passed to this function need to the reverse of the
543   /// order the tokens appear in code.
544   template <typename A, typename... Ts>
545   bool endsSequence(A K1, Ts... Tokens) const {
546     return endsSequenceInternal(K1, Tokens...);
547   }
548 
549   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
550 
551   bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
552     return Tok.isObjCAtKeyword(Kind);
553   }
554 
555   bool isAccessSpecifier(bool ColonRequired = true) const {
556     return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
557            (!ColonRequired || (Next && Next->is(tok::colon)));
558   }
559 
560   bool canBePointerOrReferenceQualifier() const {
561     return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
562                    tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable,
563                    tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64,
564                    TT_AttributeMacro);
565   }
566 
567   /// Determine whether the token is a simple-type-specifier.
568   LLVM_NODISCARD bool isSimpleTypeSpecifier() const;
569 
570   LLVM_NODISCARD bool isTypeOrIdentifier() const;
571 
572   bool isObjCAccessSpecifier() const {
573     return is(tok::at) && Next &&
574            (Next->isObjCAtKeyword(tok::objc_public) ||
575             Next->isObjCAtKeyword(tok::objc_protected) ||
576             Next->isObjCAtKeyword(tok::objc_package) ||
577             Next->isObjCAtKeyword(tok::objc_private));
578   }
579 
580   /// Returns whether \p Tok is ([{ or an opening < of a template or in
581   /// protos.
582   bool opensScope() const {
583     if (is(TT_TemplateString) && TokenText.endswith("${"))
584       return true;
585     if (is(TT_DictLiteral) && is(tok::less))
586       return true;
587     return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
588                    TT_TemplateOpener);
589   }
590   /// Returns whether \p Tok is )]} or a closing > of a template or in
591   /// protos.
592   bool closesScope() const {
593     if (is(TT_TemplateString) && TokenText.startswith("}"))
594       return true;
595     if (is(TT_DictLiteral) && is(tok::greater))
596       return true;
597     return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
598                    TT_TemplateCloser);
599   }
600 
601   /// Returns \c true if this is a "." or "->" accessing a member.
602   bool isMemberAccess() const {
603     return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
604            !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
605                     TT_LambdaArrow, TT_LeadingJavaAnnotation);
606   }
607 
608   bool isUnaryOperator() const {
609     switch (Tok.getKind()) {
610     case tok::plus:
611     case tok::plusplus:
612     case tok::minus:
613     case tok::minusminus:
614     case tok::exclaim:
615     case tok::tilde:
616     case tok::kw_sizeof:
617     case tok::kw_alignof:
618       return true;
619     default:
620       return false;
621     }
622   }
623 
624   bool isBinaryOperator() const {
625     // Comma is a binary operator, but does not behave as such wrt. formatting.
626     return getPrecedence() > prec::Comma;
627   }
628 
629   bool isTrailingComment() const {
630     return is(tok::comment) &&
631            (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
632   }
633 
634   /// Returns \c true if this is a keyword that can be used
635   /// like a function call (e.g. sizeof, typeid, ...).
636   bool isFunctionLikeKeyword() const {
637     switch (Tok.getKind()) {
638     case tok::kw_throw:
639     case tok::kw_typeid:
640     case tok::kw_return:
641     case tok::kw_sizeof:
642     case tok::kw_alignof:
643     case tok::kw_alignas:
644     case tok::kw_decltype:
645     case tok::kw_noexcept:
646     case tok::kw_static_assert:
647     case tok::kw__Atomic:
648     case tok::kw___attribute:
649     case tok::kw___underlying_type:
650     case tok::kw_requires:
651       return true;
652     default:
653       return false;
654     }
655   }
656 
657   /// Returns \c true if this is a string literal that's like a label,
658   /// e.g. ends with "=" or ":".
659   bool isLabelString() const {
660     if (!is(tok::string_literal))
661       return false;
662     StringRef Content = TokenText;
663     if (Content.startswith("\"") || Content.startswith("'"))
664       Content = Content.drop_front(1);
665     if (Content.endswith("\"") || Content.endswith("'"))
666       Content = Content.drop_back(1);
667     Content = Content.trim();
668     return Content.size() > 1 &&
669            (Content.back() == ':' || Content.back() == '=');
670   }
671 
672   /// Returns actual token start location without leading escaped
673   /// newlines and whitespace.
674   ///
675   /// This can be different to Tok.getLocation(), which includes leading escaped
676   /// newlines.
677   SourceLocation getStartOfNonWhitespace() const {
678     return WhitespaceRange.getEnd();
679   }
680 
681   /// Returns \c true if the range of whitespace immediately preceding the \c
682   /// Token is not empty.
683   bool hasWhitespaceBefore() const {
684     return WhitespaceRange.getBegin() != WhitespaceRange.getEnd();
685   }
686 
687   prec::Level getPrecedence() const {
688     return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
689                               /*CPlusPlus11=*/true);
690   }
691 
692   /// Returns the previous token ignoring comments.
693   LLVM_NODISCARD FormatToken *getPreviousNonComment() const {
694     FormatToken *Tok = Previous;
695     while (Tok && Tok->is(tok::comment))
696       Tok = Tok->Previous;
697     return Tok;
698   }
699 
700   /// Returns the next token ignoring comments.
701   LLVM_NODISCARD const FormatToken *getNextNonComment() const {
702     const FormatToken *Tok = Next;
703     while (Tok && Tok->is(tok::comment))
704       Tok = Tok->Next;
705     return Tok;
706   }
707 
708   /// Returns \c true if this tokens starts a block-type list, i.e. a
709   /// list that should be indented with a block indent.
710   LLVM_NODISCARD bool opensBlockOrBlockTypeList(const FormatStyle &Style) const;
711 
712   /// Returns whether the token is the left square bracket of a C++
713   /// structured binding declaration.
714   bool isCppStructuredBinding(const FormatStyle &Style) const {
715     if (!Style.isCpp() || isNot(tok::l_square))
716       return false;
717     const FormatToken *T = this;
718     do {
719       T = T->getPreviousNonComment();
720     } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
721                              tok::ampamp));
722     return T && T->is(tok::kw_auto);
723   }
724 
725   /// Same as opensBlockOrBlockTypeList, but for the closing token.
726   bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
727     if (is(TT_TemplateString) && closesScope())
728       return true;
729     return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
730   }
731 
732   /// Return the actual namespace token, if this token starts a namespace
733   /// block.
734   const FormatToken *getNamespaceToken() const {
735     const FormatToken *NamespaceTok = this;
736     if (is(tok::comment))
737       NamespaceTok = NamespaceTok->getNextNonComment();
738     // Detect "(inline|export)? namespace" in the beginning of a line.
739     if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
740       NamespaceTok = NamespaceTok->getNextNonComment();
741     return NamespaceTok &&
742                    NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
743                ? NamespaceTok
744                : nullptr;
745   }
746 
747   void copyFrom(const FormatToken &Tok) { *this = Tok; }
748 
749 private:
750   // Only allow copying via the explicit copyFrom method.
751   FormatToken(const FormatToken &) = delete;
752   FormatToken &operator=(const FormatToken &) = default;
753 
754   template <typename A, typename... Ts>
755   bool startsSequenceInternal(A K1, Ts... Tokens) const {
756     if (is(tok::comment) && Next)
757       return Next->startsSequenceInternal(K1, Tokens...);
758     return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
759   }
760 
761   template <typename A> bool startsSequenceInternal(A K1) const {
762     if (is(tok::comment) && Next)
763       return Next->startsSequenceInternal(K1);
764     return is(K1);
765   }
766 
767   template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
768     if (is(tok::comment) && Previous)
769       return Previous->endsSequenceInternal(K1);
770     return is(K1);
771   }
772 
773   template <typename A, typename... Ts>
774   bool endsSequenceInternal(A K1, Ts... Tokens) const {
775     if (is(tok::comment) && Previous)
776       return Previous->endsSequenceInternal(K1, Tokens...);
777     return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
778   }
779 };
780 
781 class ContinuationIndenter;
782 struct LineState;
783 
784 class TokenRole {
785 public:
786   TokenRole(const FormatStyle &Style) : Style(Style) {}
787   virtual ~TokenRole();
788 
789   /// After the \c TokenAnnotator has finished annotating all the tokens,
790   /// this function precomputes required information for formatting.
791   virtual void precomputeFormattingInfos(const FormatToken *Token);
792 
793   /// Apply the special formatting that the given role demands.
794   ///
795   /// Assumes that the token having this role is already formatted.
796   ///
797   /// Continues formatting from \p State leaving indentation to \p Indenter and
798   /// returns the total penalty that this formatting incurs.
799   virtual unsigned formatFromToken(LineState &State,
800                                    ContinuationIndenter *Indenter,
801                                    bool DryRun) {
802     return 0;
803   }
804 
805   /// Same as \c formatFromToken, but assumes that the first token has
806   /// already been set thereby deciding on the first line break.
807   virtual unsigned formatAfterToken(LineState &State,
808                                     ContinuationIndenter *Indenter,
809                                     bool DryRun) {
810     return 0;
811   }
812 
813   /// Notifies the \c Role that a comma was found.
814   virtual void CommaFound(const FormatToken *Token) {}
815 
816   virtual const FormatToken *lastComma() { return nullptr; }
817 
818 protected:
819   const FormatStyle &Style;
820 };
821 
822 class CommaSeparatedList : public TokenRole {
823 public:
824   CommaSeparatedList(const FormatStyle &Style)
825       : TokenRole(Style), HasNestedBracedList(false) {}
826 
827   void precomputeFormattingInfos(const FormatToken *Token) override;
828 
829   unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
830                             bool DryRun) override;
831 
832   unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
833                            bool DryRun) override;
834 
835   /// Adds \p Token as the next comma to the \c CommaSeparated list.
836   void CommaFound(const FormatToken *Token) override {
837     Commas.push_back(Token);
838   }
839 
840   const FormatToken *lastComma() override {
841     if (Commas.empty())
842       return nullptr;
843     return Commas.back();
844   }
845 
846 private:
847   /// A struct that holds information on how to format a given list with
848   /// a specific number of columns.
849   struct ColumnFormat {
850     /// The number of columns to use.
851     unsigned Columns;
852 
853     /// The total width in characters.
854     unsigned TotalWidth;
855 
856     /// The number of lines required for this format.
857     unsigned LineCount;
858 
859     /// The size of each column in characters.
860     SmallVector<unsigned, 8> ColumnSizes;
861   };
862 
863   /// Calculate which \c ColumnFormat fits best into
864   /// \p RemainingCharacters.
865   const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
866 
867   /// The ordered \c FormatTokens making up the commas of this list.
868   SmallVector<const FormatToken *, 8> Commas;
869 
870   /// The length of each of the list's items in characters including the
871   /// trailing comma.
872   SmallVector<unsigned, 8> ItemLengths;
873 
874   /// Precomputed formats that can be used for this list.
875   SmallVector<ColumnFormat, 4> Formats;
876 
877   bool HasNestedBracedList;
878 };
879 
880 /// Encapsulates keywords that are context sensitive or for languages not
881 /// properly supported by Clang's lexer.
882 struct AdditionalKeywords {
883   AdditionalKeywords(IdentifierTable &IdentTable) {
884     kw_final = &IdentTable.get("final");
885     kw_override = &IdentTable.get("override");
886     kw_in = &IdentTable.get("in");
887     kw_of = &IdentTable.get("of");
888     kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
889     kw_CF_ENUM = &IdentTable.get("CF_ENUM");
890     kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
891     kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
892     kw_NS_ENUM = &IdentTable.get("NS_ENUM");
893     kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
894 
895     kw_as = &IdentTable.get("as");
896     kw_async = &IdentTable.get("async");
897     kw_await = &IdentTable.get("await");
898     kw_declare = &IdentTable.get("declare");
899     kw_finally = &IdentTable.get("finally");
900     kw_from = &IdentTable.get("from");
901     kw_function = &IdentTable.get("function");
902     kw_get = &IdentTable.get("get");
903     kw_import = &IdentTable.get("import");
904     kw_infer = &IdentTable.get("infer");
905     kw_is = &IdentTable.get("is");
906     kw_let = &IdentTable.get("let");
907     kw_module = &IdentTable.get("module");
908     kw_readonly = &IdentTable.get("readonly");
909     kw_set = &IdentTable.get("set");
910     kw_type = &IdentTable.get("type");
911     kw_typeof = &IdentTable.get("typeof");
912     kw_var = &IdentTable.get("var");
913     kw_yield = &IdentTable.get("yield");
914 
915     kw_abstract = &IdentTable.get("abstract");
916     kw_assert = &IdentTable.get("assert");
917     kw_extends = &IdentTable.get("extends");
918     kw_implements = &IdentTable.get("implements");
919     kw_instanceof = &IdentTable.get("instanceof");
920     kw_interface = &IdentTable.get("interface");
921     kw_native = &IdentTable.get("native");
922     kw_package = &IdentTable.get("package");
923     kw_synchronized = &IdentTable.get("synchronized");
924     kw_throws = &IdentTable.get("throws");
925     kw___except = &IdentTable.get("__except");
926     kw___has_include = &IdentTable.get("__has_include");
927     kw___has_include_next = &IdentTable.get("__has_include_next");
928 
929     kw_mark = &IdentTable.get("mark");
930 
931     kw_extend = &IdentTable.get("extend");
932     kw_option = &IdentTable.get("option");
933     kw_optional = &IdentTable.get("optional");
934     kw_repeated = &IdentTable.get("repeated");
935     kw_required = &IdentTable.get("required");
936     kw_returns = &IdentTable.get("returns");
937 
938     kw_signals = &IdentTable.get("signals");
939     kw_qsignals = &IdentTable.get("Q_SIGNALS");
940     kw_slots = &IdentTable.get("slots");
941     kw_qslots = &IdentTable.get("Q_SLOTS");
942 
943     // For internal clang-format use.
944     kw_internal_ident_after_define =
945         &IdentTable.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
946 
947     // C# keywords
948     kw_dollar = &IdentTable.get("dollar");
949     kw_base = &IdentTable.get("base");
950     kw_byte = &IdentTable.get("byte");
951     kw_checked = &IdentTable.get("checked");
952     kw_decimal = &IdentTable.get("decimal");
953     kw_delegate = &IdentTable.get("delegate");
954     kw_event = &IdentTable.get("event");
955     kw_fixed = &IdentTable.get("fixed");
956     kw_foreach = &IdentTable.get("foreach");
957     kw_init = &IdentTable.get("init");
958     kw_implicit = &IdentTable.get("implicit");
959     kw_internal = &IdentTable.get("internal");
960     kw_lock = &IdentTable.get("lock");
961     kw_null = &IdentTable.get("null");
962     kw_object = &IdentTable.get("object");
963     kw_out = &IdentTable.get("out");
964     kw_params = &IdentTable.get("params");
965     kw_ref = &IdentTable.get("ref");
966     kw_string = &IdentTable.get("string");
967     kw_stackalloc = &IdentTable.get("stackalloc");
968     kw_sbyte = &IdentTable.get("sbyte");
969     kw_sealed = &IdentTable.get("sealed");
970     kw_uint = &IdentTable.get("uint");
971     kw_ulong = &IdentTable.get("ulong");
972     kw_unchecked = &IdentTable.get("unchecked");
973     kw_unsafe = &IdentTable.get("unsafe");
974     kw_ushort = &IdentTable.get("ushort");
975     kw_when = &IdentTable.get("when");
976     kw_where = &IdentTable.get("where");
977 
978     // Keep this at the end of the constructor to make sure everything here
979     // is
980     // already initialized.
981     JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
982         {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
983          kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override,
984          kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield,
985          // Keywords from the Java section.
986          kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
987 
988     CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
989         {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event,
990          kw_fixed, kw_foreach, kw_implicit, kw_in, kw_init, kw_interface,
991          kw_internal, kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override,
992          kw_params, kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte,
993          kw_sealed, kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort,
994          kw_when, kw_where,
995          // Keywords from the JavaScript section.
996          kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
997          kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
998          kw_set, kw_type, kw_typeof, kw_var, kw_yield,
999          // Keywords from the Java section.
1000          kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
1001   }
1002 
1003   // Context sensitive keywords.
1004   IdentifierInfo *kw_final;
1005   IdentifierInfo *kw_override;
1006   IdentifierInfo *kw_in;
1007   IdentifierInfo *kw_of;
1008   IdentifierInfo *kw_CF_CLOSED_ENUM;
1009   IdentifierInfo *kw_CF_ENUM;
1010   IdentifierInfo *kw_CF_OPTIONS;
1011   IdentifierInfo *kw_NS_CLOSED_ENUM;
1012   IdentifierInfo *kw_NS_ENUM;
1013   IdentifierInfo *kw_NS_OPTIONS;
1014   IdentifierInfo *kw___except;
1015   IdentifierInfo *kw___has_include;
1016   IdentifierInfo *kw___has_include_next;
1017 
1018   // JavaScript keywords.
1019   IdentifierInfo *kw_as;
1020   IdentifierInfo *kw_async;
1021   IdentifierInfo *kw_await;
1022   IdentifierInfo *kw_declare;
1023   IdentifierInfo *kw_finally;
1024   IdentifierInfo *kw_from;
1025   IdentifierInfo *kw_function;
1026   IdentifierInfo *kw_get;
1027   IdentifierInfo *kw_import;
1028   IdentifierInfo *kw_infer;
1029   IdentifierInfo *kw_is;
1030   IdentifierInfo *kw_let;
1031   IdentifierInfo *kw_module;
1032   IdentifierInfo *kw_readonly;
1033   IdentifierInfo *kw_set;
1034   IdentifierInfo *kw_type;
1035   IdentifierInfo *kw_typeof;
1036   IdentifierInfo *kw_var;
1037   IdentifierInfo *kw_yield;
1038 
1039   // Java keywords.
1040   IdentifierInfo *kw_abstract;
1041   IdentifierInfo *kw_assert;
1042   IdentifierInfo *kw_extends;
1043   IdentifierInfo *kw_implements;
1044   IdentifierInfo *kw_instanceof;
1045   IdentifierInfo *kw_interface;
1046   IdentifierInfo *kw_native;
1047   IdentifierInfo *kw_package;
1048   IdentifierInfo *kw_synchronized;
1049   IdentifierInfo *kw_throws;
1050 
1051   // Pragma keywords.
1052   IdentifierInfo *kw_mark;
1053 
1054   // Proto keywords.
1055   IdentifierInfo *kw_extend;
1056   IdentifierInfo *kw_option;
1057   IdentifierInfo *kw_optional;
1058   IdentifierInfo *kw_repeated;
1059   IdentifierInfo *kw_required;
1060   IdentifierInfo *kw_returns;
1061 
1062   // QT keywords.
1063   IdentifierInfo *kw_signals;
1064   IdentifierInfo *kw_qsignals;
1065   IdentifierInfo *kw_slots;
1066   IdentifierInfo *kw_qslots;
1067 
1068   // For internal use by clang-format.
1069   IdentifierInfo *kw_internal_ident_after_define;
1070 
1071   // C# keywords
1072   IdentifierInfo *kw_dollar;
1073   IdentifierInfo *kw_base;
1074   IdentifierInfo *kw_byte;
1075   IdentifierInfo *kw_checked;
1076   IdentifierInfo *kw_decimal;
1077   IdentifierInfo *kw_delegate;
1078   IdentifierInfo *kw_event;
1079   IdentifierInfo *kw_fixed;
1080   IdentifierInfo *kw_foreach;
1081   IdentifierInfo *kw_implicit;
1082   IdentifierInfo *kw_init;
1083   IdentifierInfo *kw_internal;
1084 
1085   IdentifierInfo *kw_lock;
1086   IdentifierInfo *kw_null;
1087   IdentifierInfo *kw_object;
1088   IdentifierInfo *kw_out;
1089 
1090   IdentifierInfo *kw_params;
1091 
1092   IdentifierInfo *kw_ref;
1093   IdentifierInfo *kw_string;
1094   IdentifierInfo *kw_stackalloc;
1095   IdentifierInfo *kw_sbyte;
1096   IdentifierInfo *kw_sealed;
1097   IdentifierInfo *kw_uint;
1098   IdentifierInfo *kw_ulong;
1099   IdentifierInfo *kw_unchecked;
1100   IdentifierInfo *kw_unsafe;
1101   IdentifierInfo *kw_ushort;
1102   IdentifierInfo *kw_when;
1103   IdentifierInfo *kw_where;
1104 
1105   /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1106   /// \c false if it is a keyword or a pseudo keyword.
1107   /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1108   // but also for IdentifierName tokens (aka pseudo-keywords), such as
1109   // ``yield``.
1110   bool IsJavaScriptIdentifier(const FormatToken &Tok,
1111                               bool AcceptIdentifierName = true) const {
1112     // Based on the list of JavaScript & TypeScript keywords here:
1113     // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1114     switch (Tok.Tok.getKind()) {
1115     case tok::kw_break:
1116     case tok::kw_case:
1117     case tok::kw_catch:
1118     case tok::kw_class:
1119     case tok::kw_continue:
1120     case tok::kw_const:
1121     case tok::kw_default:
1122     case tok::kw_delete:
1123     case tok::kw_do:
1124     case tok::kw_else:
1125     case tok::kw_enum:
1126     case tok::kw_export:
1127     case tok::kw_false:
1128     case tok::kw_for:
1129     case tok::kw_if:
1130     case tok::kw_import:
1131     case tok::kw_module:
1132     case tok::kw_new:
1133     case tok::kw_private:
1134     case tok::kw_protected:
1135     case tok::kw_public:
1136     case tok::kw_return:
1137     case tok::kw_static:
1138     case tok::kw_switch:
1139     case tok::kw_this:
1140     case tok::kw_throw:
1141     case tok::kw_true:
1142     case tok::kw_try:
1143     case tok::kw_typeof:
1144     case tok::kw_void:
1145     case tok::kw_while:
1146       // These are JS keywords that are lexed by LLVM/clang as keywords.
1147       return false;
1148     case tok::identifier: {
1149       // For identifiers, make sure they are true identifiers, excluding the
1150       // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1151       bool IsPseudoKeyword =
1152           JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1153           JsExtraKeywords.end();
1154       return AcceptIdentifierName || !IsPseudoKeyword;
1155     }
1156     default:
1157       // Other keywords are handled in the switch below, to avoid problems due
1158       // to duplicate case labels when using the #include trick.
1159       break;
1160     }
1161 
1162     switch (Tok.Tok.getKind()) {
1163       // Handle C++ keywords not included above: these are all JS identifiers.
1164 #define KEYWORD(X, Y) case tok::kw_##X:
1165 #include "clang/Basic/TokenKinds.def"
1166       // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1167       // TokenKinds.def
1168       return true;
1169     default:
1170       // All other tokens (punctuation etc) are not JS identifiers.
1171       return false;
1172     }
1173   }
1174 
1175   /// Returns \c true if \p Tok is a C# keyword, returns
1176   /// \c false if it is a anything else.
1177   bool isCSharpKeyword(const FormatToken &Tok) const {
1178     switch (Tok.Tok.getKind()) {
1179     case tok::kw_bool:
1180     case tok::kw_break:
1181     case tok::kw_case:
1182     case tok::kw_catch:
1183     case tok::kw_char:
1184     case tok::kw_class:
1185     case tok::kw_const:
1186     case tok::kw_continue:
1187     case tok::kw_default:
1188     case tok::kw_do:
1189     case tok::kw_double:
1190     case tok::kw_else:
1191     case tok::kw_enum:
1192     case tok::kw_explicit:
1193     case tok::kw_extern:
1194     case tok::kw_false:
1195     case tok::kw_float:
1196     case tok::kw_for:
1197     case tok::kw_goto:
1198     case tok::kw_if:
1199     case tok::kw_int:
1200     case tok::kw_long:
1201     case tok::kw_namespace:
1202     case tok::kw_new:
1203     case tok::kw_operator:
1204     case tok::kw_private:
1205     case tok::kw_protected:
1206     case tok::kw_public:
1207     case tok::kw_return:
1208     case tok::kw_short:
1209     case tok::kw_sizeof:
1210     case tok::kw_static:
1211     case tok::kw_struct:
1212     case tok::kw_switch:
1213     case tok::kw_this:
1214     case tok::kw_throw:
1215     case tok::kw_true:
1216     case tok::kw_try:
1217     case tok::kw_typeof:
1218     case tok::kw_using:
1219     case tok::kw_virtual:
1220     case tok::kw_void:
1221     case tok::kw_volatile:
1222     case tok::kw_while:
1223       return true;
1224     default:
1225       return Tok.is(tok::identifier) &&
1226              CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1227                  CSharpExtraKeywords.end();
1228     }
1229   }
1230 
1231 private:
1232   /// The JavaScript keywords beyond the C++ keyword set.
1233   std::unordered_set<IdentifierInfo *> JsExtraKeywords;
1234 
1235   /// The C# keywords beyond the C++ keyword set
1236   std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
1237 };
1238 
1239 } // namespace format
1240 } // namespace clang
1241 
1242 #endif
1243