1 //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file contains the declaration of the FormatToken, a wrapper
11 /// around Token with additional information related to formatting.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
16 #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
23 #include <unordered_set>
28 #define LIST_TOKEN_TYPES \
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeColon) \
32 TYPE(AttributeParen) \
33 TYPE(AttributeSquare) \
34 TYPE(BinaryOperator) \
38 TYPE(ConditionalExpr) \
39 TYPE(ConflictAlternative) \
42 TYPE(CtorInitializerColon) \
43 TYPE(CtorInitializerComma) \
44 TYPE(DesignatedInitializerLSquare) \
45 TYPE(DesignatedInitializerPeriod) \
48 TYPE(FunctionAnnotationRParen) \
49 TYPE(FunctionDeclarationName) \
50 TYPE(FunctionLBrace) \
51 TYPE(FunctionTypeLParen) \
52 TYPE(ImplicitStringLiteral) \
53 TYPE(InheritanceColon) \
54 TYPE(InheritanceComma) \
55 TYPE(InlineASMBrace) \
56 TYPE(InlineASMColon) \
57 TYPE(InlineASMSymbolicNameLSquare) \
58 TYPE(JavaAnnotation) \
59 TYPE(JsComputedPropertyName) \
60 TYPE(JsExponentiation) \
61 TYPE(JsExponentiationEqual) \
63 TYPE(JsNonNullAssertion) \
64 TYPE(JsNullishCoalescingOperator) \
65 TYPE(JsNullPropagatingOperator) \
66 TYPE(JsPrivateIdentifier) \
68 TYPE(JsTypeOperator) \
69 TYPE(JsTypeOptionalQuestion) \
73 TYPE(LeadingJavaAnnotation) \
75 TYPE(MacroBlockBegin) \
77 TYPE(NamespaceMacro) \
78 TYPE(ObjCBlockLBrace) \
79 TYPE(ObjCBlockLParen) \
82 TYPE(ObjCMethodExpr) \
83 TYPE(ObjCMethodSpecifier) \
85 TYPE(ObjCStringLiteral) \
86 TYPE(OverloadedOperator) \
87 TYPE(OverloadedOperatorLParen) \
88 TYPE(PointerOrReference) \
89 TYPE(PureVirtualSpecifier) \
90 TYPE(RangeBasedForLoopColon) \
94 TYPE(StatementMacro) \
95 TYPE(StructuredBindingLSquare) \
96 TYPE(TemplateCloser) \
97 TYPE(TemplateOpener) \
98 TYPE(TemplateString) \
99 TYPE(ProtoExtensionLSquare) \
100 TYPE(TrailingAnnotation) \
101 TYPE(TrailingReturnArrow) \
102 TYPE(TrailingUnaryOperator) \
103 TYPE(TypenameMacro) \
104 TYPE(UnaryOperator) \
105 TYPE(UntouchableMacroFunc) \
106 TYPE(CSharpStringLiteral) \
107 TYPE(CSharpNamedArgumentColon) \
108 TYPE(CSharpNullable) \
109 TYPE(CSharpNullCoalescing) \
110 TYPE(CSharpNullConditional) \
111 TYPE(CSharpNullConditionalLSquare) \
112 TYPE(CSharpGenericTypeConstraint) \
113 TYPE(CSharpGenericTypeConstraintColon) \
114 TYPE(CSharpGenericTypeConstraintComma) \
117 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
118 /// template opener or binary operator.
120 #define TYPE(X) TT_##X,
126 /// Determines the name of a token type.
127 const char *getTokenTypeName(TokenType Type);
129 // Represents what type of block a set of braces open.
130 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
132 // The packing kind of a function's parameters.
133 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
135 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
140 /// A wrapper around a \c Token storing information about the
141 /// whitespace characters preceding it.
148 /// The number of newlines immediately before the \c Token.
150 /// This can be used to determine what the user wrote in the original code
151 /// and thereby e.g. leave an empty line between two function definitions.
152 unsigned NewlinesBefore = 0;
154 /// Whether there is at least one unescaped newline before the \c
156 bool HasUnescapedNewline = false;
158 /// The range of the whitespace immediately preceding the \c Token.
159 SourceRange WhitespaceRange;
161 /// The offset just past the last '\n' in this token's leading
162 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
163 unsigned LastNewlineOffset = 0;
165 /// The width of the non-whitespace parts of the token (or its first
166 /// line for multi-line tokens) in columns.
167 /// We need this to correctly measure number of columns a token spans.
168 unsigned ColumnWidth = 0;
170 /// Contains the width in columns of the last line of a multi-line
172 unsigned LastLineColumnWidth = 0;
174 /// Whether the token text contains newlines (escaped or not).
175 bool IsMultiline = false;
177 /// Indicates that this is the first token of the file.
178 bool IsFirst = false;
180 /// Whether there must be a line break before this token.
182 /// This happens for example when a preprocessor directive ended directly
183 /// before the token.
184 bool MustBreakBefore = false;
186 /// The raw text of the token.
188 /// Contains the raw token text without leading whitespace and without leading
189 /// escaped newlines.
192 /// Set to \c true if this token is an unterminated literal.
193 bool IsUnterminatedLiteral = 0;
195 /// Contains the kind of block if this token is a brace.
196 BraceBlockKind BlockKind = BK_Unknown;
198 /// Returns the token's type, e.g. whether "<" is a template opener or
200 TokenType getType() const { return Type; }
201 void setType(TokenType T) { Type = T; }
203 /// The number of spaces that should be inserted before this token.
204 unsigned SpacesRequiredBefore = 0;
206 /// \c true if it is allowed to break before this token.
207 bool CanBreakBefore = false;
209 /// \c true if this is the ">" of "template<..>".
210 bool ClosesTemplateDeclaration = false;
212 /// Number of parameters, if this is "(", "[" or "<".
213 unsigned ParameterCount = 0;
215 /// Number of parameters that are nested blocks,
216 /// if this is "(", "[" or "<".
217 unsigned BlockParameterCount = 0;
219 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
220 /// the surrounding bracket.
221 tok::TokenKind ParentBracket = tok::unknown;
223 /// A token can have a special role that can carry extra information
224 /// about the token's formatting.
225 std::unique_ptr<TokenRole> Role;
227 /// If this is an opening parenthesis, how are the parameters packed?
228 ParameterPackingKind PackingKind = PPK_Inconclusive;
230 /// The total length of the unwrapped line up to and including this
232 unsigned TotalLength = 0;
234 /// The original 0-based column of this token, including expanded tabs.
235 /// The configured TabWidth is used as tab width.
236 unsigned OriginalColumn = 0;
238 /// The length of following tokens until the next natural split point,
239 /// or the next token that can be broken.
240 unsigned UnbreakableTailLength = 0;
242 // FIXME: Come up with a 'cleaner' concept.
243 /// The binding strength of a token. This is a combined value of
244 /// operator precedence, parenthesis nesting, etc.
245 unsigned BindingStrength = 0;
247 /// The nesting level of this token, i.e. the number of surrounding (),
249 unsigned NestingLevel = 0;
251 /// The indent level of this token. Copied from the surrounding line.
252 unsigned IndentLevel = 0;
254 /// Penalty for inserting a line break before this token.
255 unsigned SplitPenalty = 0;
257 /// If this is the first ObjC selector name in an ObjC method
258 /// definition or call, this contains the length of the longest name.
260 /// This being set to 0 means that the selectors should not be colon-aligned,
261 /// e.g. because several of them are block-type.
262 unsigned LongestObjCSelectorName = 0;
264 /// If this is the first ObjC selector name in an ObjC method
265 /// definition or call, this contains the number of parts that the whole
266 /// selector consist of.
267 unsigned ObjCSelectorNameParts = 0;
269 /// The 0-based index of the parameter/argument. For ObjC it is set
270 /// for the selector name token.
271 /// For now calculated only for ObjC.
272 unsigned ParameterIndex = 0;
274 /// Stores the number of required fake parentheses and the
275 /// corresponding operator precedence.
277 /// If multiple fake parentheses start at a token, this vector stores them in
278 /// reverse order, i.e. inner fake parenthesis first.
279 SmallVector<prec::Level, 4> FakeLParens;
280 /// Insert this many fake ) after this token for correct indentation.
281 unsigned FakeRParens = 0;
283 /// \c true if this token starts a binary expression, i.e. has at least
284 /// one fake l_paren with a precedence greater than prec::Unknown.
285 bool StartsBinaryExpression = false;
286 /// \c true if this token ends a binary expression.
287 bool EndsBinaryExpression = false;
289 /// If this is an operator (or "."/"->") in a sequence of operators
290 /// with the same precedence, contains the 0-based operator index.
291 unsigned OperatorIndex = 0;
293 /// If this is an operator (or "."/"->") in a sequence of operators
294 /// with the same precedence, points to the next operator.
295 FormatToken *NextOperator = nullptr;
297 /// Is this token part of a \c DeclStmt defining multiple variables?
299 /// Only set if \c Type == \c TT_StartOfName.
300 bool PartOfMultiVariableDeclStmt = false;
302 /// Does this line comment continue a line comment section?
304 /// Only set to true if \c Type == \c TT_LineComment.
305 bool ContinuesLineCommentSection = false;
307 /// If this is a bracket, this points to the matching one.
308 FormatToken *MatchingParen = nullptr;
310 /// The previous token in the unwrapped line.
311 FormatToken *Previous = nullptr;
313 /// The next token in the unwrapped line.
314 FormatToken *Next = nullptr;
316 /// If this token starts a block, this contains all the unwrapped lines
318 SmallVector<AnnotatedLine *, 1> Children;
320 /// Stores the formatting decision for the token once it was made.
321 FormatDecision Decision = FD_Unformatted;
323 /// If \c true, this token has been fully formatted (indented and
324 /// potentially re-formatted inside), and we do not allow further formatting
326 bool Finalized = false;
328 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
329 bool is(TokenType TT) const { return Type == TT; }
330 bool is(const IdentifierInfo *II) const {
331 return II && II == Tok.getIdentifierInfo();
333 bool is(tok::PPKeywordKind Kind) const {
334 return Tok.getIdentifierInfo() &&
335 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
337 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
338 return is(K1) || is(K2);
340 template <typename A, typename B, typename... Ts>
341 bool isOneOf(A K1, B K2, Ts... Ks) const {
342 return is(K1) || isOneOf(K2, Ks...);
344 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
346 bool isIf(bool AllowConstexprMacro = true) const {
347 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
348 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
351 bool closesScopeAfterBlock() const {
352 if (BlockKind == BK_Block)
355 return Previous->closesScopeAfterBlock();
359 /// \c true if this token starts a sequence with the given tokens in order,
360 /// following the ``Next`` pointers, ignoring comments.
361 template <typename A, typename... Ts>
362 bool startsSequence(A K1, Ts... Tokens) const {
363 return startsSequenceInternal(K1, Tokens...);
366 /// \c true if this token ends a sequence with the given tokens in order,
367 /// following the ``Previous`` pointers, ignoring comments.
368 /// For example, given tokens [T1, T2, T3], the function returns true if
369 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
370 /// words, the tokens passed to this function need to the reverse of the
371 /// order the tokens appear in code.
372 template <typename A, typename... Ts>
373 bool endsSequence(A K1, Ts... Tokens) const {
374 return endsSequenceInternal(K1, Tokens...);
377 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
379 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
380 return Tok.isObjCAtKeyword(Kind);
383 bool isAccessSpecifier(bool ColonRequired = true) const {
384 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
385 (!ColonRequired || (Next && Next->is(tok::colon)));
388 /// Determine whether the token is a simple-type-specifier.
389 bool isSimpleTypeSpecifier() const;
391 bool isObjCAccessSpecifier() const {
392 return is(tok::at) && Next &&
393 (Next->isObjCAtKeyword(tok::objc_public) ||
394 Next->isObjCAtKeyword(tok::objc_protected) ||
395 Next->isObjCAtKeyword(tok::objc_package) ||
396 Next->isObjCAtKeyword(tok::objc_private));
399 /// Returns whether \p Tok is ([{ or an opening < of a template or in
401 bool opensScope() const {
402 if (is(TT_TemplateString) && TokenText.endswith("${"))
404 if (is(TT_DictLiteral) && is(tok::less))
406 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
409 /// Returns whether \p Tok is )]} or a closing > of a template or in
411 bool closesScope() const {
412 if (is(TT_TemplateString) && TokenText.startswith("}"))
414 if (is(TT_DictLiteral) && is(tok::greater))
416 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
420 /// Returns \c true if this is a "." or "->" accessing a member.
421 bool isMemberAccess() const {
422 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
423 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
424 TT_LambdaArrow, TT_LeadingJavaAnnotation);
427 bool isUnaryOperator() const {
428 switch (Tok.getKind()) {
432 case tok::minusminus:
436 case tok::kw_alignof:
443 bool isBinaryOperator() const {
444 // Comma is a binary operator, but does not behave as such wrt. formatting.
445 return getPrecedence() > prec::Comma;
448 bool isTrailingComment() const {
449 return is(tok::comment) &&
450 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
453 /// Returns \c true if this is a keyword that can be used
454 /// like a function call (e.g. sizeof, typeid, ...).
455 bool isFunctionLikeKeyword() const {
456 switch (Tok.getKind()) {
461 case tok::kw_alignof:
462 case tok::kw_alignas:
463 case tok::kw_decltype:
464 case tok::kw_noexcept:
465 case tok::kw_static_assert:
466 case tok::kw___attribute:
473 /// Returns \c true if this is a string literal that's like a label,
474 /// e.g. ends with "=" or ":".
475 bool isLabelString() const {
476 if (!is(tok::string_literal))
478 StringRef Content = TokenText;
479 if (Content.startswith("\"") || Content.startswith("'"))
480 Content = Content.drop_front(1);
481 if (Content.endswith("\"") || Content.endswith("'"))
482 Content = Content.drop_back(1);
483 Content = Content.trim();
484 return Content.size() > 1 &&
485 (Content.back() == ':' || Content.back() == '=');
488 /// Returns actual token start location without leading escaped
489 /// newlines and whitespace.
491 /// This can be different to Tok.getLocation(), which includes leading escaped
493 SourceLocation getStartOfNonWhitespace() const {
494 return WhitespaceRange.getEnd();
497 prec::Level getPrecedence() const {
498 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
499 /*CPlusPlus11=*/true);
502 /// Returns the previous token ignoring comments.
503 FormatToken *getPreviousNonComment() const {
504 FormatToken *Tok = Previous;
505 while (Tok && Tok->is(tok::comment))
510 /// Returns the next token ignoring comments.
511 const FormatToken *getNextNonComment() const {
512 const FormatToken *Tok = Next;
513 while (Tok && Tok->is(tok::comment))
518 /// Returns \c true if this tokens starts a block-type list, i.e. a
519 /// list that should be indented with a block indent.
520 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
521 // C# Does not indent object initialisers as continuations.
522 if (is(tok::l_brace) && BlockKind == BK_BracedInit && Style.isCSharp())
524 if (is(TT_TemplateString) && opensScope())
526 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
528 (BlockKind == BK_Block || is(TT_DictLiteral) ||
529 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
530 (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
531 Style.Language == FormatStyle::LK_TextProto));
534 /// Returns whether the token is the left square bracket of a C++
535 /// structured binding declaration.
536 bool isCppStructuredBinding(const FormatStyle &Style) const {
537 if (!Style.isCpp() || isNot(tok::l_square))
539 const FormatToken *T = this;
541 T = T->getPreviousNonComment();
542 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
544 return T && T->is(tok::kw_auto);
547 /// Same as opensBlockOrBlockTypeList, but for the closing token.
548 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
549 if (is(TT_TemplateString) && closesScope())
551 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
554 /// Return the actual namespace token, if this token starts a namespace
556 const FormatToken *getNamespaceToken() const {
557 const FormatToken *NamespaceTok = this;
558 if (is(tok::comment))
559 NamespaceTok = NamespaceTok->getNextNonComment();
560 // Detect "(inline|export)? namespace" in the beginning of a line.
561 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
562 NamespaceTok = NamespaceTok->getNextNonComment();
563 return NamespaceTok &&
564 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
571 FormatToken(const FormatToken &) = delete;
572 void operator=(const FormatToken &) = delete;
574 template <typename A, typename... Ts>
575 bool startsSequenceInternal(A K1, Ts... Tokens) const {
576 if (is(tok::comment) && Next)
577 return Next->startsSequenceInternal(K1, Tokens...);
578 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
581 template <typename A> bool startsSequenceInternal(A K1) const {
582 if (is(tok::comment) && Next)
583 return Next->startsSequenceInternal(K1);
587 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
588 if (is(tok::comment) && Previous)
589 return Previous->endsSequenceInternal(K1);
593 template <typename A, typename... Ts>
594 bool endsSequenceInternal(A K1, Ts... Tokens) const {
595 if (is(tok::comment) && Previous)
596 return Previous->endsSequenceInternal(K1, Tokens...);
597 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
600 TokenType Type = TT_Unknown;
603 class ContinuationIndenter;
608 TokenRole(const FormatStyle &Style) : Style(Style) {}
609 virtual ~TokenRole();
611 /// After the \c TokenAnnotator has finished annotating all the tokens,
612 /// this function precomputes required information for formatting.
613 virtual void precomputeFormattingInfos(const FormatToken *Token);
615 /// Apply the special formatting that the given role demands.
617 /// Assumes that the token having this role is already formatted.
619 /// Continues formatting from \p State leaving indentation to \p Indenter and
620 /// returns the total penalty that this formatting incurs.
621 virtual unsigned formatFromToken(LineState &State,
622 ContinuationIndenter *Indenter,
627 /// Same as \c formatFromToken, but assumes that the first token has
628 /// already been set thereby deciding on the first line break.
629 virtual unsigned formatAfterToken(LineState &State,
630 ContinuationIndenter *Indenter,
635 /// Notifies the \c Role that a comma was found.
636 virtual void CommaFound(const FormatToken *Token) {}
638 virtual const FormatToken *lastComma() { return nullptr; }
641 const FormatStyle &Style;
644 class CommaSeparatedList : public TokenRole {
646 CommaSeparatedList(const FormatStyle &Style)
647 : TokenRole(Style), HasNestedBracedList(false) {}
649 void precomputeFormattingInfos(const FormatToken *Token) override;
651 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
652 bool DryRun) override;
654 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
655 bool DryRun) override;
657 /// Adds \p Token as the next comma to the \c CommaSeparated list.
658 void CommaFound(const FormatToken *Token) override {
659 Commas.push_back(Token);
662 const FormatToken *lastComma() override {
665 return Commas.back();
669 /// A struct that holds information on how to format a given list with
670 /// a specific number of columns.
671 struct ColumnFormat {
672 /// The number of columns to use.
675 /// The total width in characters.
678 /// The number of lines required for this format.
681 /// The size of each column in characters.
682 SmallVector<unsigned, 8> ColumnSizes;
685 /// Calculate which \c ColumnFormat fits best into
686 /// \p RemainingCharacters.
687 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
689 /// The ordered \c FormatTokens making up the commas of this list.
690 SmallVector<const FormatToken *, 8> Commas;
692 /// The length of each of the list's items in characters including the
694 SmallVector<unsigned, 8> ItemLengths;
696 /// Precomputed formats that can be used for this list.
697 SmallVector<ColumnFormat, 4> Formats;
699 bool HasNestedBracedList;
702 /// Encapsulates keywords that are context sensitive or for languages not
703 /// properly supported by Clang's lexer.
704 struct AdditionalKeywords {
705 AdditionalKeywords(IdentifierTable &IdentTable) {
706 kw_final = &IdentTable.get("final");
707 kw_override = &IdentTable.get("override");
708 kw_in = &IdentTable.get("in");
709 kw_of = &IdentTable.get("of");
710 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
711 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
712 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
713 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
714 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
715 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
717 kw_as = &IdentTable.get("as");
718 kw_async = &IdentTable.get("async");
719 kw_await = &IdentTable.get("await");
720 kw_declare = &IdentTable.get("declare");
721 kw_finally = &IdentTable.get("finally");
722 kw_from = &IdentTable.get("from");
723 kw_function = &IdentTable.get("function");
724 kw_get = &IdentTable.get("get");
725 kw_import = &IdentTable.get("import");
726 kw_infer = &IdentTable.get("infer");
727 kw_is = &IdentTable.get("is");
728 kw_let = &IdentTable.get("let");
729 kw_module = &IdentTable.get("module");
730 kw_readonly = &IdentTable.get("readonly");
731 kw_set = &IdentTable.get("set");
732 kw_type = &IdentTable.get("type");
733 kw_typeof = &IdentTable.get("typeof");
734 kw_var = &IdentTable.get("var");
735 kw_yield = &IdentTable.get("yield");
737 kw_abstract = &IdentTable.get("abstract");
738 kw_assert = &IdentTable.get("assert");
739 kw_extends = &IdentTable.get("extends");
740 kw_implements = &IdentTable.get("implements");
741 kw_instanceof = &IdentTable.get("instanceof");
742 kw_interface = &IdentTable.get("interface");
743 kw_native = &IdentTable.get("native");
744 kw_package = &IdentTable.get("package");
745 kw_synchronized = &IdentTable.get("synchronized");
746 kw_throws = &IdentTable.get("throws");
747 kw___except = &IdentTable.get("__except");
748 kw___has_include = &IdentTable.get("__has_include");
749 kw___has_include_next = &IdentTable.get("__has_include_next");
751 kw_mark = &IdentTable.get("mark");
753 kw_extend = &IdentTable.get("extend");
754 kw_option = &IdentTable.get("option");
755 kw_optional = &IdentTable.get("optional");
756 kw_repeated = &IdentTable.get("repeated");
757 kw_required = &IdentTable.get("required");
758 kw_returns = &IdentTable.get("returns");
760 kw_signals = &IdentTable.get("signals");
761 kw_qsignals = &IdentTable.get("Q_SIGNALS");
762 kw_slots = &IdentTable.get("slots");
763 kw_qslots = &IdentTable.get("Q_SLOTS");
766 kw_dollar = &IdentTable.get("dollar");
767 kw_base = &IdentTable.get("base");
768 kw_byte = &IdentTable.get("byte");
769 kw_checked = &IdentTable.get("checked");
770 kw_decimal = &IdentTable.get("decimal");
771 kw_delegate = &IdentTable.get("delegate");
772 kw_event = &IdentTable.get("event");
773 kw_fixed = &IdentTable.get("fixed");
774 kw_foreach = &IdentTable.get("foreach");
775 kw_implicit = &IdentTable.get("implicit");
776 kw_internal = &IdentTable.get("internal");
777 kw_lock = &IdentTable.get("lock");
778 kw_null = &IdentTable.get("null");
779 kw_object = &IdentTable.get("object");
780 kw_out = &IdentTable.get("out");
781 kw_params = &IdentTable.get("params");
782 kw_ref = &IdentTable.get("ref");
783 kw_string = &IdentTable.get("string");
784 kw_stackalloc = &IdentTable.get("stackalloc");
785 kw_sbyte = &IdentTable.get("sbyte");
786 kw_sealed = &IdentTable.get("sealed");
787 kw_uint = &IdentTable.get("uint");
788 kw_ulong = &IdentTable.get("ulong");
789 kw_unchecked = &IdentTable.get("unchecked");
790 kw_unsafe = &IdentTable.get("unsafe");
791 kw_ushort = &IdentTable.get("ushort");
792 kw_when = &IdentTable.get("when");
793 kw_where = &IdentTable.get("where");
795 // Keep this at the end of the constructor to make sure everything here
797 // already initialized.
798 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
799 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
800 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
801 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
802 // Keywords from the Java section.
803 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
805 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
806 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event,
807 kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal,
808 kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params,
809 kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed,
810 kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when,
812 // Keywords from the JavaScript section.
813 kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
814 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
815 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
816 // Keywords from the Java section.
817 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
820 // Context sensitive keywords.
821 IdentifierInfo *kw_final;
822 IdentifierInfo *kw_override;
823 IdentifierInfo *kw_in;
824 IdentifierInfo *kw_of;
825 IdentifierInfo *kw_CF_CLOSED_ENUM;
826 IdentifierInfo *kw_CF_ENUM;
827 IdentifierInfo *kw_CF_OPTIONS;
828 IdentifierInfo *kw_NS_CLOSED_ENUM;
829 IdentifierInfo *kw_NS_ENUM;
830 IdentifierInfo *kw_NS_OPTIONS;
831 IdentifierInfo *kw___except;
832 IdentifierInfo *kw___has_include;
833 IdentifierInfo *kw___has_include_next;
835 // JavaScript keywords.
836 IdentifierInfo *kw_as;
837 IdentifierInfo *kw_async;
838 IdentifierInfo *kw_await;
839 IdentifierInfo *kw_declare;
840 IdentifierInfo *kw_finally;
841 IdentifierInfo *kw_from;
842 IdentifierInfo *kw_function;
843 IdentifierInfo *kw_get;
844 IdentifierInfo *kw_import;
845 IdentifierInfo *kw_infer;
846 IdentifierInfo *kw_is;
847 IdentifierInfo *kw_let;
848 IdentifierInfo *kw_module;
849 IdentifierInfo *kw_readonly;
850 IdentifierInfo *kw_set;
851 IdentifierInfo *kw_type;
852 IdentifierInfo *kw_typeof;
853 IdentifierInfo *kw_var;
854 IdentifierInfo *kw_yield;
857 IdentifierInfo *kw_abstract;
858 IdentifierInfo *kw_assert;
859 IdentifierInfo *kw_extends;
860 IdentifierInfo *kw_implements;
861 IdentifierInfo *kw_instanceof;
862 IdentifierInfo *kw_interface;
863 IdentifierInfo *kw_native;
864 IdentifierInfo *kw_package;
865 IdentifierInfo *kw_synchronized;
866 IdentifierInfo *kw_throws;
869 IdentifierInfo *kw_mark;
872 IdentifierInfo *kw_extend;
873 IdentifierInfo *kw_option;
874 IdentifierInfo *kw_optional;
875 IdentifierInfo *kw_repeated;
876 IdentifierInfo *kw_required;
877 IdentifierInfo *kw_returns;
880 IdentifierInfo *kw_signals;
881 IdentifierInfo *kw_qsignals;
882 IdentifierInfo *kw_slots;
883 IdentifierInfo *kw_qslots;
886 IdentifierInfo *kw_dollar;
887 IdentifierInfo *kw_base;
888 IdentifierInfo *kw_byte;
889 IdentifierInfo *kw_checked;
890 IdentifierInfo *kw_decimal;
891 IdentifierInfo *kw_delegate;
892 IdentifierInfo *kw_event;
893 IdentifierInfo *kw_fixed;
894 IdentifierInfo *kw_foreach;
895 IdentifierInfo *kw_implicit;
896 IdentifierInfo *kw_internal;
898 IdentifierInfo *kw_lock;
899 IdentifierInfo *kw_null;
900 IdentifierInfo *kw_object;
901 IdentifierInfo *kw_out;
903 IdentifierInfo *kw_params;
905 IdentifierInfo *kw_ref;
906 IdentifierInfo *kw_string;
907 IdentifierInfo *kw_stackalloc;
908 IdentifierInfo *kw_sbyte;
909 IdentifierInfo *kw_sealed;
910 IdentifierInfo *kw_uint;
911 IdentifierInfo *kw_ulong;
912 IdentifierInfo *kw_unchecked;
913 IdentifierInfo *kw_unsafe;
914 IdentifierInfo *kw_ushort;
915 IdentifierInfo *kw_when;
916 IdentifierInfo *kw_where;
918 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
919 /// \c false if it is a keyword or a pseudo keyword.
920 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
921 // but also for IdentifierName tokens (aka pseudo-keywords), such as
923 bool IsJavaScriptIdentifier(const FormatToken &Tok,
924 bool AcceptIdentifierName = true) const {
925 // Based on the list of JavaScript & TypeScript keywords here:
926 // https://github.com/microsoft/TypeScript/blob/master/src/compiler/scanner.ts#L74
927 switch (Tok.Tok.getKind()) {
932 case tok::kw_continue:
934 case tok::kw_default:
946 case tok::kw_private:
947 case tok::kw_protected:
959 // These are JS keywords that are lexed by LLVM/clang as keywords.
961 case tok::identifier: {
962 // For identifiers, make sure they are true identifiers, excluding the
963 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
964 bool IsPseudoKeyword =
965 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
966 JsExtraKeywords.end();
967 return AcceptIdentifierName || !IsPseudoKeyword;
970 // Other keywords are handled in the switch below, to avoid problems due
971 // to duplicate case labels when using the #include trick.
975 switch (Tok.Tok.getKind()) {
976 // Handle C++ keywords not included above: these are all JS identifiers.
977 #define KEYWORD(X, Y) case tok::kw_##X:
978 #include "clang/Basic/TokenKinds.def"
979 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
983 // All other tokens (punctuation etc) are not JS identifiers.
988 /// Returns \c true if \p Tok is a C# keyword, returns
989 /// \c false if it is a anything else.
990 bool isCSharpKeyword(const FormatToken &Tok) const {
991 switch (Tok.Tok.getKind()) {
999 case tok::kw_continue:
1000 case tok::kw_default:
1002 case tok::kw_double:
1005 case tok::kw_explicit:
1006 case tok::kw_extern:
1014 case tok::kw_namespace:
1016 case tok::kw_operator:
1017 case tok::kw_private:
1018 case tok::kw_protected:
1019 case tok::kw_public:
1020 case tok::kw_return:
1022 case tok::kw_sizeof:
1023 case tok::kw_static:
1024 case tok::kw_struct:
1025 case tok::kw_switch:
1030 case tok::kw_typeof:
1032 case tok::kw_virtual:
1034 case tok::kw_volatile:
1038 return Tok.is(tok::identifier) &&
1039 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1040 CSharpExtraKeywords.end();
1045 /// The JavaScript keywords beyond the C++ keyword set.
1046 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
1048 /// The C# keywords beyond the C++ keyword set
1049 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
1052 } // namespace format
1053 } // namespace clang