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