clang  7.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  /// How many parts ObjC selector have (i.e. how many parameters method
247  /// has).
248  unsigned ObjCSelectorNameParts = 0;
249 
250  /// Stores the number of required fake parentheses and the
251  /// corresponding operator precedence.
252  ///
253  /// If multiple fake parentheses start at a token, this vector stores them in
254  /// reverse order, i.e. inner fake parenthesis first.
256  /// Insert this many fake ) after this token for correct indentation.
257  unsigned FakeRParens = 0;
258 
259  /// \c true if this token starts a binary expression, i.e. has at least
260  /// one fake l_paren with a precedence greater than prec::Unknown.
262  /// \c true if this token ends a binary expression.
263  bool EndsBinaryExpression = false;
264 
265  /// Is this is an operator (or "."/"->") in a sequence of operators
266  /// with the same precedence, contains the 0-based operator index.
267  unsigned OperatorIndex = 0;
268 
269  /// If this is an operator (or "."/"->") in a sequence of operators
270  /// with the same precedence, points to the next operator.
272 
273  /// Is this token part of a \c DeclStmt defining multiple variables?
274  ///
275  /// Only set if \c Type == \c TT_StartOfName.
277 
278  /// Does this line comment continue a line comment section?
279  ///
280  /// Only set to true if \c Type == \c TT_LineComment.
282 
283  /// If this is a bracket, this points to the matching one.
285 
286  /// The previous token in the unwrapped line.
287  FormatToken *Previous = nullptr;
288 
289  /// The next token in the unwrapped line.
290  FormatToken *Next = nullptr;
291 
292  /// If this token starts a block, this contains all the unwrapped lines
293  /// in it.
295 
296  /// Stores the formatting decision for the token once it was made.
298 
299  /// If \c true, this token has been fully formatted (indented and
300  /// potentially re-formatted inside), and we do not allow further formatting
301  /// changes.
302  bool Finalized = false;
303 
304  bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
305  bool is(TokenType TT) const { return Type == TT; }
306  bool is(const IdentifierInfo *II) const {
307  return II && II == Tok.getIdentifierInfo();
308  }
309  bool is(tok::PPKeywordKind Kind) const {
310  return Tok.getIdentifierInfo() &&
312  }
313  template <typename A, typename B> bool isOneOf(A K1, B K2) const {
314  return is(K1) || is(K2);
315  }
316  template <typename A, typename B, typename... Ts>
317  bool isOneOf(A K1, B K2, Ts... Ks) const {
318  return is(K1) || isOneOf(K2, Ks...);
319  }
320  template <typename T> bool isNot(T Kind) const { return !is(Kind); }
321 
322  /// \c true if this token starts a sequence with the given tokens in order,
323  /// following the ``Next`` pointers, ignoring comments.
324  template <typename A, typename... Ts>
325  bool startsSequence(A K1, Ts... Tokens) const {
326  return startsSequenceInternal(K1, Tokens...);
327  }
328 
329  /// \c true if this token ends a sequence with the given tokens in order,
330  /// following the ``Previous`` pointers, ignoring comments.
331  template <typename A, typename... Ts>
332  bool endsSequence(A K1, Ts... Tokens) const {
333  return endsSequenceInternal(K1, Tokens...);
334  }
335 
336  bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
337 
339  return Tok.isObjCAtKeyword(Kind);
340  }
341 
342  bool isAccessSpecifier(bool ColonRequired = true) const {
343  return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
344  (!ColonRequired || (Next && Next->is(tok::colon)));
345  }
346 
347  /// Determine whether the token is a simple-type-specifier.
348  bool isSimpleTypeSpecifier() const;
349 
350  bool isObjCAccessSpecifier() const {
351  return is(tok::at) && Next &&
352  (Next->isObjCAtKeyword(tok::objc_public) ||
353  Next->isObjCAtKeyword(tok::objc_protected) ||
354  Next->isObjCAtKeyword(tok::objc_package) ||
355  Next->isObjCAtKeyword(tok::objc_private));
356  }
357 
358  /// Returns whether \p Tok is ([{ or an opening < of a template or in
359  /// protos.
360  bool opensScope() const {
361  if (is(TT_TemplateString) && TokenText.endswith("${"))
362  return true;
363  if (is(TT_DictLiteral) && is(tok::less))
364  return true;
365  return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
366  TT_TemplateOpener);
367  }
368  /// Returns whether \p Tok is )]} or a closing > of a template or in
369  /// protos.
370  bool closesScope() const {
371  if (is(TT_TemplateString) && TokenText.startswith("}"))
372  return true;
373  if (is(TT_DictLiteral) && is(tok::greater))
374  return true;
375  return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
376  TT_TemplateCloser);
377  }
378 
379  /// Returns \c true if this is a "." or "->" accessing a member.
380  bool isMemberAccess() const {
381  return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
382  !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
383  TT_LambdaArrow);
384  }
385 
386  bool isUnaryOperator() const {
387  switch (Tok.getKind()) {
388  case tok::plus:
389  case tok::plusplus:
390  case tok::minus:
391  case tok::minusminus:
392  case tok::exclaim:
393  case tok::tilde:
394  case tok::kw_sizeof:
395  case tok::kw_alignof:
396  return true;
397  default:
398  return false;
399  }
400  }
401 
402  bool isBinaryOperator() const {
403  // Comma is a binary operator, but does not behave as such wrt. formatting.
404  return getPrecedence() > prec::Comma;
405  }
406 
407  bool isTrailingComment() const {
408  return is(tok::comment) &&
409  (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
410  }
411 
412  /// Returns \c true if this is a keyword that can be used
413  /// like a function call (e.g. sizeof, typeid, ...).
414  bool isFunctionLikeKeyword() const {
415  switch (Tok.getKind()) {
416  case tok::kw_throw:
417  case tok::kw_typeid:
418  case tok::kw_return:
419  case tok::kw_sizeof:
420  case tok::kw_alignof:
421  case tok::kw_alignas:
422  case tok::kw_decltype:
423  case tok::kw_noexcept:
424  case tok::kw_static_assert:
425  case tok::kw___attribute:
426  return true;
427  default:
428  return false;
429  }
430  }
431 
432  /// Returns \c true if this is a string literal that's like a label,
433  /// e.g. ends with "=" or ":".
434  bool isLabelString() const {
435  if (!is(tok::string_literal))
436  return false;
437  StringRef Content = TokenText;
438  if (Content.startswith("\"") || Content.startswith("'"))
439  Content = Content.drop_front(1);
440  if (Content.endswith("\"") || Content.endswith("'"))
441  Content = Content.drop_back(1);
442  Content = Content.trim();
443  return Content.size() > 1 &&
444  (Content.back() == ':' || Content.back() == '=');
445  }
446 
447  /// Returns actual token start location without leading escaped
448  /// newlines and whitespace.
449  ///
450  /// This can be different to Tok.getLocation(), which includes leading escaped
451  /// newlines.
453  return WhitespaceRange.getEnd();
454  }
455 
457  return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
458  /*CPlusPlus11=*/true);
459  }
460 
461  /// Returns the previous token ignoring comments.
463  FormatToken *Tok = Previous;
464  while (Tok && Tok->is(tok::comment))
465  Tok = Tok->Previous;
466  return Tok;
467  }
468 
469  /// Returns the next token ignoring comments.
471  const FormatToken *Tok = Next;
472  while (Tok && Tok->is(tok::comment))
473  Tok = Tok->Next;
474  return Tok;
475  }
476 
477  /// Returns \c true if this tokens starts a block-type list, i.e. a
478  /// list that should be indented with a block indent.
480  if (is(TT_TemplateString) && opensScope())
481  return true;
482  return is(TT_ArrayInitializerLSquare) ||
483  is(TT_ProtoExtensionLSquare) ||
484  (is(tok::l_brace) &&
485  (BlockKind == BK_Block || is(TT_DictLiteral) ||
486  (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
487  (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
489  }
490 
491  /// Returns whether the token is the left square bracket of a C++
492  /// structured binding declaration.
494  if (!Style.isCpp() || isNot(tok::l_square))
495  return false;
496  const FormatToken *T = this;
497  do {
498  T = T->getPreviousNonComment();
499  } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
500  tok::ampamp));
501  return T && T->is(tok::kw_auto);
502  }
503 
504  /// Same as opensBlockOrBlockTypeList, but for the closing token.
506  if (is(TT_TemplateString) && closesScope())
507  return true;
508  return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
509  }
510 
511  /// Return the actual namespace token, if this token starts a namespace
512  /// block.
514  const FormatToken *NamespaceTok = this;
515  if (is(tok::comment))
516  NamespaceTok = NamespaceTok->getNextNonComment();
517  // Detect "(inline)? namespace" in the beginning of a line.
518  if (NamespaceTok && NamespaceTok->is(tok::kw_inline))
519  NamespaceTok = NamespaceTok->getNextNonComment();
520  return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok
521  : nullptr;
522  }
523 
524 private:
525  // Disallow copying.
526  FormatToken(const FormatToken &) = delete;
527  void operator=(const FormatToken &) = delete;
528 
529  template <typename A, typename... Ts>
530  bool startsSequenceInternal(A K1, Ts... Tokens) const {
531  if (is(tok::comment) && Next)
532  return Next->startsSequenceInternal(K1, Tokens...);
533  return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
534  }
535 
536  template <typename A> bool startsSequenceInternal(A K1) const {
537  if (is(tok::comment) && Next)
538  return Next->startsSequenceInternal(K1);
539  return is(K1);
540  }
541 
542  template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
543  if (is(tok::comment) && Previous)
544  return Previous->endsSequenceInternal(K1);
545  return is(K1);
546  }
547 
548  template <typename A, typename... Ts>
549  bool endsSequenceInternal(A K1, Ts... Tokens) const {
550  if (is(tok::comment) && Previous)
551  return Previous->endsSequenceInternal(K1, Tokens...);
552  return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
553  }
554 };
555 
557 struct LineState;
558 
559 class TokenRole {
560 public:
561  TokenRole(const FormatStyle &Style) : Style(Style) {}
562  virtual ~TokenRole();
563 
564  /// After the \c TokenAnnotator has finished annotating all the tokens,
565  /// this function precomputes required information for formatting.
566  virtual void precomputeFormattingInfos(const FormatToken *Token);
567 
568  /// Apply the special formatting that the given role demands.
569  ///
570  /// Assumes that the token having this role is already formatted.
571  ///
572  /// Continues formatting from \p State leaving indentation to \p Indenter and
573  /// returns the total penalty that this formatting incurs.
574  virtual unsigned formatFromToken(LineState &State,
576  bool DryRun) {
577  return 0;
578  }
579 
580  /// Same as \c formatFromToken, but assumes that the first token has
581  /// already been set thereby deciding on the first line break.
582  virtual unsigned formatAfterToken(LineState &State,
584  bool DryRun) {
585  return 0;
586  }
587 
588  /// Notifies the \c Role that a comma was found.
589  virtual void CommaFound(const FormatToken *Token) {}
590 
591 protected:
593 };
594 
596 public:
598  : TokenRole(Style), HasNestedBracedList(false) {}
599 
600  void precomputeFormattingInfos(const FormatToken *Token) override;
601 
602  unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
603  bool DryRun) override;
604 
605  unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
606  bool DryRun) override;
607 
608  /// Adds \p Token as the next comma to the \c CommaSeparated list.
609  void CommaFound(const FormatToken *Token) override {
610  Commas.push_back(Token);
611  }
612 
613 private:
614  /// A struct that holds information on how to format a given list with
615  /// a specific number of columns.
616  struct ColumnFormat {
617  /// The number of columns to use.
618  unsigned Columns;
619 
620  /// The total width in characters.
621  unsigned TotalWidth;
622 
623  /// The number of lines required for this format.
624  unsigned LineCount;
625 
626  /// The size of each column in characters.
627  SmallVector<unsigned, 8> ColumnSizes;
628  };
629 
630  /// Calculate which \c ColumnFormat fits best into
631  /// \p RemainingCharacters.
632  const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
633 
634  /// The ordered \c FormatTokens making up the commas of this list.
636 
637  /// The length of each of the list's items in characters including the
638  /// trailing comma.
639  SmallVector<unsigned, 8> ItemLengths;
640 
641  /// Precomputed formats that can be used for this list.
643 
644  bool HasNestedBracedList;
645 };
646 
647 /// Encapsulates keywords that are context sensitive or for languages not
648 /// properly supported by Clang's lexer.
651  kw_final = &IdentTable.get("final");
652  kw_override = &IdentTable.get("override");
653  kw_in = &IdentTable.get("in");
654  kw_of = &IdentTable.get("of");
655  kw_CF_ENUM = &IdentTable.get("CF_ENUM");
656  kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
657  kw_NS_ENUM = &IdentTable.get("NS_ENUM");
658  kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
659 
660  kw_as = &IdentTable.get("as");
661  kw_async = &IdentTable.get("async");
662  kw_await = &IdentTable.get("await");
663  kw_declare = &IdentTable.get("declare");
664  kw_finally = &IdentTable.get("finally");
665  kw_from = &IdentTable.get("from");
666  kw_function = &IdentTable.get("function");
667  kw_get = &IdentTable.get("get");
668  kw_import = &IdentTable.get("import");
669  kw_is = &IdentTable.get("is");
670  kw_let = &IdentTable.get("let");
671  kw_module = &IdentTable.get("module");
672  kw_readonly = &IdentTable.get("readonly");
673  kw_set = &IdentTable.get("set");
674  kw_type = &IdentTable.get("type");
675  kw_typeof = &IdentTable.get("typeof");
676  kw_var = &IdentTable.get("var");
677  kw_yield = &IdentTable.get("yield");
678 
679  kw_abstract = &IdentTable.get("abstract");
680  kw_assert = &IdentTable.get("assert");
681  kw_extends = &IdentTable.get("extends");
682  kw_implements = &IdentTable.get("implements");
683  kw_instanceof = &IdentTable.get("instanceof");
684  kw_interface = &IdentTable.get("interface");
685  kw_native = &IdentTable.get("native");
686  kw_package = &IdentTable.get("package");
687  kw_synchronized = &IdentTable.get("synchronized");
688  kw_throws = &IdentTable.get("throws");
689  kw___except = &IdentTable.get("__except");
690  kw___has_include = &IdentTable.get("__has_include");
691  kw___has_include_next = &IdentTable.get("__has_include_next");
692 
693  kw_mark = &IdentTable.get("mark");
694 
695  kw_extend = &IdentTable.get("extend");
696  kw_option = &IdentTable.get("option");
697  kw_optional = &IdentTable.get("optional");
698  kw_repeated = &IdentTable.get("repeated");
699  kw_required = &IdentTable.get("required");
700  kw_returns = &IdentTable.get("returns");
701 
702  kw_signals = &IdentTable.get("signals");
703  kw_qsignals = &IdentTable.get("Q_SIGNALS");
704  kw_slots = &IdentTable.get("slots");
705  kw_qslots = &IdentTable.get("Q_SLOTS");
706 
707  // Keep this at the end of the constructor to make sure everything here is
708  // already initialized.
709  JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
710  {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
711  kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
712  kw_set, kw_type, kw_typeof, kw_var, kw_yield,
713  // Keywords from the Java section.
714  kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
715  }
716 
717  // Context sensitive keywords.
729 
730  // JavaScript keywords.
749 
750  // Java keywords.
761 
762  // Pragma keywords.
764 
765  // Proto keywords.
772 
773  // QT keywords.
778 
779  /// Returns \c true if \p Tok is a true JavaScript identifier, returns
780  /// \c false if it is a keyword or a pseudo keyword.
782  return Tok.is(tok::identifier) &&
783  JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
784  JsExtraKeywords.end();
785  }
786 
787 private:
788  /// The JavaScript keywords beyond the C++ keyword set.
789  std::unordered_set<IdentifierInfo *> JsExtraKeywords;
790 };
791 
792 } // namespace format
793 } // namespace clang
794 
795 #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:332
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:1170
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:597
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:380
bool isFunctionLikeKeyword() const
Returns true if this is a keyword that can be used like a function call (e.g.
Definition: FormatToken.h:414
The base class of the type hierarchy.
Definition: Type.h:1420
bool isUnaryOperator() const
Definition: FormatToken.h:386
const FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:470
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
Definition: FormatToken.h:513
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
How many parts ObjC selector have (i.e.
Definition: FormatToken.h:248
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:342
bool EndsBinaryExpression
true if this token ends a binary expression.
Definition: FormatToken.h:263
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:402
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:290
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:370
unsigned SplitPenalty
Penalty for inserting a line break before this token.
Definition: FormatToken.h:237
prec::Level getPrecedence() const
Definition: FormatToken.h:456
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:257
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:287
AdditionalKeywords(IdentifierTable &IdentTable)
Definition: FormatToken.h:650
bool StartsBinaryExpression
true if this token starts a binary expression, i.e.
Definition: FormatToken.h:261
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:267
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:781
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:320
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const
Same as opensBlockOrBlockTypeList, but for the closing token.
Definition: FormatToken.h:505
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:609
bool isCppStructuredBinding(const FormatStyle &Style) const
Returns whether the token is the left square bracket of a C++ structured binding declaration.
Definition: FormatToken.h:493
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:462
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:452
bool isLabelString() const
Returns true if this is a string literal that&#39;s like a label, e.g.
Definition: FormatToken.h:434
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:313
virtual void CommaFound(const FormatToken *Token)
Notifies the Role that a comma was found.
Definition: FormatToken.h:589
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: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:728
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:350
bool isTrailingComment() const
Definition: FormatToken.h:407
TokenRole(const FormatStyle &Style)
Definition: FormatToken.h:561
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 is(tok::TokenKind Kind) const
Definition: FormatToken.h:304
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:649
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:305
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
Definition: FormatToken.h:255
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:1180
Dataflow Directional Tag Classes.
bool is(const IdentifierInfo *II) const
Definition: FormatToken.h:306
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:302
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:982
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:582
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:271
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:284
bool isOneOf(A K1, B K2, Ts... Ks) const
Definition: FormatToken.h:317
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:294
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:325
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e.
Definition: FormatToken.h:479
bool opensScope() const
Returns whether Tok is ([{ or an opening < of a template or in protos.
Definition: FormatToken.h:360
const FormatStyle & Style
Definition: FormatToken.h:592
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:574
Should be used for Protocol Buffer messages in text format (https://developers.google.com/protocol-buffers/).
Definition: Format.h:1175
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:297
bool ContinuesLineCommentSection
Does this line comment continue a line comment section?
Definition: FormatToken.h:281
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:338
bool isStringLiteral() const
Definition: FormatToken.h:336
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:276
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:309
const FormatStyle & Style
#define LIST_TOKEN_TYPES
Definition: FormatToken.h:29