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