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