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