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(JavaAnnotation)                                                         \
58   TYPE(JsComputedPropertyName)                                                 \
59   TYPE(JsExponentiation)                                                       \
60   TYPE(JsExponentiationEqual)                                                  \
61   TYPE(JsFatArrow)                                                             \
62   TYPE(JsNonNullAssertion)                                                     \
63   TYPE(JsTypeColon)                                                            \
64   TYPE(JsTypeOperator)                                                         \
65   TYPE(JsTypeOptionalQuestion)                                                 \
66   TYPE(LambdaArrow)                                                            \
67   TYPE(LambdaLSquare)                                                          \
68   TYPE(LeadingJavaAnnotation)                                                  \
69   TYPE(LineComment)                                                            \
70   TYPE(MacroBlockBegin)                                                        \
71   TYPE(MacroBlockEnd)                                                          \
72   TYPE(ObjCBlockLBrace)                                                        \
73   TYPE(ObjCBlockLParen)                                                        \
74   TYPE(ObjCDecl)                                                               \
75   TYPE(ObjCForIn)                                                              \
76   TYPE(ObjCMethodExpr)                                                         \
77   TYPE(ObjCMethodSpecifier)                                                    \
78   TYPE(ObjCProperty)                                                           \
79   TYPE(ObjCStringLiteral)                                                      \
80   TYPE(OverloadedOperator)                                                     \
81   TYPE(OverloadedOperatorLParen)                                               \
82   TYPE(PointerOrReference)                                                     \
83   TYPE(PureVirtualSpecifier)                                                   \
84   TYPE(RangeBasedForLoopColon)                                                 \
85   TYPE(RegexLiteral)                                                           \
86   TYPE(SelectorName)                                                           \
87   TYPE(StartOfName)                                                            \
88   TYPE(StatementMacro)                                                         \
89   TYPE(StructuredBindingLSquare)                                               \
90   TYPE(TemplateCloser)                                                         \
91   TYPE(TemplateOpener)                                                         \
92   TYPE(TemplateString)                                                         \
93   TYPE(ProtoExtensionLSquare)                                                  \
94   TYPE(TrailingAnnotation)                                                     \
95   TYPE(TrailingReturnArrow)                                                    \
96   TYPE(TrailingUnaryOperator)                                                  \
97   TYPE(UnaryOperator)                                                          \
98   TYPE(Unknown)
99 
100 enum TokenType {
101 #define TYPE(X) TT_##X,
102   LIST_TOKEN_TYPES
103 #undef TYPE
104       NUM_TOKEN_TYPES
105 };
106 
107 /// Determines the name of a token type.
108 const char *getTokenTypeName(TokenType Type);
109 
110 // Represents what type of block a set of braces open.
111 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
112 
113 // The packing kind of a function's parameters.
114 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
115 
116 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
117 
118 class TokenRole;
119 class AnnotatedLine;
120 
121 /// A wrapper around a \c Token storing information about the
122 /// whitespace characters preceding it.
123 struct FormatToken {
124   FormatToken() {}
125 
126   /// The \c Token.
127   Token Tok;
128 
129   /// The number of newlines immediately before the \c Token.
130   ///
131   /// This can be used to determine what the user wrote in the original code
132   /// and thereby e.g. leave an empty line between two function definitions.
133   unsigned NewlinesBefore = 0;
134 
135   /// Whether there is at least one unescaped newline before the \c
136   /// Token.
137   bool HasUnescapedNewline = false;
138 
139   /// The range of the whitespace immediately preceding the \c Token.
140   SourceRange WhitespaceRange;
141 
142   /// The offset just past the last '\n' in this token's leading
143   /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
144   unsigned LastNewlineOffset = 0;
145 
146   /// The width of the non-whitespace parts of the token (or its first
147   /// line for multi-line tokens) in columns.
148   /// We need this to correctly measure number of columns a token spans.
149   unsigned ColumnWidth = 0;
150 
151   /// Contains the width in columns of the last line of a multi-line
152   /// token.
153   unsigned LastLineColumnWidth = 0;
154 
155   /// Whether the token text contains newlines (escaped or not).
156   bool IsMultiline = false;
157 
158   /// Indicates that this is the first token of the file.
159   bool IsFirst = false;
160 
161   /// Whether there must be a line break before this token.
162   ///
163   /// This happens for example when a preprocessor directive ended directly
164   /// before the token.
165   bool MustBreakBefore = false;
166 
167   /// The raw text of the token.
168   ///
169   /// Contains the raw token text without leading whitespace and without leading
170   /// escaped newlines.
171   StringRef TokenText;
172 
173   /// Set to \c true if this token is an unterminated literal.
174   bool IsUnterminatedLiteral = 0;
175 
176   /// Contains the kind of block if this token is a brace.
177   BraceBlockKind BlockKind = BK_Unknown;
178 
179   TokenType Type = TT_Unknown;
180 
181   /// The number of spaces that should be inserted before this token.
182   unsigned SpacesRequiredBefore = 0;
183 
184   /// \c true if it is allowed to break before this token.
185   bool CanBreakBefore = false;
186 
187   /// \c true if this is the ">" of "template<..>".
188   bool ClosesTemplateDeclaration = false;
189 
190   /// Number of parameters, if this is "(", "[" or "<".
191   unsigned ParameterCount = 0;
192 
193   /// Number of parameters that are nested blocks,
194   /// if this is "(", "[" or "<".
195   unsigned BlockParameterCount = 0;
196 
197   /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
198   /// the surrounding bracket.
199   tok::TokenKind ParentBracket = tok::unknown;
200 
201   /// A token can have a special role that can carry extra information
202   /// about the token's formatting.
203   std::unique_ptr<TokenRole> Role;
204 
205   /// If this is an opening parenthesis, how are the parameters packed?
206   ParameterPackingKind PackingKind = PPK_Inconclusive;
207 
208   /// The total length of the unwrapped line up to and including this
209   /// token.
210   unsigned TotalLength = 0;
211 
212   /// The original 0-based column of this token, including expanded tabs.
213   /// The configured TabWidth is used as tab width.
214   unsigned OriginalColumn = 0;
215 
216   /// The length of following tokens until the next natural split point,
217   /// or the next token that can be broken.
218   unsigned UnbreakableTailLength = 0;
219 
220   // FIXME: Come up with a 'cleaner' concept.
221   /// The binding strength of a token. This is a combined value of
222   /// operator precedence, parenthesis nesting, etc.
223   unsigned BindingStrength = 0;
224 
225   /// The nesting level of this token, i.e. the number of surrounding (),
226   /// [], {} or <>.
227   unsigned NestingLevel = 0;
228 
229   /// The indent level of this token. Copied from the surrounding line.
230   unsigned IndentLevel = 0;
231 
232   /// Penalty for inserting a line break before this token.
233   unsigned SplitPenalty = 0;
234 
235   /// If this is the first ObjC selector name in an ObjC method
236   /// definition or call, this contains the length of the longest name.
237   ///
238   /// This being set to 0 means that the selectors should not be colon-aligned,
239   /// e.g. because several of them are block-type.
240   unsigned LongestObjCSelectorName = 0;
241 
242   /// If this is the first ObjC selector name in an ObjC method
243   /// definition or call, this contains the number of parts that the whole
244   /// selector consist of.
245   unsigned ObjCSelectorNameParts = 0;
246 
247   /// The 0-based index of the parameter/argument. For ObjC it is set
248   /// for the selector name token.
249   /// For now calculated only for ObjC.
250   unsigned ParameterIndex = 0;
251 
252   /// Stores the number of required fake parentheses and the
253   /// corresponding operator precedence.
254   ///
255   /// If multiple fake parentheses start at a token, this vector stores them in
256   /// reverse order, i.e. inner fake parenthesis first.
257   SmallVector<prec::Level, 4> FakeLParens;
258   /// Insert this many fake ) after this token for correct indentation.
259   unsigned FakeRParens = 0;
260 
261   /// \c true if this token starts a binary expression, i.e. has at least
262   /// one fake l_paren with a precedence greater than prec::Unknown.
263   bool StartsBinaryExpression = false;
264   /// \c true if this token ends a binary expression.
265   bool EndsBinaryExpression = false;
266 
267   /// If this is an operator (or "."/"->") in a sequence of operators
268   /// with the same precedence, contains the 0-based operator index.
269   unsigned OperatorIndex = 0;
270 
271   /// If this is an operator (or "."/"->") in a sequence of operators
272   /// with the same precedence, points to the next operator.
273   FormatToken *NextOperator = nullptr;
274 
275   /// Is this token part of a \c DeclStmt defining multiple variables?
276   ///
277   /// Only set if \c Type == \c TT_StartOfName.
278   bool PartOfMultiVariableDeclStmt = false;
279 
280   /// Does this line comment continue a line comment section?
281   ///
282   /// Only set to true if \c Type == \c TT_LineComment.
283   bool ContinuesLineCommentSection = false;
284 
285   /// If this is a bracket, this points to the matching one.
286   FormatToken *MatchingParen = nullptr;
287 
288   /// The previous token in the unwrapped line.
289   FormatToken *Previous = nullptr;
290 
291   /// The next token in the unwrapped line.
292   FormatToken *Next = nullptr;
293 
294   /// If this token starts a block, this contains all the unwrapped lines
295   /// in it.
296   SmallVector<AnnotatedLine *, 1> Children;
297 
298   /// Stores the formatting decision for the token once it was made.
299   FormatDecision Decision = FD_Unformatted;
300 
301   /// If \c true, this token has been fully formatted (indented and
302   /// potentially re-formatted inside), and we do not allow further formatting
303   /// changes.
304   bool Finalized = false;
305 
306   bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
307   bool is(TokenType TT) const { return Type == TT; }
308   bool is(const IdentifierInfo *II) const {
309     return II && II == Tok.getIdentifierInfo();
310   }
311   bool is(tok::PPKeywordKind Kind) const {
312     return Tok.getIdentifierInfo() &&
313            Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
314   }
315   template <typename A, typename B> bool isOneOf(A K1, B K2) const {
316     return is(K1) || is(K2);
317   }
318   template <typename A, typename B, typename... Ts>
319   bool isOneOf(A K1, B K2, Ts... Ks) const {
320     return is(K1) || isOneOf(K2, Ks...);
321   }
322   template <typename T> bool isNot(T Kind) const { return !is(Kind); }
323 
324   bool closesScopeAfterBlock() const {
325     if (BlockKind == BK_Block)
326       return true;
327     if (closesScope())
328       return Previous->closesScopeAfterBlock();
329     return false;
330   }
331 
332   /// \c true if this token starts a sequence with the given tokens in order,
333   /// following the ``Next`` pointers, ignoring comments.
334   template <typename A, typename... Ts>
335   bool startsSequence(A K1, Ts... Tokens) const {
336     return startsSequenceInternal(K1, Tokens...);
337   }
338 
339   /// \c true if this token ends a sequence with the given tokens in order,
340   /// following the ``Previous`` pointers, ignoring comments.
341   template <typename A, typename... Ts>
342   bool endsSequence(A K1, Ts... Tokens) const {
343     return endsSequenceInternal(K1, Tokens...);
344   }
345 
346   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
347 
348   bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
349     return Tok.isObjCAtKeyword(Kind);
350   }
351 
352   bool isAccessSpecifier(bool ColonRequired = true) const {
353     return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
354            (!ColonRequired || (Next && Next->is(tok::colon)));
355   }
356 
357   /// Determine whether the token is a simple-type-specifier.
358   bool isSimpleTypeSpecifier() const;
359 
360   bool isObjCAccessSpecifier() const {
361     return is(tok::at) && Next &&
362            (Next->isObjCAtKeyword(tok::objc_public) ||
363             Next->isObjCAtKeyword(tok::objc_protected) ||
364             Next->isObjCAtKeyword(tok::objc_package) ||
365             Next->isObjCAtKeyword(tok::objc_private));
366   }
367 
368   /// Returns whether \p Tok is ([{ or an opening < of a template or in
369   /// protos.
370   bool opensScope() const {
371     if (is(TT_TemplateString) && TokenText.endswith("${"))
372       return true;
373     if (is(TT_DictLiteral) && is(tok::less))
374       return true;
375     return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
376                    TT_TemplateOpener);
377   }
378   /// Returns whether \p Tok is )]} or a closing > of a template or in
379   /// protos.
380   bool closesScope() const {
381     if (is(TT_TemplateString) && TokenText.startswith("}"))
382       return true;
383     if (is(TT_DictLiteral) && is(tok::greater))
384       return true;
385     return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
386                    TT_TemplateCloser);
387   }
388 
389   /// Returns \c true if this is a "." or "->" accessing a member.
390   bool isMemberAccess() const {
391     return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
392            !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
393                     TT_LambdaArrow);
394   }
395 
396   bool isUnaryOperator() const {
397     switch (Tok.getKind()) {
398     case tok::plus:
399     case tok::plusplus:
400     case tok::minus:
401     case tok::minusminus:
402     case tok::exclaim:
403     case tok::tilde:
404     case tok::kw_sizeof:
405     case tok::kw_alignof:
406       return true;
407     default:
408       return false;
409     }
410   }
411 
412   bool isBinaryOperator() const {
413     // Comma is a binary operator, but does not behave as such wrt. formatting.
414     return getPrecedence() > prec::Comma;
415   }
416 
417   bool isTrailingComment() const {
418     return is(tok::comment) &&
419            (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
420   }
421 
422   /// Returns \c true if this is a keyword that can be used
423   /// like a function call (e.g. sizeof, typeid, ...).
424   bool isFunctionLikeKeyword() const {
425     switch (Tok.getKind()) {
426     case tok::kw_throw:
427     case tok::kw_typeid:
428     case tok::kw_return:
429     case tok::kw_sizeof:
430     case tok::kw_alignof:
431     case tok::kw_alignas:
432     case tok::kw_decltype:
433     case tok::kw_noexcept:
434     case tok::kw_static_assert:
435     case tok::kw___attribute:
436       return true;
437     default:
438       return false;
439     }
440   }
441 
442   /// Returns \c true if this is a string literal that's like a label,
443   /// e.g. ends with "=" or ":".
444   bool isLabelString() const {
445     if (!is(tok::string_literal))
446       return false;
447     StringRef Content = TokenText;
448     if (Content.startswith("\"") || Content.startswith("'"))
449       Content = Content.drop_front(1);
450     if (Content.endswith("\"") || Content.endswith("'"))
451       Content = Content.drop_back(1);
452     Content = Content.trim();
453     return Content.size() > 1 &&
454            (Content.back() == ':' || Content.back() == '=');
455   }
456 
457   /// Returns actual token start location without leading escaped
458   /// newlines and whitespace.
459   ///
460   /// This can be different to Tok.getLocation(), which includes leading escaped
461   /// newlines.
462   SourceLocation getStartOfNonWhitespace() const {
463     return WhitespaceRange.getEnd();
464   }
465 
466   prec::Level getPrecedence() const {
467     return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
468                               /*CPlusPlus11=*/true);
469   }
470 
471   /// Returns the previous token ignoring comments.
472   FormatToken *getPreviousNonComment() const {
473     FormatToken *Tok = Previous;
474     while (Tok && Tok->is(tok::comment))
475       Tok = Tok->Previous;
476     return Tok;
477   }
478 
479   /// Returns the next token ignoring comments.
480   const FormatToken *getNextNonComment() const {
481     const FormatToken *Tok = Next;
482     while (Tok && Tok->is(tok::comment))
483       Tok = Tok->Next;
484     return Tok;
485   }
486 
487   /// Returns \c true if this tokens starts a block-type list, i.e. a
488   /// list that should be indented with a block indent.
489   bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
490     if (is(TT_TemplateString) && opensScope())
491       return true;
492     return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
493            (is(tok::l_brace) &&
494             (BlockKind == BK_Block || is(TT_DictLiteral) ||
495              (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
496            (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
497                               Style.Language == FormatStyle::LK_TextProto));
498   }
499 
500   /// Returns whether the token is the left square bracket of a C++
501   /// structured binding declaration.
502   bool isCppStructuredBinding(const FormatStyle &Style) const {
503     if (!Style.isCpp() || isNot(tok::l_square))
504       return false;
505     const FormatToken *T = this;
506     do {
507       T = T->getPreviousNonComment();
508     } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
509                              tok::ampamp));
510     return T && T->is(tok::kw_auto);
511   }
512 
513   /// Same as opensBlockOrBlockTypeList, but for the closing token.
514   bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
515     if (is(TT_TemplateString) && closesScope())
516       return true;
517     return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
518   }
519 
520   /// Return the actual namespace token, if this token starts a namespace
521   /// block.
522   const FormatToken *getNamespaceToken() const {
523     const FormatToken *NamespaceTok = this;
524     if (is(tok::comment))
525       NamespaceTok = NamespaceTok->getNextNonComment();
526     // Detect "(inline|export)? namespace" in the beginning of a line.
527     if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
528       NamespaceTok = NamespaceTok->getNextNonComment();
529     return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok
530                                                                : nullptr;
531   }
532 
533 private:
534   // Disallow copying.
535   FormatToken(const FormatToken &) = delete;
536   void operator=(const FormatToken &) = delete;
537 
538   template <typename A, typename... Ts>
539   bool startsSequenceInternal(A K1, Ts... Tokens) const {
540     if (is(tok::comment) && Next)
541       return Next->startsSequenceInternal(K1, Tokens...);
542     return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
543   }
544 
545   template <typename A> bool startsSequenceInternal(A K1) const {
546     if (is(tok::comment) && Next)
547       return Next->startsSequenceInternal(K1);
548     return is(K1);
549   }
550 
551   template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
552     if (is(tok::comment) && Previous)
553       return Previous->endsSequenceInternal(K1);
554     return is(K1);
555   }
556 
557   template <typename A, typename... Ts>
558   bool endsSequenceInternal(A K1, Ts... Tokens) const {
559     if (is(tok::comment) && Previous)
560       return Previous->endsSequenceInternal(K1, Tokens...);
561     return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
562   }
563 };
564 
565 class ContinuationIndenter;
566 struct LineState;
567 
568 class TokenRole {
569 public:
570   TokenRole(const FormatStyle &Style) : Style(Style) {}
571   virtual ~TokenRole();
572 
573   /// After the \c TokenAnnotator has finished annotating all the tokens,
574   /// this function precomputes required information for formatting.
575   virtual void precomputeFormattingInfos(const FormatToken *Token);
576 
577   /// Apply the special formatting that the given role demands.
578   ///
579   /// Assumes that the token having this role is already formatted.
580   ///
581   /// Continues formatting from \p State leaving indentation to \p Indenter and
582   /// returns the total penalty that this formatting incurs.
583   virtual unsigned formatFromToken(LineState &State,
584                                    ContinuationIndenter *Indenter,
585                                    bool DryRun) {
586     return 0;
587   }
588 
589   /// Same as \c formatFromToken, but assumes that the first token has
590   /// already been set thereby deciding on the first line break.
591   virtual unsigned formatAfterToken(LineState &State,
592                                     ContinuationIndenter *Indenter,
593                                     bool DryRun) {
594     return 0;
595   }
596 
597   /// Notifies the \c Role that a comma was found.
598   virtual void CommaFound(const FormatToken *Token) {}
599 
600   virtual const FormatToken *lastComma() { return nullptr; }
601 
602 protected:
603   const FormatStyle &Style;
604 };
605 
606 class CommaSeparatedList : public TokenRole {
607 public:
608   CommaSeparatedList(const FormatStyle &Style)
609       : TokenRole(Style), HasNestedBracedList(false) {}
610 
611   void precomputeFormattingInfos(const FormatToken *Token) override;
612 
613   unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
614                             bool DryRun) override;
615 
616   unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
617                            bool DryRun) override;
618 
619   /// Adds \p Token as the next comma to the \c CommaSeparated list.
620   void CommaFound(const FormatToken *Token) override {
621     Commas.push_back(Token);
622   }
623 
624   const FormatToken *lastComma() override {
625     if (Commas.empty())
626       return nullptr;
627     return Commas.back();
628   }
629 
630 private:
631   /// A struct that holds information on how to format a given list with
632   /// a specific number of columns.
633   struct ColumnFormat {
634     /// The number of columns to use.
635     unsigned Columns;
636 
637     /// The total width in characters.
638     unsigned TotalWidth;
639 
640     /// The number of lines required for this format.
641     unsigned LineCount;
642 
643     /// The size of each column in characters.
644     SmallVector<unsigned, 8> ColumnSizes;
645   };
646 
647   /// Calculate which \c ColumnFormat fits best into
648   /// \p RemainingCharacters.
649   const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
650 
651   /// The ordered \c FormatTokens making up the commas of this list.
652   SmallVector<const FormatToken *, 8> Commas;
653 
654   /// The length of each of the list's items in characters including the
655   /// trailing comma.
656   SmallVector<unsigned, 8> ItemLengths;
657 
658   /// Precomputed formats that can be used for this list.
659   SmallVector<ColumnFormat, 4> Formats;
660 
661   bool HasNestedBracedList;
662 };
663 
664 /// Encapsulates keywords that are context sensitive or for languages not
665 /// properly supported by Clang's lexer.
666 struct AdditionalKeywords {
667   AdditionalKeywords(IdentifierTable &IdentTable) {
668     kw_final = &IdentTable.get("final");
669     kw_override = &IdentTable.get("override");
670     kw_in = &IdentTable.get("in");
671     kw_of = &IdentTable.get("of");
672     kw_CF_ENUM = &IdentTable.get("CF_ENUM");
673     kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
674     kw_NS_ENUM = &IdentTable.get("NS_ENUM");
675     kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
676 
677     kw_as = &IdentTable.get("as");
678     kw_async = &IdentTable.get("async");
679     kw_await = &IdentTable.get("await");
680     kw_declare = &IdentTable.get("declare");
681     kw_finally = &IdentTable.get("finally");
682     kw_from = &IdentTable.get("from");
683     kw_function = &IdentTable.get("function");
684     kw_get = &IdentTable.get("get");
685     kw_import = &IdentTable.get("import");
686     kw_infer = &IdentTable.get("infer");
687     kw_is = &IdentTable.get("is");
688     kw_let = &IdentTable.get("let");
689     kw_module = &IdentTable.get("module");
690     kw_readonly = &IdentTable.get("readonly");
691     kw_set = &IdentTable.get("set");
692     kw_type = &IdentTable.get("type");
693     kw_typeof = &IdentTable.get("typeof");
694     kw_var = &IdentTable.get("var");
695     kw_yield = &IdentTable.get("yield");
696 
697     kw_abstract = &IdentTable.get("abstract");
698     kw_assert = &IdentTable.get("assert");
699     kw_extends = &IdentTable.get("extends");
700     kw_implements = &IdentTable.get("implements");
701     kw_instanceof = &IdentTable.get("instanceof");
702     kw_interface = &IdentTable.get("interface");
703     kw_native = &IdentTable.get("native");
704     kw_package = &IdentTable.get("package");
705     kw_synchronized = &IdentTable.get("synchronized");
706     kw_throws = &IdentTable.get("throws");
707     kw___except = &IdentTable.get("__except");
708     kw___has_include = &IdentTable.get("__has_include");
709     kw___has_include_next = &IdentTable.get("__has_include_next");
710 
711     kw_mark = &IdentTable.get("mark");
712 
713     kw_extend = &IdentTable.get("extend");
714     kw_option = &IdentTable.get("option");
715     kw_optional = &IdentTable.get("optional");
716     kw_repeated = &IdentTable.get("repeated");
717     kw_required = &IdentTable.get("required");
718     kw_returns = &IdentTable.get("returns");
719 
720     kw_signals = &IdentTable.get("signals");
721     kw_qsignals = &IdentTable.get("Q_SIGNALS");
722     kw_slots = &IdentTable.get("slots");
723     kw_qslots = &IdentTable.get("Q_SLOTS");
724 
725     // Keep this at the end of the constructor to make sure everything here is
726     // already initialized.
727     JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
728         {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
729          kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
730          kw_set, kw_type, kw_typeof, kw_var, kw_yield,
731          // Keywords from the Java section.
732          kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
733   }
734 
735   // Context sensitive keywords.
736   IdentifierInfo *kw_final;
737   IdentifierInfo *kw_override;
738   IdentifierInfo *kw_in;
739   IdentifierInfo *kw_of;
740   IdentifierInfo *kw_CF_ENUM;
741   IdentifierInfo *kw_CF_OPTIONS;
742   IdentifierInfo *kw_NS_ENUM;
743   IdentifierInfo *kw_NS_OPTIONS;
744   IdentifierInfo *kw___except;
745   IdentifierInfo *kw___has_include;
746   IdentifierInfo *kw___has_include_next;
747 
748   // JavaScript keywords.
749   IdentifierInfo *kw_as;
750   IdentifierInfo *kw_async;
751   IdentifierInfo *kw_await;
752   IdentifierInfo *kw_declare;
753   IdentifierInfo *kw_finally;
754   IdentifierInfo *kw_from;
755   IdentifierInfo *kw_function;
756   IdentifierInfo *kw_get;
757   IdentifierInfo *kw_import;
758   IdentifierInfo *kw_infer;
759   IdentifierInfo *kw_is;
760   IdentifierInfo *kw_let;
761   IdentifierInfo *kw_module;
762   IdentifierInfo *kw_readonly;
763   IdentifierInfo *kw_set;
764   IdentifierInfo *kw_type;
765   IdentifierInfo *kw_typeof;
766   IdentifierInfo *kw_var;
767   IdentifierInfo *kw_yield;
768 
769   // Java keywords.
770   IdentifierInfo *kw_abstract;
771   IdentifierInfo *kw_assert;
772   IdentifierInfo *kw_extends;
773   IdentifierInfo *kw_implements;
774   IdentifierInfo *kw_instanceof;
775   IdentifierInfo *kw_interface;
776   IdentifierInfo *kw_native;
777   IdentifierInfo *kw_package;
778   IdentifierInfo *kw_synchronized;
779   IdentifierInfo *kw_throws;
780 
781   // Pragma keywords.
782   IdentifierInfo *kw_mark;
783 
784   // Proto keywords.
785   IdentifierInfo *kw_extend;
786   IdentifierInfo *kw_option;
787   IdentifierInfo *kw_optional;
788   IdentifierInfo *kw_repeated;
789   IdentifierInfo *kw_required;
790   IdentifierInfo *kw_returns;
791 
792   // QT keywords.
793   IdentifierInfo *kw_signals;
794   IdentifierInfo *kw_qsignals;
795   IdentifierInfo *kw_slots;
796   IdentifierInfo *kw_qslots;
797 
798   /// Returns \c true if \p Tok is a true JavaScript identifier, returns
799   /// \c false if it is a keyword or a pseudo keyword.
800   bool IsJavaScriptIdentifier(const FormatToken &Tok) const {
801     return Tok.is(tok::identifier) &&
802            JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
803                JsExtraKeywords.end();
804   }
805 
806 private:
807   /// The JavaScript keywords beyond the C++ keyword set.
808   std::unordered_set<IdentifierInfo *> JsExtraKeywords;
809 };
810 
811 } // namespace format
812 } // namespace clang
813 
814 #endif
815