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