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