clang  6.0.0svn
FormatToken.h
Go to the documentation of this file.
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 
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,
100 #undef TYPE
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.
109 
110 // The packing kind of a function's parameters.
112 
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 {
122 
123  /// \brief The \c Token.
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.
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.
172 
173  /// \brief Contains the kind of block if this token is a brace.
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<..>".
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.
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?
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.
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.
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.
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.
265 
266  /// \brief Is this token part of a \c DeclStmt defining multiple variables?
267  ///
268  /// Only set if \c Type == \c TT_StartOfName.
270 
271  /// \brief Does this line comment continue a line comment section?
272  ///
273  /// Only set to true if \c Type == \c TT_LineComment.
275 
276  /// \brief If this is a bracket, this points to the matching one.
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.
288 
289  /// \brief Stores the formatting decision for the token once it was made.
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() &&
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 
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.
440  return WhitespaceRange.getEnd();
441  }
442 
444  return getBinOpPrecedence(Tok.getKind(), true, true);
445  }
446 
447  /// \brief Returns the previous token ignoring comments.
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.
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.
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 ||
474  }
475 
476  /// \brief Returns whether the token is the left square bracket of a C++
477  /// structured binding declaration.
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.
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.
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 
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,
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,
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:
578 };
579 
581 public:
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.
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.
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.
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.
714 
715  // JavaScript keywords.
734 
735  // Java keywords.
746 
747  // Pragma keywords.
749 
750  // Proto keywords.
757 
758  // QT keywords.
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.
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
bool endsSequence(A K1, Ts... Tokens) const
true if this token ends a sequence with the given tokens in order, following the Previous pointers...
Definition: FormatToken.h:325
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:228
Token Tok
The Token.
Definition: FormatToken.h:124
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:1209
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:95
CommaSeparatedList(const FormatStyle &Style)
Definition: FormatToken.h:582
std::unique_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token&#39;s formatting...
Definition: FormatToken.h:204
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:215
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:367
bool isFunctionLikeKeyword() const
Returns true if this is a keyword that can be used like a function call (e.g.
Definition: FormatToken.h:401
The base class of the type hierarchy.
Definition: Type.h:1353
bool isUnaryOperator() const
Definition: FormatToken.h:373
const FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:456
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
Definition: FormatToken.h:498
bool IsMultiline
Whether the token text contains newlines (escaped or not).
Definition: FormatToken.h:153
bool IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:156
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token...
Definition: TokenKinds.h:79
bool isAccessSpecifier(bool ColonRequired=true) const
Definition: FormatToken.h:335
bool EndsBinaryExpression
true if this token ends a binary expression.
Definition: FormatToken.h:256
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:211
bool isBinaryOperator() const
Definition: FormatToken.h:389
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:130
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:283
tok::TokenKind getKind() const
Definition: Token.h:90
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
Definition: FormatToken.h:219
bool closesScope() const
Returns whether Tok is )]} or a template closing >.
Definition: FormatToken.h:359
unsigned SplitPenalty
Penalty for inserting a line break before this token.
Definition: FormatToken.h:234
prec::Level getPrecedence() const
Definition: FormatToken.h:443
One of these records is kept for each identifier that is lexed.
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
Definition: FormatToken.h:192
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
Definition: FormatToken.h:250
LineState State
bool CanBreakBefore
true if it is allowed to break before this token.
Definition: FormatToken.h:182
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:280
AdditionalKeywords(IdentifierTable &IdentTable)
Definition: FormatToken.h:635
bool StartsBinaryExpression
true if this token starts a binary expression, i.e.
Definition: FormatToken.h:254
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
unsigned LongestObjCSelectorName
If this is the first ObjC selector name in an ObjC method definition or call, this contains the lengt...
Definition: FormatToken.h:241
unsigned OperatorIndex
Is this is an operator (or "."/"->") in a sequence of operators with the same precedence, contains the 0-based operator index.
Definition: FormatToken.h:260
bool IsJavaScriptIdentifier(const FormatToken &Tok) const
Returns true if Tok is a true JavaScript identifier, returns false if it is a keyword or a pseudo key...
Definition: FormatToken.h:766
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:179
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:57
bool isNot(T Kind) const
Definition: FormatToken.h:313
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const
Same as opensBlockOrBlockTypeList, but for the closing token.
Definition: FormatToken.h:490
unsigned BlockParameterCount
Number of parameters that are nested blocks, if this is "(", "[" or "<".
Definition: FormatToken.h:196
void CommaFound(const FormatToken *Token) override
Adds Token as the next comma to the CommaSeparated list.
Definition: FormatToken.h:594
bool isCppStructuredBinding(const FormatStyle &Style) const
Returns whether the token is the left square bracket of a C++ structured binding declaration.
Definition: FormatToken.h:478
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:448
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:439
bool isLabelString() const
Returns true if this is a string literal that&#39;s like a label, e.g.
Definition: FormatToken.h:421
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:306
virtual void CommaFound(const FormatToken *Token)
Notifies the Role that a comma was found.
Definition: FormatToken.h:574
The current state when indenting a unwrapped line.
ContinuationIndenter * Indenter
const FunctionProtoType * T
Implements an efficient mapping from strings to IdentifierInfo nodes.
ParameterPackingKind PackingKind
If this is an opening parenthesis, how are the parameters packed?
Definition: FormatToken.h:207
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a &#39;#&#39; at the beginning of the line...
Definition: TokenKinds.h:33
IdentifierInfo * kw___has_include_next
Definition: FormatToken.h:713
A wrapper around a Token storing information about the whitespace characters preceding it...
Definition: FormatToken.h:120
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines and computes precedence levels for binary/ternary operators.
SourceLocation getEnd() const
bool isObjCAccessSpecifier() const
Definition: FormatToken.h:343
bool isTrailingComment() const
Definition: FormatToken.h:394
TokenRole(const FormatStyle &Style)
Definition: FormatToken.h:546
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an &#39;@&#39;.
Definition: TokenKinds.h:41
unsigned LastNewlineOffset
The offset just past the last &#39; &#39; in this token&#39;s leading whitespace (relative to WhiteSpaceStart)...
Definition: FormatToken.h:141
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
Definition: FormatToken.cpp:25
#define false
Definition: stdbool.h:33
Kind
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:297
Various functions to configurably format source code.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang&#39;s l...
Definition: FormatToken.h:634
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:137
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
tok::TokenKind ParentBracket
If this is a bracket ("<", "(", "[" or "{"), contains the kind of the surrounding bracket...
Definition: FormatToken.h:200
bool IsUnterminatedLiteral
Set to true if this token is an unterminated literal.
Definition: FormatToken.h:171
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:168
bool is(TokenType TT) const
Definition: FormatToken.h:298
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
Definition: FormatToken.h:248
bool isSimpleTypeSpecifier() const
Determine whether the token is a simple-type-specifier.
Definition: FormatToken.cpp:40
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:46
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
Definition: FormatToken.h:231
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1219
Dataflow Directional Tag Classes.
bool is(const IdentifierInfo *II) const
Definition: FormatToken.h:299
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Definition: FormatToken.h:146
bool Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside)...
Definition: FormatToken.h:295
tok::PPKeywordKind getPPKeywordID() const
Return the preprocessor keyword ID for this identifier.
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:937
virtual unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
Definition: FormatToken.h:567
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence, points to the next operator.
Definition: FormatToken.h:264
bool ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
Definition: FormatToken.h:185
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:277
bool isOneOf(A K1, B K2, Ts... Ks) const
Definition: FormatToken.h:310
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:287
bool startsSequence(A K1, Ts... Tokens) const
true if this token starts a sequence with the given tokens in order, following the Next pointers...
Definition: FormatToken.h:318
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e.
Definition: FormatToken.h:465
bool opensScope() const
Returns whether Tok is ([{ or a template opening <.
Definition: FormatToken.h:352
const FormatStyle & Style
Definition: FormatToken.h:577
bool MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:162
virtual unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Apply the special formatting that the given role demands.
Definition: FormatToken.h:559
Should be used for Protocol Buffer messages in text format (https://developers.google.com/protocol-buffers/).
Definition: Format.h:1214
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
A trivial tuple used to represent a source range.
unsigned BindingStrength
The binding strength of a token.
Definition: FormatToken.h:224
FormatDecision Decision
Stores the formatting decision for the token once it was made.
Definition: FormatToken.h:290
bool ContinuesLineCommentSection
Does this line comment continue a line comment section?
Definition: FormatToken.h:274
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:331
bool isStringLiteral() const
Definition: FormatToken.h:329
bool HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
Definition: FormatToken.h:134
BraceBlockKind BlockKind
Contains the kind of block if this token is a brace.
Definition: FormatToken.h:174
bool PartOfMultiVariableDeclStmt
Is this token part of a DeclStmt defining multiple variables?
Definition: FormatToken.h:269
unsigned LastLineColumnWidth
Contains the width in columns of the last line of a multi-line token.
Definition: FormatToken.h:150
bool is(tok::PPKeywordKind Kind) const
Definition: FormatToken.h:302
const FormatStyle & Style
#define LIST_TOKEN_TYPES
Definition: FormatToken.h:29