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(JavaAnnotation) \
58 TYPE(JsComputedPropertyName) \
59 TYPE(JsExponentiation) \
60 TYPE(JsExponentiationEqual) \
62 TYPE(JsNonNullAssertion) \
63 TYPE(JsNullishCoalescingOperator) \
64 TYPE(JsNullPropagatingOperator) \
65 TYPE(JsPrivateIdentifier) \
67 TYPE(JsTypeOperator) \
68 TYPE(JsTypeOptionalQuestion) \
72 TYPE(LeadingJavaAnnotation) \
74 TYPE(MacroBlockBegin) \
76 TYPE(NamespaceMacro) \
77 TYPE(ObjCBlockLBrace) \
78 TYPE(ObjCBlockLParen) \
81 TYPE(ObjCMethodExpr) \
82 TYPE(ObjCMethodSpecifier) \
84 TYPE(ObjCStringLiteral) \
85 TYPE(OverloadedOperator) \
86 TYPE(OverloadedOperatorLParen) \
87 TYPE(PointerOrReference) \
88 TYPE(PureVirtualSpecifier) \
89 TYPE(RangeBasedForLoopColon) \
93 TYPE(StatementMacro) \
94 TYPE(StructuredBindingLSquare) \
95 TYPE(TemplateCloser) \
96 TYPE(TemplateOpener) \
97 TYPE(TemplateString) \
98 TYPE(ProtoExtensionLSquare) \
99 TYPE(TrailingAnnotation) \
100 TYPE(TrailingReturnArrow) \
101 TYPE(TrailingUnaryOperator) \
102 TYPE(TypenameMacro) \
103 TYPE(UnaryOperator) \
104 TYPE(CSharpStringLiteral) \
105 TYPE(CSharpNullCoalescing) \
109 #define TYPE(X) TT_##X,
115 /// Determines the name of a token type.
116 const char *getTokenTypeName(TokenType Type);
118 // Represents what type of block a set of braces open.
119 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
121 // The packing kind of a function's parameters.
122 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
124 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
129 /// A wrapper around a \c Token storing information about the
130 /// whitespace characters preceding it.
137 /// The number of newlines immediately before the \c Token.
139 /// This can be used to determine what the user wrote in the original code
140 /// and thereby e.g. leave an empty line between two function definitions.
141 unsigned NewlinesBefore = 0;
143 /// Whether there is at least one unescaped newline before the \c
145 bool HasUnescapedNewline = false;
147 /// The range of the whitespace immediately preceding the \c Token.
148 SourceRange WhitespaceRange;
150 /// The offset just past the last '\n' in this token's leading
151 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
152 unsigned LastNewlineOffset = 0;
154 /// The width of the non-whitespace parts of the token (or its first
155 /// line for multi-line tokens) in columns.
156 /// We need this to correctly measure number of columns a token spans.
157 unsigned ColumnWidth = 0;
159 /// Contains the width in columns of the last line of a multi-line
161 unsigned LastLineColumnWidth = 0;
163 /// Whether the token text contains newlines (escaped or not).
164 bool IsMultiline = false;
166 /// Indicates that this is the first token of the file.
167 bool IsFirst = false;
169 /// Whether there must be a line break before this token.
171 /// This happens for example when a preprocessor directive ended directly
172 /// before the token.
173 bool MustBreakBefore = false;
175 /// The raw text of the token.
177 /// Contains the raw token text without leading whitespace and without leading
178 /// escaped newlines.
181 /// Set to \c true if this token is an unterminated literal.
182 bool IsUnterminatedLiteral = 0;
184 /// Contains the kind of block if this token is a brace.
185 BraceBlockKind BlockKind = BK_Unknown;
187 TokenType Type = TT_Unknown;
189 /// The number of spaces that should be inserted before this token.
190 unsigned SpacesRequiredBefore = 0;
192 /// \c true if it is allowed to break before this token.
193 bool CanBreakBefore = false;
195 /// \c true if this is the ">" of "template<..>".
196 bool ClosesTemplateDeclaration = false;
198 /// Number of parameters, if this is "(", "[" or "<".
199 unsigned ParameterCount = 0;
201 /// Number of parameters that are nested blocks,
202 /// if this is "(", "[" or "<".
203 unsigned BlockParameterCount = 0;
205 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
206 /// the surrounding bracket.
207 tok::TokenKind ParentBracket = tok::unknown;
209 /// A token can have a special role that can carry extra information
210 /// about the token's formatting.
211 std::unique_ptr<TokenRole> Role;
213 /// If this is an opening parenthesis, how are the parameters packed?
214 ParameterPackingKind PackingKind = PPK_Inconclusive;
216 /// The total length of the unwrapped line up to and including this
218 unsigned TotalLength = 0;
220 /// The original 0-based column of this token, including expanded tabs.
221 /// The configured TabWidth is used as tab width.
222 unsigned OriginalColumn = 0;
224 /// The length of following tokens until the next natural split point,
225 /// or the next token that can be broken.
226 unsigned UnbreakableTailLength = 0;
228 // FIXME: Come up with a 'cleaner' concept.
229 /// The binding strength of a token. This is a combined value of
230 /// operator precedence, parenthesis nesting, etc.
231 unsigned BindingStrength = 0;
233 /// The nesting level of this token, i.e. the number of surrounding (),
235 unsigned NestingLevel = 0;
237 /// The indent level of this token. Copied from the surrounding line.
238 unsigned IndentLevel = 0;
240 /// Penalty for inserting a line break before this token.
241 unsigned SplitPenalty = 0;
243 /// If this is the first ObjC selector name in an ObjC method
244 /// definition or call, this contains the length of the longest name.
246 /// This being set to 0 means that the selectors should not be colon-aligned,
247 /// e.g. because several of them are block-type.
248 unsigned LongestObjCSelectorName = 0;
250 /// If this is the first ObjC selector name in an ObjC method
251 /// definition or call, this contains the number of parts that the whole
252 /// selector consist of.
253 unsigned ObjCSelectorNameParts = 0;
255 /// The 0-based index of the parameter/argument. For ObjC it is set
256 /// for the selector name token.
257 /// For now calculated only for ObjC.
258 unsigned ParameterIndex = 0;
260 /// Stores the number of required fake parentheses and the
261 /// corresponding operator precedence.
263 /// If multiple fake parentheses start at a token, this vector stores them in
264 /// reverse order, i.e. inner fake parenthesis first.
265 SmallVector<prec::Level, 4> FakeLParens;
266 /// Insert this many fake ) after this token for correct indentation.
267 unsigned FakeRParens = 0;
269 /// \c true if this token starts a binary expression, i.e. has at least
270 /// one fake l_paren with a precedence greater than prec::Unknown.
271 bool StartsBinaryExpression = false;
272 /// \c true if this token ends a binary expression.
273 bool EndsBinaryExpression = false;
275 /// If this is an operator (or "."/"->") in a sequence of operators
276 /// with the same precedence, contains the 0-based operator index.
277 unsigned OperatorIndex = 0;
279 /// If this is an operator (or "."/"->") in a sequence of operators
280 /// with the same precedence, points to the next operator.
281 FormatToken *NextOperator = nullptr;
283 /// Is this token part of a \c DeclStmt defining multiple variables?
285 /// Only set if \c Type == \c TT_StartOfName.
286 bool PartOfMultiVariableDeclStmt = false;
288 /// Does this line comment continue a line comment section?
290 /// Only set to true if \c Type == \c TT_LineComment.
291 bool ContinuesLineCommentSection = false;
293 /// If this is a bracket, this points to the matching one.
294 FormatToken *MatchingParen = nullptr;
296 /// The previous token in the unwrapped line.
297 FormatToken *Previous = nullptr;
299 /// The next token in the unwrapped line.
300 FormatToken *Next = nullptr;
302 /// If this token starts a block, this contains all the unwrapped lines
304 SmallVector<AnnotatedLine *, 1> Children;
306 /// Stores the formatting decision for the token once it was made.
307 FormatDecision Decision = FD_Unformatted;
309 /// If \c true, this token has been fully formatted (indented and
310 /// potentially re-formatted inside), and we do not allow further formatting
312 bool Finalized = false;
314 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
315 bool is(TokenType TT) const { return Type == TT; }
316 bool is(const IdentifierInfo *II) const {
317 return II && II == Tok.getIdentifierInfo();
319 bool is(tok::PPKeywordKind Kind) const {
320 return Tok.getIdentifierInfo() &&
321 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
323 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
324 return is(K1) || is(K2);
326 template <typename A, typename B, typename... Ts>
327 bool isOneOf(A K1, B K2, Ts... Ks) const {
328 return is(K1) || isOneOf(K2, Ks...);
330 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
332 bool isIf(bool AllowConstexprMacro = true) const {
333 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
334 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
337 bool closesScopeAfterBlock() const {
338 if (BlockKind == BK_Block)
341 return Previous->closesScopeAfterBlock();
345 /// \c true if this token starts a sequence with the given tokens in order,
346 /// following the ``Next`` pointers, ignoring comments.
347 template <typename A, typename... Ts>
348 bool startsSequence(A K1, Ts... Tokens) const {
349 return startsSequenceInternal(K1, Tokens...);
352 /// \c true if this token ends a sequence with the given tokens in order,
353 /// following the ``Previous`` pointers, ignoring comments.
354 /// For example, given tokens [T1, T2, T3], the function returns true if
355 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
356 /// words, the tokens passed to this function need to the reverse of the
357 /// order the tokens appear in code.
358 template <typename A, typename... Ts>
359 bool endsSequence(A K1, Ts... Tokens) const {
360 return endsSequenceInternal(K1, Tokens...);
363 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
365 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
366 return Tok.isObjCAtKeyword(Kind);
369 bool isAccessSpecifier(bool ColonRequired = true) const {
370 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
371 (!ColonRequired || (Next && Next->is(tok::colon)));
374 /// Determine whether the token is a simple-type-specifier.
375 bool isSimpleTypeSpecifier() const;
377 bool isObjCAccessSpecifier() const {
378 return is(tok::at) && Next &&
379 (Next->isObjCAtKeyword(tok::objc_public) ||
380 Next->isObjCAtKeyword(tok::objc_protected) ||
381 Next->isObjCAtKeyword(tok::objc_package) ||
382 Next->isObjCAtKeyword(tok::objc_private));
385 /// Returns whether \p Tok is ([{ or an opening < of a template or in
387 bool opensScope() const {
388 if (is(TT_TemplateString) && TokenText.endswith("${"))
390 if (is(TT_DictLiteral) && is(tok::less))
392 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
395 /// Returns whether \p Tok is )]} or a closing > of a template or in
397 bool closesScope() const {
398 if (is(TT_TemplateString) && TokenText.startswith("}"))
400 if (is(TT_DictLiteral) && is(tok::greater))
402 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
406 /// Returns \c true if this is a "." or "->" accessing a member.
407 bool isMemberAccess() const {
408 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
409 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
410 TT_LambdaArrow, TT_LeadingJavaAnnotation);
413 bool isUnaryOperator() const {
414 switch (Tok.getKind()) {
418 case tok::minusminus:
422 case tok::kw_alignof:
429 bool isBinaryOperator() const {
430 // Comma is a binary operator, but does not behave as such wrt. formatting.
431 return getPrecedence() > prec::Comma;
434 bool isTrailingComment() const {
435 return is(tok::comment) &&
436 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
439 /// Returns \c true if this is a keyword that can be used
440 /// like a function call (e.g. sizeof, typeid, ...).
441 bool isFunctionLikeKeyword() const {
442 switch (Tok.getKind()) {
447 case tok::kw_alignof:
448 case tok::kw_alignas:
449 case tok::kw_decltype:
450 case tok::kw_noexcept:
451 case tok::kw_static_assert:
452 case tok::kw___attribute:
459 /// Returns \c true if this is a string literal that's like a label,
460 /// e.g. ends with "=" or ":".
461 bool isLabelString() const {
462 if (!is(tok::string_literal))
464 StringRef Content = TokenText;
465 if (Content.startswith("\"") || Content.startswith("'"))
466 Content = Content.drop_front(1);
467 if (Content.endswith("\"") || Content.endswith("'"))
468 Content = Content.drop_back(1);
469 Content = Content.trim();
470 return Content.size() > 1 &&
471 (Content.back() == ':' || Content.back() == '=');
474 /// Returns actual token start location without leading escaped
475 /// newlines and whitespace.
477 /// This can be different to Tok.getLocation(), which includes leading escaped
479 SourceLocation getStartOfNonWhitespace() const {
480 return WhitespaceRange.getEnd();
483 prec::Level getPrecedence() const {
484 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
485 /*CPlusPlus11=*/true);
488 /// Returns the previous token ignoring comments.
489 FormatToken *getPreviousNonComment() const {
490 FormatToken *Tok = Previous;
491 while (Tok && Tok->is(tok::comment))
496 /// Returns the next token ignoring comments.
497 const FormatToken *getNextNonComment() const {
498 const FormatToken *Tok = Next;
499 while (Tok && Tok->is(tok::comment))
504 /// Returns \c true if this tokens starts a block-type list, i.e. a
505 /// list that should be indented with a block indent.
506 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
507 if (is(TT_TemplateString) && opensScope())
509 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
511 (BlockKind == BK_Block || is(TT_DictLiteral) ||
512 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
513 (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
514 Style.Language == FormatStyle::LK_TextProto));
517 /// Returns whether the token is the left square bracket of a C++
518 /// structured binding declaration.
519 bool isCppStructuredBinding(const FormatStyle &Style) const {
520 if (!Style.isCpp() || isNot(tok::l_square))
522 const FormatToken *T = this;
524 T = T->getPreviousNonComment();
525 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
527 return T && T->is(tok::kw_auto);
530 /// Same as opensBlockOrBlockTypeList, but for the closing token.
531 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
532 if (is(TT_TemplateString) && closesScope())
534 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
537 /// Return the actual namespace token, if this token starts a namespace
539 const FormatToken *getNamespaceToken() const {
540 const FormatToken *NamespaceTok = this;
541 if (is(tok::comment))
542 NamespaceTok = NamespaceTok->getNextNonComment();
543 // Detect "(inline|export)? namespace" in the beginning of a line.
544 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
545 NamespaceTok = NamespaceTok->getNextNonComment();
546 return NamespaceTok &&
547 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
554 FormatToken(const FormatToken &) = delete;
555 void operator=(const FormatToken &) = delete;
557 template <typename A, typename... Ts>
558 bool startsSequenceInternal(A K1, Ts... Tokens) const {
559 if (is(tok::comment) && Next)
560 return Next->startsSequenceInternal(K1, Tokens...);
561 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
564 template <typename A> bool startsSequenceInternal(A K1) const {
565 if (is(tok::comment) && Next)
566 return Next->startsSequenceInternal(K1);
570 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
571 if (is(tok::comment) && Previous)
572 return Previous->endsSequenceInternal(K1);
576 template <typename A, typename... Ts>
577 bool endsSequenceInternal(A K1, Ts... Tokens) const {
578 if (is(tok::comment) && Previous)
579 return Previous->endsSequenceInternal(K1, Tokens...);
580 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
584 class ContinuationIndenter;
589 TokenRole(const FormatStyle &Style) : Style(Style) {}
590 virtual ~TokenRole();
592 /// After the \c TokenAnnotator has finished annotating all the tokens,
593 /// this function precomputes required information for formatting.
594 virtual void precomputeFormattingInfos(const FormatToken *Token);
596 /// Apply the special formatting that the given role demands.
598 /// Assumes that the token having this role is already formatted.
600 /// Continues formatting from \p State leaving indentation to \p Indenter and
601 /// returns the total penalty that this formatting incurs.
602 virtual unsigned formatFromToken(LineState &State,
603 ContinuationIndenter *Indenter,
608 /// Same as \c formatFromToken, but assumes that the first token has
609 /// already been set thereby deciding on the first line break.
610 virtual unsigned formatAfterToken(LineState &State,
611 ContinuationIndenter *Indenter,
616 /// Notifies the \c Role that a comma was found.
617 virtual void CommaFound(const FormatToken *Token) {}
619 virtual const FormatToken *lastComma() { return nullptr; }
622 const FormatStyle &Style;
625 class CommaSeparatedList : public TokenRole {
627 CommaSeparatedList(const FormatStyle &Style)
628 : TokenRole(Style), HasNestedBracedList(false) {}
630 void precomputeFormattingInfos(const FormatToken *Token) override;
632 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
633 bool DryRun) override;
635 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
636 bool DryRun) override;
638 /// Adds \p Token as the next comma to the \c CommaSeparated list.
639 void CommaFound(const FormatToken *Token) override {
640 Commas.push_back(Token);
643 const FormatToken *lastComma() override {
646 return Commas.back();
650 /// A struct that holds information on how to format a given list with
651 /// a specific number of columns.
652 struct ColumnFormat {
653 /// The number of columns to use.
656 /// The total width in characters.
659 /// The number of lines required for this format.
662 /// The size of each column in characters.
663 SmallVector<unsigned, 8> ColumnSizes;
666 /// Calculate which \c ColumnFormat fits best into
667 /// \p RemainingCharacters.
668 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
670 /// The ordered \c FormatTokens making up the commas of this list.
671 SmallVector<const FormatToken *, 8> Commas;
673 /// The length of each of the list's items in characters including the
675 SmallVector<unsigned, 8> ItemLengths;
677 /// Precomputed formats that can be used for this list.
678 SmallVector<ColumnFormat, 4> Formats;
680 bool HasNestedBracedList;
683 /// Encapsulates keywords that are context sensitive or for languages not
684 /// properly supported by Clang's lexer.
685 struct AdditionalKeywords {
686 AdditionalKeywords(IdentifierTable &IdentTable) {
687 kw_final = &IdentTable.get("final");
688 kw_override = &IdentTable.get("override");
689 kw_in = &IdentTable.get("in");
690 kw_of = &IdentTable.get("of");
691 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
692 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
693 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
694 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
695 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
696 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
698 kw_as = &IdentTable.get("as");
699 kw_async = &IdentTable.get("async");
700 kw_await = &IdentTable.get("await");
701 kw_declare = &IdentTable.get("declare");
702 kw_finally = &IdentTable.get("finally");
703 kw_from = &IdentTable.get("from");
704 kw_function = &IdentTable.get("function");
705 kw_get = &IdentTable.get("get");
706 kw_import = &IdentTable.get("import");
707 kw_infer = &IdentTable.get("infer");
708 kw_is = &IdentTable.get("is");
709 kw_let = &IdentTable.get("let");
710 kw_module = &IdentTable.get("module");
711 kw_readonly = &IdentTable.get("readonly");
712 kw_set = &IdentTable.get("set");
713 kw_type = &IdentTable.get("type");
714 kw_typeof = &IdentTable.get("typeof");
715 kw_var = &IdentTable.get("var");
716 kw_yield = &IdentTable.get("yield");
718 kw_abstract = &IdentTable.get("abstract");
719 kw_assert = &IdentTable.get("assert");
720 kw_extends = &IdentTable.get("extends");
721 kw_implements = &IdentTable.get("implements");
722 kw_instanceof = &IdentTable.get("instanceof");
723 kw_interface = &IdentTable.get("interface");
724 kw_native = &IdentTable.get("native");
725 kw_package = &IdentTable.get("package");
726 kw_synchronized = &IdentTable.get("synchronized");
727 kw_throws = &IdentTable.get("throws");
728 kw___except = &IdentTable.get("__except");
729 kw___has_include = &IdentTable.get("__has_include");
730 kw___has_include_next = &IdentTable.get("__has_include_next");
732 kw_mark = &IdentTable.get("mark");
734 kw_extend = &IdentTable.get("extend");
735 kw_option = &IdentTable.get("option");
736 kw_optional = &IdentTable.get("optional");
737 kw_repeated = &IdentTable.get("repeated");
738 kw_required = &IdentTable.get("required");
739 kw_returns = &IdentTable.get("returns");
741 kw_signals = &IdentTable.get("signals");
742 kw_qsignals = &IdentTable.get("Q_SIGNALS");
743 kw_slots = &IdentTable.get("slots");
744 kw_qslots = &IdentTable.get("Q_SLOTS");
747 kw_dollar = &IdentTable.get("dollar");
748 kw_base = &IdentTable.get("base");
749 kw_byte = &IdentTable.get("byte");
750 kw_checked = &IdentTable.get("checked");
751 kw_decimal = &IdentTable.get("decimal");
752 kw_delegate = &IdentTable.get("delegate");
753 kw_event = &IdentTable.get("event");
754 kw_fixed = &IdentTable.get("fixed");
755 kw_foreach = &IdentTable.get("foreach");
756 kw_implicit = &IdentTable.get("implicit");
757 kw_internal = &IdentTable.get("internal");
758 kw_lock = &IdentTable.get("lock");
759 kw_null = &IdentTable.get("null");
760 kw_object = &IdentTable.get("object");
761 kw_out = &IdentTable.get("out");
762 kw_params = &IdentTable.get("params");
763 kw_ref = &IdentTable.get("ref");
764 kw_string = &IdentTable.get("string");
765 kw_stackalloc = &IdentTable.get("stackalloc");
766 kw_sbyte = &IdentTable.get("sbyte");
767 kw_sealed = &IdentTable.get("sealed");
768 kw_uint = &IdentTable.get("uint");
769 kw_ulong = &IdentTable.get("ulong");
770 kw_unchecked = &IdentTable.get("unchecked");
771 kw_unsafe = &IdentTable.get("unsafe");
772 kw_ushort = &IdentTable.get("ushort");
774 // Keep this at the end of the constructor to make sure everything here
776 // already initialized.
777 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
778 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
779 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
780 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
781 // Keywords from the Java section.
782 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
784 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
785 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event,
786 kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal,
787 kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params,
788 kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed,
789 kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort,
790 // Keywords from the JavaScript section.
791 kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
792 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
793 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
794 // Keywords from the Java section.
795 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
798 // Context sensitive keywords.
799 IdentifierInfo *kw_final;
800 IdentifierInfo *kw_override;
801 IdentifierInfo *kw_in;
802 IdentifierInfo *kw_of;
803 IdentifierInfo *kw_CF_CLOSED_ENUM;
804 IdentifierInfo *kw_CF_ENUM;
805 IdentifierInfo *kw_CF_OPTIONS;
806 IdentifierInfo *kw_NS_CLOSED_ENUM;
807 IdentifierInfo *kw_NS_ENUM;
808 IdentifierInfo *kw_NS_OPTIONS;
809 IdentifierInfo *kw___except;
810 IdentifierInfo *kw___has_include;
811 IdentifierInfo *kw___has_include_next;
813 // JavaScript keywords.
814 IdentifierInfo *kw_as;
815 IdentifierInfo *kw_async;
816 IdentifierInfo *kw_await;
817 IdentifierInfo *kw_declare;
818 IdentifierInfo *kw_finally;
819 IdentifierInfo *kw_from;
820 IdentifierInfo *kw_function;
821 IdentifierInfo *kw_get;
822 IdentifierInfo *kw_import;
823 IdentifierInfo *kw_infer;
824 IdentifierInfo *kw_is;
825 IdentifierInfo *kw_let;
826 IdentifierInfo *kw_module;
827 IdentifierInfo *kw_readonly;
828 IdentifierInfo *kw_set;
829 IdentifierInfo *kw_type;
830 IdentifierInfo *kw_typeof;
831 IdentifierInfo *kw_var;
832 IdentifierInfo *kw_yield;
835 IdentifierInfo *kw_abstract;
836 IdentifierInfo *kw_assert;
837 IdentifierInfo *kw_extends;
838 IdentifierInfo *kw_implements;
839 IdentifierInfo *kw_instanceof;
840 IdentifierInfo *kw_interface;
841 IdentifierInfo *kw_native;
842 IdentifierInfo *kw_package;
843 IdentifierInfo *kw_synchronized;
844 IdentifierInfo *kw_throws;
847 IdentifierInfo *kw_mark;
850 IdentifierInfo *kw_extend;
851 IdentifierInfo *kw_option;
852 IdentifierInfo *kw_optional;
853 IdentifierInfo *kw_repeated;
854 IdentifierInfo *kw_required;
855 IdentifierInfo *kw_returns;
858 IdentifierInfo *kw_signals;
859 IdentifierInfo *kw_qsignals;
860 IdentifierInfo *kw_slots;
861 IdentifierInfo *kw_qslots;
864 IdentifierInfo *kw_dollar;
865 IdentifierInfo *kw_base;
866 IdentifierInfo *kw_byte;
867 IdentifierInfo *kw_checked;
868 IdentifierInfo *kw_decimal;
869 IdentifierInfo *kw_delegate;
870 IdentifierInfo *kw_event;
871 IdentifierInfo *kw_fixed;
872 IdentifierInfo *kw_foreach;
873 IdentifierInfo *kw_implicit;
874 IdentifierInfo *kw_internal;
876 IdentifierInfo *kw_lock;
877 IdentifierInfo *kw_null;
878 IdentifierInfo *kw_object;
879 IdentifierInfo *kw_out;
881 IdentifierInfo *kw_params;
883 IdentifierInfo *kw_ref;
884 IdentifierInfo *kw_string;
885 IdentifierInfo *kw_stackalloc;
886 IdentifierInfo *kw_sbyte;
887 IdentifierInfo *kw_sealed;
888 IdentifierInfo *kw_uint;
889 IdentifierInfo *kw_ulong;
890 IdentifierInfo *kw_unchecked;
891 IdentifierInfo *kw_unsafe;
892 IdentifierInfo *kw_ushort;
894 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
895 /// \c false if it is a keyword or a pseudo keyword.
896 bool IsJavaScriptIdentifier(const FormatToken &Tok) const {
897 return Tok.is(tok::identifier) &&
898 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
899 JsExtraKeywords.end();
902 /// Returns \c true if \p Tok is a C# keyword, returns
903 /// \c false if it is a anything else.
904 bool isCSharpKeyword(const FormatToken &Tok) const {
905 switch (Tok.Tok.getKind()) {
913 case tok::kw_continue:
914 case tok::kw_default:
919 case tok::kw_explicit:
928 case tok::kw_namespace:
930 case tok::kw_operator:
931 case tok::kw_private:
932 case tok::kw_protected:
946 case tok::kw_virtual:
948 case tok::kw_volatile:
952 return Tok.is(tok::identifier) &&
953 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
954 CSharpExtraKeywords.end();
959 /// The JavaScript keywords beyond the C++ keyword set.
960 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
962 /// The C# keywords beyond the C++ keyword set
963 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
966 } // namespace format