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