clang 24.0.0git
Parser.h
Go to the documentation of this file.
1//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Parser interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_PARSE_PARSER_H
14#define LLVM_CLANG_PARSE_PARSER_H
15
20#include "clang/Sema/Sema.h"
22#include "clang/Sema/SemaObjC.h"
24#include "llvm/ADT/STLForwardCompat.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Frontend/OpenMP/OMPContext.h"
27#include "llvm/Support/SaveAndRestore.h"
28#include <optional>
29#include <stack>
30
31namespace clang {
32class PragmaHandler;
33class Scope;
36class DeclGroupRef;
38struct LoopHint;
39class Parser;
41class ParsingDeclSpec;
47class OMPClause;
48class OpenACCClause;
50struct OMPTraitProperty;
51struct OMPTraitSelector;
52struct OMPTraitSet;
53class OMPTraitInfo;
54
56 /// Annotation has failed and emitted an error.
58 /// The identifier is a tentatively-declared name.
60 /// The identifier is a template name. FIXME: Add an annotation for that.
62 /// The identifier can't be resolved.
64 /// Annotation was successful.
66};
67
68/// The kind of extra semi diagnostic to emit.
75
76/// The kind of template we are parsing.
78 /// We are not parsing a template at all.
80 /// We are parsing a template declaration.
82 /// We are parsing an explicit specialization.
84 /// We are parsing an explicit instantiation.
86};
87
89
90// Definitions for Objective-c context sensitive keywords recognition.
103
104/// If a typo should be encountered, should typo correction suggest type names,
105/// non type names, or both?
111
112/// Control what ParseCastExpression will parse.
114
115/// ParenParseOption - Control what ParseParenExpression will parse.
117 SimpleExpr, // Only parse '(' expression ')'
118 FoldExpr, // Also allow fold-expression <anything>
119 CompoundStmt, // Also allow '(' compound-statement ')'
120 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
121 CastExpr // Also allow '(' type-name ')' <anything>
122};
123
124/// In a call to ParseParenExpression, are the initial parentheses part of an
125/// operator that requires the parens be there (like typeof(int)) or could they
126/// be something else, such as part of a compound literal or a sizeof
127/// expression, etc.
128enum class ParenExprKind {
129 PartOfOperator, // typeof(int)
130 Unknown, // sizeof(int) or sizeof (int)1.0f, or compound literal, etc
131};
132
133/// Describes the behavior that should be taken for an __if_exists
134/// block.
136 /// Parse the block; this code is always used.
138 /// Skip the block entirely; this code is never used.
140 /// Parse the block as a dependent block, which may be used in
141 /// some template instantiations but not others.
143};
144
145/// Specifies the context in which type-id/expression
146/// disambiguation will occur.
155
156/// The kind of attribute specifier we have found.
158 /// This is not an attribute specifier.
160 /// This should be treated as an attribute-specifier.
162 /// The next tokens are '[[', but this is not an attribute-specifier. This
163 /// is ill-formed by C++11 [dcl.attr.grammar]p6.
165};
166
167/// [class.mem]p1: "... the class is regarded as complete within
168/// - function bodies
169/// - default arguments
170/// - exception-specifications (TODO: C++0x)
171/// - and brace-or-equal-initializers for non-static data members
172/// (including such things in nested classes)."
173/// LateParsedDeclarations build the tree of those elements so they can
174/// be parsed after parsing the top-level class.
176public:
177 virtual ~LateParsedDeclaration();
178
179 virtual void ParseLexedMethodDeclarations();
180 virtual void ParseLexedMemberInitializers();
181 virtual void ParseLexedMethodDefs();
182 virtual void ParseLexedAttributes();
183 virtual void ParseLexedPragmas();
184};
185
186/// Contains the lexed tokens of an attribute with arguments that
187/// may reference member variables and so need to be parsed at the
188/// end of the class declaration after parsing all other member
189/// member declarations.
190/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
191/// LateParsedTokens.
193
194 enum class Kind {
197 };
198
205
206private:
207 Kind K;
208
209protected:
211 SourceLocation Loc, Kind K)
212 : Self(P), AttrName(Name), AttrNameLoc(Loc), K(K) {}
213
214public:
216 SourceLocation Loc)
217 : LateParsedAttribute(P, Name, Loc, Kind::Declaration) {}
218
219 void ParseLexedAttributes() override;
220
221 void addDecl(Decl *D) { Decls.push_back(D); }
222
223 Kind getKind() const { return K; }
224
225 static bool classof(const LateParsedAttribute *LA) { return true; }
226};
227
228/// A late-parsed attribute that will be applied as a type attribute.
229/// Unlike LateParsedAttribute (which applies to declarations via
230/// ActOnFinishDelayedAttribute), this stores cached tokens that are
231/// parsed during type construction when the placeholder LateParsedAttrType
232/// is replaced with a concrete type (e.g., CountAttributedType).
234
236 SourceLocation Loc)
237 : LateParsedAttribute(P, Name, Loc, Kind::Type) {}
238
239 void ParseLexedAttributes() override;
240
241 /// Parse this late-parsed type attribute and store results in OutAttrs.
242 /// This method can be called from Sema during type transformation to
243 /// parse the cached tokens and produce the final attribute.
244 void ParseInto(ParsedAttributes &OutAttrs);
245
246 static bool classof(const LateParsedAttribute *LA) {
247 return LA->getKind() == Kind::Type;
248 }
249};
250
251/// Parser - This implements a parser for the C family of languages. After
252/// parsing units of the grammar, productions are invoked to handle whatever has
253/// been read.
254///
255/// \nosubgrouping
257 // Table of Contents
258 // -----------------
259 // 1. Parsing (Parser.cpp)
260 // 2. C++ Class Inline Methods (ParseCXXInlineMethods.cpp)
261 // 3. Declarations (ParseDecl.cpp)
262 // 4. C++ Declarations (ParseDeclCXX.cpp)
263 // 5. Expressions (ParseExpr.cpp)
264 // 6. C++ Expressions (ParseExprCXX.cpp)
265 // 7. HLSL Constructs (ParseHLSL.cpp)
266 // 8. Initializers (ParseInit.cpp)
267 // 9. Objective-C Constructs (ParseObjc.cpp)
268 // 10. OpenACC Constructs (ParseOpenACC.cpp)
269 // 11. OpenMP Constructs (ParseOpenMP.cpp)
270 // 12. Pragmas (ParsePragma.cpp)
271 // 13. Statements (ParseStmt.cpp)
272 // 14. `inline asm` Statement (ParseStmtAsm.cpp)
273 // 15. C++ Templates (ParseTemplate.cpp)
274 // 16. Tentative Parsing (ParseTentative.cpp)
275
276 /// \name Parsing
277 /// Implementations are in Parser.cpp
278 ///@{
279
280public:
285
286 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
287 ~Parser() override;
288
289 const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
290 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
291 Preprocessor &getPreprocessor() const { return PP; }
292 Sema &getActions() const { return Actions; }
293 AttributeFactory &getAttrFactory() { return AttrFactory; }
294
295 const Token &getCurToken() const { return Tok; }
296 Scope *getCurScope() const { return Actions.getCurScope(); }
297
299 return Actions.incrementMSManglingNumber();
300 }
301
302 // Type forwarding. All of these are statically 'void*', but they may all be
303 // different actual classes based on the actions in place.
306
307 /// Initialize - Warm up the parser.
308 ///
309 void Initialize();
310
311 /// Parse the first top-level declaration in a translation unit.
312 ///
313 /// \verbatim
314 /// translation-unit:
315 /// [C] external-declaration
316 /// [C] translation-unit external-declaration
317 /// [C++] top-level-declaration-seq[opt]
318 /// [C++20] global-module-fragment[opt] module-declaration
319 /// top-level-declaration-seq[opt] private-module-fragment[opt]
320 /// \endverbatim
321 ///
322 /// Note that in C, it is an error if there is no first declaration.
324 Sema::ModuleImportState &ImportState);
325
326 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
327 /// action tells us to. This returns true if the EOF was encountered.
328 ///
329 /// \verbatim
330 /// top-level-declaration:
331 /// declaration
332 /// [C++20] module-import-declaration
333 /// \endverbatim
335 Sema::ModuleImportState &ImportState);
341
342 /// ConsumeToken - Consume the current 'peek token' and lex the next one.
343 /// This does not work with special tokens: string literals, code completion,
344 /// annotation tokens and balanced tokens must be handled using the specific
345 /// consume methods.
346 /// Returns the location of the consumed token.
348 assert(!isTokenSpecial() &&
349 "Should consume special tokens with Consume*Token");
350 PrevTokLocation = Tok.getLocation();
351 PP.Lex(Tok);
352 return PrevTokLocation;
353 }
354
356 if (Tok.isNot(Expected))
357 return false;
358 assert(!isTokenSpecial() &&
359 "Should consume special tokens with Consume*Token");
360 PrevTokLocation = Tok.getLocation();
361 PP.Lex(Tok);
362 return true;
363 }
364
367 return false;
368 Loc = PrevTokLocation;
369 return true;
370 }
371
372 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
373 /// current token type. This should only be used in cases where the type of
374 /// the token really isn't known, e.g. in error recovery.
375 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
376 if (isTokenParen())
377 return ConsumeParen();
378 if (isTokenBracket())
379 return ConsumeBracket();
380 if (isTokenBrace())
381 return ConsumeBrace();
382 if (isTokenStringLiteral())
383 return ConsumeStringToken();
384 if (Tok.is(tok::code_completion))
385 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
386 : handleUnexpectedCodeCompletionToken();
387 if (Tok.isAnnotation())
388 return ConsumeAnnotationToken();
389 return ConsumeToken();
390 }
391
393
394 /// GetLookAheadToken - This peeks ahead N tokens and returns that token
395 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
396 /// returns the token after Tok, etc.
397 ///
398 /// Note that this differs from the Preprocessor's LookAhead method, because
399 /// the Parser always has one token lexed that the preprocessor doesn't.
400 ///
401 const Token &GetLookAheadToken(unsigned N) {
402 if (N == 0 || Tok.is(tok::eof))
403 return Tok;
404 return PP.LookAhead(N - 1);
405 }
406
407 /// NextToken - This peeks ahead one token and returns it without
408 /// consuming it.
409 const Token &NextToken() { return PP.LookAhead(0); }
410
411 /// getTypeAnnotation - Read a parsed type out of an annotation token.
412 static TypeResult getTypeAnnotation(const Token &Tok) {
413 if (!Tok.getAnnotationValue())
414 return TypeError();
415 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
416 }
417
418 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
419 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
420 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
421 /// with a single annotation token representing the typename or C++ scope
422 /// respectively.
423 /// This simplifies handling of C++ scope specifiers and allows efficient
424 /// backtracking without the need to re-parse and resolve nested-names and
425 /// typenames.
426 /// It will mainly be called when we expect to treat identifiers as typenames
427 /// (if they are typenames). For example, in C we do not expect identifiers
428 /// inside expressions to be treated as typenames so it will not be called
429 /// for expressions in C.
430 /// The benefit for C/ObjC is that a typename will be annotated and
431 /// Actions.getTypeName will not be needed to be called again (e.g.
432 /// getTypeName will not be called twice, once to check whether we have a
433 /// declaration specifier, and another one to get the actual type inside
434 /// ParseDeclarationSpecifiers).
435 ///
436 /// This returns true if an error occurred.
437 ///
438 /// Note that this routine emits an error if you call it with ::new or
439 /// ::delete as the current tokens, so only call it in contexts where these
440 /// are invalid.
441 ///
442 /// \param IsAddressOfOperand A hint indicating whether the current token
443 /// sequence is likely part of an address-of operation. Used by code
444 /// completion to filter results; may not be set by all callers.
445 bool
448 bool IsAddressOfOperand = false);
449
450 bool TryAnnotateTypeOrScopeToken(bool IsAddressOfOperand) {
452 /*AllowImplicitTypename=*/ImplicitTypenameContext::No,
453 /*IsAddressOfOperand=*/IsAddressOfOperand);
454 }
455
456 /// Try to annotate a type or scope token, having already parsed an
457 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
458 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
460 CXXScopeSpec &SS, bool IsNewScope,
461 ImplicitTypenameContext AllowImplicitTypename);
462
463 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
464 /// annotates C++ scope specifiers and template-ids. This returns
465 /// true if there was an error that could not be recovered from.
466 ///
467 /// Note that this routine emits an error if you call it with ::new or
468 /// ::delete as the current tokens, so only call it in contexts where these
469 /// are invalid.
470 bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
471
473 return getLangOpts().CPlusPlus &&
474 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
475 (Tok.is(tok::annot_template_id) &&
476 NextToken().is(tok::coloncolon)) ||
477 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super));
478 }
479 bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
480 return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
481 }
482
483 //===--------------------------------------------------------------------===//
484 // Scope manipulation
485
486 /// ParseScope - Introduces a new scope for parsing. The kind of
487 /// scope is determined by ScopeFlags. Objects of this type should
488 /// be created on the stack to coincide with the position where the
489 /// parser enters the new scope, and this object's constructor will
490 /// create that new scope. Similarly, once the object is destroyed
491 /// the parser will exit the scope.
492 class ParseScope {
493 Parser *Self;
494 ParseScope(const ParseScope &) = delete;
495 void operator=(const ParseScope &) = delete;
496
497 public:
498 // ParseScope - Construct a new object to manage a scope in the
499 // parser Self where the new Scope is created with the flags
500 // ScopeFlags, but only when we aren't about to enter a compound statement.
501 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
502 bool BeforeCompoundStmt = false)
503 : Self(Self) {
504 if (EnteredScope && !BeforeCompoundStmt)
505 Self->EnterScope(ScopeFlags);
506 else {
507 if (BeforeCompoundStmt)
508 Self->incrementMSManglingNumber();
509
510 this->Self = nullptr;
511 }
512 }
513
514 // Exit - Exit the scope associated with this object now, rather
515 // than waiting until the object is destroyed.
516 void Exit() {
517 if (Self) {
518 Self->ExitScope();
519 Self = nullptr;
520 }
521 }
522
524 };
525
526 /// Introduces zero or more scopes for parsing. The scopes will all be exited
527 /// when the object is destroyed.
528 class MultiParseScope {
529 Parser &Self;
530 unsigned NumScopes = 0;
531
532 MultiParseScope(const MultiParseScope &) = delete;
533
534 public:
535 MultiParseScope(Parser &Self) : Self(Self) {}
536 void Enter(unsigned ScopeFlags) {
537 Self.EnterScope(ScopeFlags);
538 ++NumScopes;
539 }
540 void Exit() {
541 while (NumScopes) {
542 Self.ExitScope();
543 --NumScopes;
544 }
545 }
547 };
548
549 /// EnterScope - Start a new scope.
550 void EnterScope(unsigned ScopeFlags);
551
552 /// ExitScope - Pop a scope off the scope stack.
553 void ExitScope();
554
555 //===--------------------------------------------------------------------===//
556 // Diagnostic Emission and Error recovery.
557
558 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
559 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
560 DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); }
561
562 DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId);
563 DiagnosticBuilder DiagCompat(const Token &Tok, unsigned CompatDiagId);
564 DiagnosticBuilder DiagCompat(unsigned CompatDiagId) {
565 return DiagCompat(Tok, CompatDiagId);
566 }
567
568 /// Control flags for SkipUntil functions.
570 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon
571 /// Stop skipping at specified token, but don't skip the token itself
573 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
574 };
575
577 SkipUntilFlags R) {
578 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
579 static_cast<unsigned>(R));
580 }
581
582 /// SkipUntil - Read tokens until we get to the specified token, then consume
583 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee
584 /// that the token will ever occur, this skips to the next token, or to some
585 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will
586 /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
587 /// skipping.
588 ///
589 /// If SkipUntil finds the specified token, it returns true, otherwise it
590 /// returns false.
592 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
593 return SkipUntil(llvm::ArrayRef(T), Flags);
594 }
596 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
597 tok::TokenKind TokArray[] = {T1, T2};
598 return SkipUntil(TokArray, Flags);
599 }
601 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
602 tok::TokenKind TokArray[] = {T1, T2, T3};
603 return SkipUntil(TokArray, Flags);
604 }
605
606 /// SkipUntil - Read tokens until we get to the specified token, then consume
607 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
608 /// token will ever occur, this skips to the next token, or to some likely
609 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
610 /// character.
611 ///
612 /// If SkipUntil finds the specified token, it returns true, otherwise it
613 /// returns false.
615 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
616
617private:
618 Preprocessor &PP;
619
620 /// Tok - The current token we are peeking ahead. All parsing methods assume
621 /// that this is valid.
622 Token Tok;
623
624 // PrevTokLocation - The location of the token we previously
625 // consumed. This token is used for diagnostics where we expected to
626 // see a token following another token (e.g., the ';' at the end of
627 // a statement).
628 SourceLocation PrevTokLocation;
629
630 /// Tracks an expected type for the current token when parsing an expression.
631 /// Used by code completion for ranking.
632 PreferredTypeBuilder PreferredType;
633
634 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
635 unsigned short MisplacedModuleBeginCount = 0;
636
637 /// Actions - These are the callbacks we invoke as we parse various constructs
638 /// in the file.
639 Sema &Actions;
640
641 DiagnosticsEngine &Diags;
642
643 StackExhaustionHandler StackHandler;
644
645 /// ScopeCache - Cache scopes to reduce malloc traffic.
646 static constexpr int ScopeCacheSize = 16;
647 unsigned NumCachedScopes;
648 Scope *ScopeCache[ScopeCacheSize];
649
650 /// Identifiers used for SEH handling in Borland. These are only
651 /// allowed in particular circumstances
652 // __except block
653 IdentifierInfo *Ident__exception_code, *Ident___exception_code,
654 *Ident_GetExceptionCode;
655 // __except filter expression
656 IdentifierInfo *Ident__exception_info, *Ident___exception_info,
657 *Ident_GetExceptionInfo;
658 // __finally
659 IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination,
660 *Ident_AbnormalTermination;
661
662 /// Contextual keywords for Microsoft extensions.
663 IdentifierInfo *Ident__except;
664 IdentifierInfo *Ident_except;
665
666 std::unique_ptr<CommentHandler> CommentSemaHandler;
667
668 /// Gets set to true after calling ProduceSignatureHelp, it is for a
669 /// workaround to make sure ProduceSignatureHelp is only called at the deepest
670 /// function call.
671 bool CalledSignatureHelp = false;
672
673 bool isTokenSEHExcept();
674
675 /// Whether to skip parsing of function bodies.
676 ///
677 /// This option can be used, for example, to speed up searches for
678 /// declarations/definitions when indexing.
679 bool SkipFunctionBodies;
680
681 //===--------------------------------------------------------------------===//
682 // Low-Level token peeking and consumption methods.
683 //
684
685 /// isTokenParen - Return true if the cur token is '(' or ')'.
686 bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); }
687 /// isTokenBracket - Return true if the cur token is '[' or ']'.
688 bool isTokenBracket() const {
689 return Tok.isOneOf(tok::l_square, tok::r_square);
690 }
691 /// isTokenBrace - Return true if the cur token is '{' or '}'.
692 bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); }
693 /// isTokenStringLiteral - True if this token is a string-literal.
694 bool isTokenStringLiteral() const {
695 return tok::isStringLiteral(Tok.getKind());
696 }
697 /// isTokenSpecial - True if this token requires special consumption methods.
698 bool isTokenSpecial() const {
699 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
700 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
701 }
702
703 /// Returns true if the current token is '=' or is a type of '='.
704 /// For typos, give a fixit to '='
705 bool isTokenEqualOrEqualTypo();
706
707 /// Return the current token to the token stream and make the given
708 /// token the current token.
709 void UnconsumeToken(Token &Consumed) {
710 Token Next = Tok;
711 PP.EnterToken(Consumed, /*IsReinject*/ true);
712 PP.Lex(Tok);
713 PP.EnterToken(Next, /*IsReinject*/ true);
714 }
715
716 SourceLocation ConsumeAnnotationToken() {
717 assert(Tok.isAnnotation() && "wrong consume method");
718 SourceLocation Loc = Tok.getLocation();
719 PrevTokLocation = Tok.getAnnotationEndLoc();
720 PP.Lex(Tok);
721 return Loc;
722 }
723
724 /// ConsumeParen - This consume method keeps the paren count up-to-date.
725 ///
726 SourceLocation ConsumeParen() {
727 assert(isTokenParen() && "wrong consume method");
728 if (Tok.getKind() == tok::l_paren)
729 ++ParenCount;
730 else if (ParenCount) {
731 AngleBrackets.clear(*this);
732 --ParenCount; // Don't let unbalanced )'s drive the count negative.
733 }
734 PrevTokLocation = Tok.getLocation();
735 PP.Lex(Tok);
736 return PrevTokLocation;
737 }
738
739 /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
740 ///
741 SourceLocation ConsumeBracket() {
742 assert(isTokenBracket() && "wrong consume method");
743 if (Tok.getKind() == tok::l_square)
744 ++BracketCount;
745 else if (BracketCount) {
746 AngleBrackets.clear(*this);
747 --BracketCount; // Don't let unbalanced ]'s drive the count negative.
748 }
749
750 PrevTokLocation = Tok.getLocation();
751 PP.Lex(Tok);
752 return PrevTokLocation;
753 }
754
755 /// ConsumeBrace - This consume method keeps the brace count up-to-date.
756 ///
757 SourceLocation ConsumeBrace() {
758 assert(isTokenBrace() && "wrong consume method");
759 if (Tok.getKind() == tok::l_brace)
760 ++BraceCount;
761 else if (BraceCount) {
762 AngleBrackets.clear(*this);
763 --BraceCount; // Don't let unbalanced }'s drive the count negative.
764 }
765
766 PrevTokLocation = Tok.getLocation();
767 PP.Lex(Tok);
768 return PrevTokLocation;
769 }
770
771 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
772 /// and returning the token kind. This method is specific to strings, as it
773 /// handles string literal concatenation, as per C99 5.1.1.2, translation
774 /// phase #6.
775 SourceLocation ConsumeStringToken() {
776 assert(isTokenStringLiteral() &&
777 "Should only consume string literals with this method");
778 PrevTokLocation = Tok.getLocation();
779 PP.Lex(Tok);
780 return PrevTokLocation;
781 }
782
783 /// Consume the current code-completion token.
784 ///
785 /// This routine can be called to consume the code-completion token and
786 /// continue processing in special cases where \c cutOffParsing() isn't
787 /// desired, such as token caching or completion with lookahead.
788 SourceLocation ConsumeCodeCompletionToken() {
789 assert(Tok.is(tok::code_completion));
790 PrevTokLocation = Tok.getLocation();
791 PP.Lex(Tok);
792 return PrevTokLocation;
793 }
794
795 /// When we are consuming a code-completion token without having matched
796 /// specific position in the grammar, provide code-completion results based
797 /// on context.
798 ///
799 /// \returns the source location of the code-completion token.
800 SourceLocation handleUnexpectedCodeCompletionToken();
801
802 /// Abruptly cut off parsing; mainly used when we have reached the
803 /// code-completion point.
804 void cutOffParsing() {
805 if (PP.isCodeCompletionEnabled())
806 PP.setCodeCompletionReached();
807 // Cut off parsing by acting as if we reached the end-of-file.
808 Tok.setKind(tok::eof);
809 }
810
811 /// Determine if we're at the end of the file or at a transition
812 /// between modules.
813 bool isEofOrEom() {
814 tok::TokenKind Kind = Tok.getKind();
815 return Kind == tok::eof || Kind == tok::annot_module_begin ||
816 Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
817 Kind == tok::annot_repl_input_end;
818 }
819
820 static void setTypeAnnotation(Token &Tok, TypeResult T) {
821 assert((T.isInvalid() || T.get()) &&
822 "produced a valid-but-null type annotation?");
823 Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
824 }
825
826 static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
827 return static_cast<NamedDecl *>(Tok.getAnnotationValue());
828 }
829
830 static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
831 Tok.setAnnotationValue(ND);
832 }
833
834 static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
835 return static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
836 }
837
838 static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
839 Tok.setAnnotationValue(ND);
840 }
841
842 /// Read an already-translated primary expression out of an annotation
843 /// token.
844 static ExprResult getExprAnnotation(const Token &Tok) {
845 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
846 }
847
848 /// Set the primary expression corresponding to the given annotation
849 /// token.
850 static void setExprAnnotation(Token &Tok, ExprResult ER) {
851 Tok.setAnnotationValue(ER.getAsOpaquePointer());
852 }
853
854 /// Attempt to classify the name at the current token position. This may
855 /// form a type, scope or primary expression annotation, or replace the token
856 /// with a typo-corrected keyword. This is only appropriate when the current
857 /// name must refer to an entity which has already been declared.
858 ///
859 /// \param CCC Indicates how to perform typo-correction for this name. If
860 /// NULL, no typo correction will be performed.
861 /// \param AllowImplicitTypename Whether we are in a context where a dependent
862 /// nested-name-specifier without typename is treated as a type (e.g.
863 /// T::type).
865 TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
866 ImplicitTypenameContext AllowImplicitTypename =
868
869 /// Push a tok::annot_cxxscope token onto the token stream.
870 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
871
872 /// TryKeywordIdentFallback - For compatibility with system headers using
873 /// keywords as identifiers, attempt to convert the current token to an
874 /// identifier and optionally disable the keyword for the remainder of the
875 /// translation unit. This returns false if the token was not replaced,
876 /// otherwise emits a diagnostic and returns true.
877 bool TryKeywordIdentFallback(bool DisableKeyword);
878
879 /// Get the TemplateIdAnnotation from the token and put it in the
880 /// cleanup pool so that it gets destroyed when parsing the current top level
881 /// declaration is finished.
882 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
883
884 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
885 /// input. If so, it is consumed and false is returned.
886 ///
887 /// If a trivial punctuator misspelling is encountered, a FixIt error
888 /// diagnostic is issued and false is returned after recovery.
889 ///
890 /// If the input is malformed, this emits the specified diagnostic and true is
891 /// returned.
892 bool ExpectAndConsume(tok::TokenKind ExpectedTok,
893 unsigned Diag = diag::err_expected,
894 StringRef DiagMsg = "");
895
896 /// The parser expects a semicolon and, if present, will consume it.
897 ///
898 /// If the next token is not a semicolon, this emits the specified diagnostic,
899 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
900 /// to the semicolon, consumes that extra token.
901 bool ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed = "");
902
903 /// Returns true if the current token is likely the start of a new
904 /// declaration (e.g., it starts a new line and is a declaration specifier).
905 /// This is a heuristic used for error recovery.
906 bool isLikelyAtStartOfNewDeclaration();
907
908 /// Consume any extra semi-colons until the end of the line.
909 void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
910
911 /// Return false if the next token is an identifier. An 'expected identifier'
912 /// error is emitted otherwise.
913 ///
914 /// The parser tries to recover from the error by checking if the next token
915 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
916 /// was successful.
917 bool expectIdentifier();
918
919 /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
920 enum class CompoundToken {
921 /// A '(' '{' beginning a statement-expression.
922 StmtExprBegin,
923 /// A '}' ')' ending a statement-expression.
924 StmtExprEnd,
925 /// A '[' '[' beginning a C++11 or C23 attribute.
926 AttrBegin,
927 /// A ']' ']' ending a C++11 or C23 attribute.
928 AttrEnd,
929 /// A '::' '*' forming a C++ pointer-to-member declaration.
930 MemberPtr,
931 };
932
933 /// Check that a compound operator was written in a "sensible" way, and warn
934 /// if not.
935 void checkCompoundToken(SourceLocation FirstTokLoc,
936 tok::TokenKind FirstTokKind, CompoundToken Op);
937
938 void diagnoseUseOfC11Keyword(const Token &Tok);
939
940 /// RAII object used to modify the scope flags for the current scope.
941 class ParseScopeFlags {
942 Scope *CurScope;
943 unsigned OldFlags = 0;
944 ParseScopeFlags(const ParseScopeFlags &) = delete;
945 void operator=(const ParseScopeFlags &) = delete;
946
947 public:
948 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is
949 /// false, this object does nothing.
950 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
951
952 /// Restore the flags for the current scope to what they were before this
953 /// object overrode them.
954 ~ParseScopeFlags();
955 };
956
957 /// Emits a diagnostic suggesting parentheses surrounding a
958 /// given range.
959 ///
960 /// \param Loc The location where we'll emit the diagnostic.
961 /// \param DK The kind of diagnostic to emit.
962 /// \param ParenRange Source range enclosing code that should be
963 /// parenthesized.
964 void SuggestParentheses(SourceLocation Loc, unsigned DK,
965 SourceRange ParenRange);
966
967 //===--------------------------------------------------------------------===//
968 // C99 6.9: External Definitions.
969
970 /// ParseExternalDeclaration:
971 ///
972 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
973 /// declaration.
974 ///
975 /// \verbatim
976 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
977 /// function-definition
978 /// declaration
979 /// [GNU] asm-definition
980 /// [GNU] __extension__ external-declaration
981 /// [OBJC] objc-class-definition
982 /// [OBJC] objc-class-declaration
983 /// [OBJC] objc-alias-declaration
984 /// [OBJC] objc-protocol-definition
985 /// [OBJC] objc-method-definition
986 /// [OBJC] @end
987 /// [C++] linkage-specification
988 /// [GNU] asm-definition:
989 /// simple-asm-expr ';'
990 /// [C++11] empty-declaration
991 /// [C++11] attribute-declaration
992 ///
993 /// [C++11] empty-declaration:
994 /// ';'
995 ///
996 /// [C++0x/GNU] 'extern' 'template' declaration
997 ///
998 /// [C++20] module-import-declaration
999 /// \endverbatim
1000 ///
1001 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
1002 ParsedAttributes &DeclSpecAttrs,
1003 ParsingDeclSpec *DS = nullptr);
1004
1005 /// Determine whether the current token, if it occurs after a
1006 /// declarator, continues a declaration or declaration list.
1007 bool isDeclarationAfterDeclarator();
1008
1009 /// Determine whether the current token, if it occurs after a
1010 /// declarator, indicates the start of a function definition.
1011 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1012
1013 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1014 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1015 ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
1016
1017 /// Parse either a function-definition or a declaration. We can't tell which
1018 /// we have until we read up to the compound-statement in function-definition.
1019 /// TemplateParams, if non-NULL, provides the template parameters when we're
1020 /// parsing a C++ template-declaration.
1021 ///
1022 /// \verbatim
1023 /// function-definition: [C99 6.9.1]
1024 /// decl-specs declarator declaration-list[opt] compound-statement
1025 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1026 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1027 ///
1028 /// declaration: [C99 6.7]
1029 /// declaration-specifiers init-declarator-list[opt] ';'
1030 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1031 /// [OMP] threadprivate-directive
1032 /// [OMP] allocate-directive [TODO]
1033 /// \endverbatim
1034 ///
1035 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
1036 ParsedAttributes &DeclSpecAttrs,
1037 ParsingDeclSpec &DS,
1038 AccessSpecifier AS);
1039
1040 void SkipFunctionBody();
1041
1042 struct ParsedTemplateInfo;
1043
1044 /// ParseFunctionDefinition - We parsed and verified that the specified
1045 /// Declarator is well formed. If this is a K&R-style function, read the
1046 /// parameters declaration-list, then start the compound-statement.
1047 ///
1048 /// \verbatim
1049 /// function-definition: [C99 6.9.1]
1050 /// decl-specs declarator declaration-list[opt] compound-statement
1051 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1052 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1053 /// [C++] function-definition: [C++ 8.4]
1054 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1055 /// function-body
1056 /// [C++] function-definition: [C++ 8.4]
1057 /// decl-specifier-seq[opt] declarator function-try-block
1058 /// \endverbatim
1059 ///
1060 Decl *ParseFunctionDefinition(
1061 ParsingDeclarator &D,
1062 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1063 LateParsedAttrList *LateParsedAttrs = nullptr);
1064
1065 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1066 /// types for a function with a K&R-style identifier list for arguments.
1067 void ParseKNRParamDeclarations(Declarator &D);
1068
1069 /// ParseSimpleAsm
1070 ///
1071 /// \verbatim
1072 /// [GNU] simple-asm-expr:
1073 /// 'asm' '(' asm-string-literal ')'
1074 /// \endverbatim
1075 ///
1076 /// EndLoc is filled with the location of the last token of the simple-asm.
1077 ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1078
1079 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1080 /// allowed to be a wide string, and is not subject to character translation.
1081 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1082 /// asm label as opposed to an asm statement, because such a construct does
1083 /// not behave well.
1084 ///
1085 /// \verbatim
1086 /// [GNU] asm-string-literal:
1087 /// string-literal
1088 /// \endverbatim
1089 ///
1090 ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1091
1092 /// Describes the condition of a Microsoft __if_exists or
1093 /// __if_not_exists block.
1094 struct IfExistsCondition {
1095 /// The location of the initial keyword.
1096 SourceLocation KeywordLoc;
1097 /// Whether this is an __if_exists block (rather than an
1098 /// __if_not_exists block).
1099 bool IsIfExists;
1100
1101 /// Nested-name-specifier preceding the name.
1102 CXXScopeSpec SS;
1103
1104 /// The name we're looking for.
1105 UnqualifiedId Name;
1106
1107 /// The behavior of this __if_exists or __if_not_exists block
1108 /// should.
1109 IfExistsBehavior Behavior;
1110 };
1111
1112 bool ParseMicrosoftIfExistsCondition(IfExistsCondition &Result);
1113 void ParseMicrosoftIfExistsExternalDeclaration();
1114
1115 //===--------------------------------------------------------------------===//
1116 // Modules
1117
1118 /// Parse a declaration beginning with the 'module' keyword or C++20
1119 /// context-sensitive keyword (optionally preceded by 'export').
1120 ///
1121 /// \verbatim
1122 /// module-declaration: [C++20]
1123 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
1124 ///
1125 /// global-module-fragment: [C++2a]
1126 /// 'module' ';' top-level-declaration-seq[opt]
1127 /// module-declaration: [C++2a]
1128 /// 'export'[opt] 'module' module-name module-partition[opt]
1129 /// attribute-specifier-seq[opt] ';'
1130 /// private-module-fragment: [C++2a]
1131 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
1132 /// \endverbatim
1133 DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
1134
1135 /// Parse a module import declaration. This is essentially the same for
1136 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
1137 /// trailing optional attributes (in C++).
1138 ///
1139 /// \verbatim
1140 /// [ObjC] @import declaration:
1141 /// '@' 'import' module-name ';'
1142 /// [ModTS] module-import-declaration:
1143 /// 'import' module-name attribute-specifier-seq[opt] ';'
1144 /// [C++20] module-import-declaration:
1145 /// 'export'[opt] 'import' module-name
1146 /// attribute-specifier-seq[opt] ';'
1147 /// 'export'[opt] 'import' module-partition
1148 /// attribute-specifier-seq[opt] ';'
1149 /// 'export'[opt] 'import' header-name
1150 /// attribute-specifier-seq[opt] ';'
1151 /// \endverbatim
1152 Decl *ParseModuleImport(SourceLocation AtLoc,
1153 Sema::ModuleImportState &ImportState);
1154
1155 /// Try recover parser when module annotation appears where it must not
1156 /// be found.
1157 /// \returns false if the recover was successful and parsing may be continued,
1158 /// or true if parser must bail out to top level and handle the token there.
1159 bool parseMisplacedModuleImport();
1160
1161 bool tryParseMisplacedModuleImport() {
1162 tok::TokenKind Kind = Tok.getKind();
1163 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
1164 Kind == tok::annot_module_include)
1165 return parseMisplacedModuleImport();
1166 return false;
1167 }
1168
1169 /// Parse a C++ / Objective-C module name (both forms use the same
1170 /// grammar).
1171 ///
1172 /// \verbatim
1173 /// module-name:
1174 /// module-name-qualifier[opt] identifier
1175 /// module-name-qualifier:
1176 /// module-name-qualifier[opt] identifier '.'
1177 /// \endverbatim
1178 bool ParseModuleName(SourceLocation UseLoc,
1179 SmallVectorImpl<IdentifierLoc> &Path, bool IsImport);
1180
1181 void DiagnoseInvalidCXXModuleDecl(const Sema::ModuleImportState &ImportState);
1182 void DiagnoseInvalidCXXModuleImport();
1183
1184 //===--------------------------------------------------------------------===//
1185 // Preprocessor code-completion pass-through
1186 void CodeCompleteDirective(bool InConditional) override;
1187 void CodeCompleteInConditionalExclusion() override;
1188 void CodeCompleteMacroName(bool IsDefinition) override;
1189 void CodeCompletePreprocessorExpression() override;
1190 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
1191 unsigned ArgumentIndex) override;
1192 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
1193 void CodeCompleteNaturalLanguage() override;
1194 void CodeCompleteModuleImport(SourceLocation ImportLoc,
1195 ModuleIdPath Path) override;
1196
1197 ///@}
1198
1199 //
1200 //
1201 // -------------------------------------------------------------------------
1202 //
1203 //
1204
1205 /// \name C++ Class Inline Methods
1206 /// Implementations are in ParseCXXInlineMethods.cpp
1207 ///@{
1208
1209private:
1210 friend struct LateParsedAttribute;
1212
1213 struct ParsingClass;
1214
1215 /// Inner node of the LateParsedDeclaration tree that parses
1216 /// all its members recursively.
1217 class LateParsedClass : public LateParsedDeclaration {
1218 public:
1219 LateParsedClass(Parser *P, ParsingClass *C);
1220 ~LateParsedClass() override;
1221
1222 void ParseLexedMethodDeclarations() override;
1223 void ParseLexedMemberInitializers() override;
1224 void ParseLexedMethodDefs() override;
1225 void ParseLexedAttributes() override;
1226 void ParseLexedPragmas() override;
1227
1228 // Delete copy constructor and copy assignment operator.
1229 LateParsedClass(const LateParsedClass &) = delete;
1230 LateParsedClass &operator=(const LateParsedClass &) = delete;
1231
1232 private:
1233 Parser *Self;
1234 ParsingClass *Class;
1235 };
1236
1237 /// Contains the lexed tokens of a pragma with arguments that
1238 /// may reference member variables and so need to be parsed at the
1239 /// end of the class declaration after parsing all other member
1240 /// member declarations.
1241 class LateParsedPragma : public LateParsedDeclaration {
1242 Parser *Self = nullptr;
1244 CachedTokens Toks;
1245
1246 public:
1247 explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1248 : Self(P), AS(AS) {}
1249
1250 void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1251 const CachedTokens &toks() const { return Toks; }
1252 AccessSpecifier getAccessSpecifier() const { return AS; }
1253
1254 void ParseLexedPragmas() override;
1255 };
1256
1257 /// Contains the lexed tokens of a member function definition
1258 /// which needs to be parsed at the end of the class declaration
1259 /// after parsing all other member declarations.
1260 struct LexedMethod : public LateParsedDeclaration {
1261 Parser *Self;
1262 Decl *D;
1263 CachedTokens Toks;
1264
1265 explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1266
1267 void ParseLexedMethodDefs() override;
1268 };
1269
1270 /// LateParsedDefaultArgument - Keeps track of a parameter that may
1271 /// have a default argument that cannot be parsed yet because it
1272 /// occurs within a member function declaration inside the class
1273 /// (C++ [class.mem]p2).
1274 struct LateParsedDefaultArgument {
1275 explicit LateParsedDefaultArgument(
1276 Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr)
1277 : Param(P), Toks(std::move(Toks)) {}
1278
1279 /// Param - The parameter declaration for this parameter.
1280 Decl *Param;
1281
1282 /// Toks - The sequence of tokens that comprises the default
1283 /// argument expression, not including the '=' or the terminating
1284 /// ')' or ','. This will be NULL for parameters that have no
1285 /// default argument.
1286 std::unique_ptr<CachedTokens> Toks;
1287 };
1288
1289 /// LateParsedMethodDeclaration - A method declaration inside a class that
1290 /// contains at least one entity whose parsing needs to be delayed
1291 /// until the class itself is completely-defined, such as a default
1292 /// argument (C++ [class.mem]p2).
1293 struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1294 explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1295 : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1296
1297 void ParseLexedMethodDeclarations() override;
1298
1299 Parser *Self;
1300
1301 /// Method - The method declaration.
1302 Decl *Method;
1303
1304 /// DefaultArgs - Contains the parameters of the function and
1305 /// their default arguments. At least one of the parameters will
1306 /// have a default argument, but all of the parameters of the
1307 /// method will be stored so that they can be reintroduced into
1308 /// scope at the appropriate times.
1309 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1310
1311 /// The set of tokens that make up an exception-specification that
1312 /// has not yet been parsed.
1313 CachedTokens *ExceptionSpecTokens;
1314 };
1315
1316 /// LateParsedMemberInitializer - An initializer for a non-static class data
1317 /// member whose parsing must to be delayed until the class is completely
1318 /// defined (C++11 [class.mem]p2).
1319 struct LateParsedMemberInitializer : public LateParsedDeclaration {
1320 LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) {}
1321
1322 void ParseLexedMemberInitializers() override;
1323
1324 Parser *Self;
1325
1326 /// Field - The field declaration.
1327 Decl *Field;
1328
1329 /// CachedTokens - The sequence of tokens that comprises the initializer,
1330 /// including any leading '='.
1331 CachedTokens Toks;
1332 };
1333
1334 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1335 /// C++ class, its method declarations that contain parts that won't be
1336 /// parsed until after the definition is completed (C++ [class.mem]p2),
1337 /// the method declarations and possibly attached inline definitions
1338 /// will be stored here with the tokens that will be parsed to create those
1339 /// entities.
1340 typedef SmallVector<LateParsedDeclaration *, 2>
1341 LateParsedDeclarationsContainer;
1342
1343 /// Utility to re-enter a possibly-templated scope while parsing its
1344 /// late-parsed components.
1346
1347 /// Utility to re-enter a class scope while parsing its late-parsed
1348 /// components.
1349 struct ReenterClassScopeRAII;
1350
1351 /// ParseCXXInlineMethodDef - We parsed and verified that the specified
1352 /// Declarator is a well formed C++ inline method definition. Now lex its body
1353 /// and store its tokens for parsing after the C++ class is complete.
1354 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1355 const ParsedAttributesView &AccessAttrs,
1356 ParsingDeclarator &D,
1357 const ParsedTemplateInfo &TemplateInfo,
1358 const VirtSpecifiers &VS,
1359 SourceLocation PureSpecLoc);
1360
1361 /// Parse the optional ("message") part of a deleted-function-body.
1362 StringLiteral *ParseCXXDeletedFunctionMessage();
1363
1364 /// If we've encountered '= delete' in a context where it is ill-formed, such
1365 /// as in the declaration of a non-function, also skip the ("message") part if
1366 /// it is present to avoid issuing further diagnostics.
1367 void SkipDeletedFunctionBody();
1368
1369 /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the
1370 /// specified Declarator is a well formed C++ non-static data member
1371 /// declaration. Now lex its initializer and store its tokens for parsing
1372 /// after the class is complete.
1373 void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1374
1375 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1376 /// scope appropriately.
1377 void ParseLexedAttributes(ParsingClass &Class);
1378
1379 /// Parse all attributes in LAs, and attach them to Decl D.
1380 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1381 bool EnterScope, bool OnDefinition,
1382 ParsedAttributes *OutAttrs = nullptr);
1383
1384 /// Finish parsing an attribute for which parsing was delayed.
1385 /// This will be called at the end of parsing a class declaration
1386 /// for each LateParsedAttribute. We consume the saved tokens and
1387 /// create an attribute with the arguments filled in. We add this
1388 /// to the Attribute list for the decl.
1389 void ParseLexedAttribute(LateParsedAttribute &LPA, bool EnterScope,
1390 bool OnDefinition,
1391 ParsedAttributes *OutAttrs = nullptr);
1392
1393 /// ParseLexedMethodDeclarations - We finished parsing the member
1394 /// specification of a top (non-nested) C++ class. Now go over the
1395 /// stack of method declarations with some parts for which parsing was
1396 /// delayed (such as default arguments) and parse them.
1397 void ParseLexedMethodDeclarations(ParsingClass &Class);
1398 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1399
1400 /// ParseLexedMethodDefs - We finished parsing the member specification of a
1401 /// top (non-nested) C++ class. Now go over the stack of lexed methods that
1402 /// were collected during its parsing and parse them all.
1403 void ParseLexedMethodDefs(ParsingClass &Class);
1404 void ParseLexedMethodDef(LexedMethod &LM);
1405
1406 /// ParseLexedMemberInitializers - We finished parsing the member
1407 /// specification of a top (non-nested) C++ class. Now go over the stack of
1408 /// lexed data member initializers that were collected during its parsing and
1409 /// parse them all.
1410 void ParseLexedMemberInitializers(ParsingClass &Class);
1411 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1412
1413 ///@}
1414
1415 //
1416 //
1417 // -------------------------------------------------------------------------
1418 //
1419 //
1420
1421 /// \name Declarations
1422 /// Implementations are in ParseDecl.cpp
1423 ///@{
1424
1425public:
1426 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1427 /// point for skipping past a simple-declaration.
1428 ///
1429 /// Skip until we reach something which seems like a sensible place to pick
1430 /// up parsing after a malformed declaration. This will sometimes stop sooner
1431 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1432 void SkipMalformedDecl();
1433
1434 /// ParseTypeName
1435 /// \verbatim
1436 /// type-name: [C99 6.7.6]
1437 /// specifier-qualifier-list abstract-declarator[opt]
1438 /// \endverbatim
1439 ///
1440 /// Called type-id in C++.
1442 ParseTypeName(SourceRange *Range = nullptr,
1444 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
1445 ParsedAttributes *Attrs = nullptr);
1446
1447private:
1448 /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
1449 /// and "bool" fast comparison. Only present if AltiVec or ZVector are
1450 /// enabled.
1451 IdentifierInfo *Ident_vector;
1452 IdentifierInfo *Ident_bool;
1453 IdentifierInfo *Ident_Bool;
1454
1455 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
1456 /// Only present if AltiVec enabled.
1457 IdentifierInfo *Ident_pixel;
1458
1459 /// Identifier for "introduced".
1460 IdentifierInfo *Ident_introduced;
1461
1462 /// Identifier for "deprecated".
1463 IdentifierInfo *Ident_deprecated;
1464
1465 /// Identifier for "obsoleted".
1466 IdentifierInfo *Ident_obsoleted;
1467
1468 /// Identifier for "unavailable".
1469 IdentifierInfo *Ident_unavailable;
1470
1471 /// Identifier for "message".
1472 IdentifierInfo *Ident_message;
1473
1474 /// Identifier for "strict".
1475 IdentifierInfo *Ident_strict;
1476
1477 /// Identifier for "replacement".
1478 IdentifierInfo *Ident_replacement;
1479
1480 /// Identifier for "environment".
1481 IdentifierInfo *Ident_environment;
1482
1483 /// Identifiers used by the 'external_source_symbol' attribute.
1484 IdentifierInfo *Ident_language, *Ident_defined_in,
1485 *Ident_generated_declaration, *Ident_USR;
1486
1487 /// Factory object for creating ParsedAttr objects.
1488 AttributeFactory AttrFactory;
1489
1490 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
1491 /// replacing them with the non-context-sensitive keywords. This returns
1492 /// true if the token was replaced.
1493 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec,
1494 unsigned &DiagID, bool &isInvalid) {
1495 if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
1496 return false;
1497
1498 if (Tok.getIdentifierInfo() != Ident_vector &&
1499 Tok.getIdentifierInfo() != Ident_bool &&
1500 Tok.getIdentifierInfo() != Ident_Bool &&
1501 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
1502 return false;
1503
1504 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
1505 }
1506
1507 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
1508 /// identifier token, replacing it with the non-context-sensitive __vector.
1509 /// This returns true if the token was replaced.
1510 bool TryAltiVecVectorToken() {
1511 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
1512 Tok.getIdentifierInfo() != Ident_vector)
1513 return false;
1514 return TryAltiVecVectorTokenOutOfLine();
1515 }
1516
1517 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be
1518 /// called from TryAltiVecVectorToken.
1519 bool TryAltiVecVectorTokenOutOfLine();
1520 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
1521 const char *&PrevSpec, unsigned &DiagID,
1522 bool &isInvalid);
1523
1524 void ParseLexedTypeAttribute(LateParsedTypeAttribute &LA,
1525 ParsedAttributes &OutAttrs);
1526
1527 /// Parse cached tokens for a late-parsed attribute and return the parsed
1528 /// attributes. Shared implementation used by both ParseLexedAttribute and
1529 /// ParseLexedTypeAttribute.
1530 ParsedAttributes ParseLexedAttributeTokens(LateParsedAttribute &LPA);
1531
1532 /// Helper function to move LateParsedTypeAttribute pointers from one list
1533 /// to another. Filters type attributes from \p From and appends them to \p
1534 /// To.
1535 static void TakeTypeAttrsAppendingFrom(LateParsedAttrList &To,
1536 LateParsedAttrList &From);
1537
1538 void ParseLexedPragmas(ParsingClass &Class);
1539 void ParseLexedPragma(LateParsedPragma &LP);
1540
1541 /// Consume tokens and store them in the passed token container until
1542 /// we've passed the try keyword and constructor initializers and have
1543 /// consumed the opening brace of the function body. The opening brace will be
1544 /// consumed if and only if there was no error.
1545 ///
1546 /// \return True on error.
1547 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1548
1549 /// ConsumeAndStoreInitializer - Consume and store the token at the passed
1550 /// token container until the end of the current initializer expression
1551 /// (either a default argument or an in-class initializer for a non-static
1552 /// data member).
1553 ///
1554 /// Returns \c true if we reached the end of something initializer-shaped,
1555 /// \c false if we bailed out.
1556 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1557
1558 /// Consume and store tokens from the '?' to the ':' in a conditional
1559 /// expression.
1560 bool ConsumeAndStoreConditional(CachedTokens &Toks);
1561 bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks,
1562 bool StopAtSemi = true,
1563 bool ConsumeFinalToken = true) {
1564 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1565 }
1566
1567 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
1568 /// container until the token 'T' is reached (which gets
1569 /// consumed/stored too, if ConsumeFinalToken).
1570 /// If StopAtSemi is true, then we will stop early at a ';' character.
1571 /// Returns true if token 'T1' or 'T2' was found.
1572 /// NOTE: This is a specialized version of Parser::SkipUntil.
1573 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1574 CachedTokens &Toks, bool StopAtSemi = true,
1575 bool ConsumeFinalToken = true);
1576
1577 //===--------------------------------------------------------------------===//
1578 // C99 6.7: Declarations.
1579
1580 /// A context for parsing declaration specifiers. TODO: flesh this
1581 /// out, there are other significant restrictions on specifiers than
1582 /// would be best implemented in the parser.
1583 enum class DeclSpecContext {
1584 DSC_normal, // normal context
1585 DSC_class, // class context, enables 'friend'
1586 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1587 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1588 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1589 DSC_conv_operator, // C++ type-specifier-seq in an conversion operator
1590 DSC_top_level, // top-level/namespace declaration context
1591 DSC_template_param, // template parameter context
1592 DSC_template_arg, // template argument context
1593 DSC_template_type_arg, // template type argument context
1594 DSC_objc_method_result, // ObjC method result context, enables
1595 // 'instancetype'
1596 DSC_condition, // condition declaration context
1597 DSC_association, // A _Generic selection expression's type association
1598 DSC_new, // C++ new expression
1599 };
1600
1601 /// Is this a context in which we are parsing just a type-specifier (or
1602 /// trailing-type-specifier)?
1603 static bool isTypeSpecifier(DeclSpecContext DSC) {
1604 switch (DSC) {
1605 case DeclSpecContext::DSC_normal:
1606 case DeclSpecContext::DSC_template_param:
1607 case DeclSpecContext::DSC_template_arg:
1608 case DeclSpecContext::DSC_class:
1609 case DeclSpecContext::DSC_top_level:
1610 case DeclSpecContext::DSC_objc_method_result:
1611 case DeclSpecContext::DSC_condition:
1612 return false;
1613
1614 case DeclSpecContext::DSC_template_type_arg:
1615 case DeclSpecContext::DSC_type_specifier:
1616 case DeclSpecContext::DSC_conv_operator:
1617 case DeclSpecContext::DSC_trailing:
1618 case DeclSpecContext::DSC_alias_declaration:
1619 case DeclSpecContext::DSC_association:
1620 case DeclSpecContext::DSC_new:
1621 return true;
1622 }
1623 llvm_unreachable("Missing DeclSpecContext case");
1624 }
1625
1626 /// Whether a defining-type-specifier is permitted in a given context.
1627 enum class AllowDefiningTypeSpec {
1628 /// The grammar doesn't allow a defining-type-specifier here, and we must
1629 /// not parse one (eg, because a '{' could mean something else).
1630 No,
1631 /// The grammar doesn't allow a defining-type-specifier here, but we permit
1632 /// one for error recovery purposes. Sema will reject.
1633 NoButErrorRecovery,
1634 /// The grammar allows a defining-type-specifier here, even though it's
1635 /// always invalid. Sema will reject.
1636 YesButInvalid,
1637 /// The grammar allows a defining-type-specifier here, and one can be valid.
1638 Yes
1639 };
1640
1641 /// Is this a context in which we are parsing defining-type-specifiers (and
1642 /// so permit class and enum definitions in addition to non-defining class and
1643 /// enum elaborated-type-specifiers)?
1644 static AllowDefiningTypeSpec
1645 isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
1646 switch (DSC) {
1647 case DeclSpecContext::DSC_normal:
1648 case DeclSpecContext::DSC_class:
1649 case DeclSpecContext::DSC_top_level:
1650 case DeclSpecContext::DSC_alias_declaration:
1651 case DeclSpecContext::DSC_objc_method_result:
1652 return AllowDefiningTypeSpec::Yes;
1653
1654 case DeclSpecContext::DSC_condition:
1655 case DeclSpecContext::DSC_template_param:
1656 return AllowDefiningTypeSpec::YesButInvalid;
1657
1658 case DeclSpecContext::DSC_template_type_arg:
1659 case DeclSpecContext::DSC_type_specifier:
1660 return AllowDefiningTypeSpec::NoButErrorRecovery;
1661
1662 case DeclSpecContext::DSC_association:
1663 return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
1664 : AllowDefiningTypeSpec::Yes;
1665
1666 case DeclSpecContext::DSC_trailing:
1667 case DeclSpecContext::DSC_conv_operator:
1668 case DeclSpecContext::DSC_template_arg:
1669 case DeclSpecContext::DSC_new:
1670 return AllowDefiningTypeSpec::No;
1671 }
1672 llvm_unreachable("Missing DeclSpecContext case");
1673 }
1674
1675 /// Is this a context in which an opaque-enum-declaration can appear?
1676 static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
1677 switch (DSC) {
1678 case DeclSpecContext::DSC_normal:
1679 case DeclSpecContext::DSC_class:
1680 case DeclSpecContext::DSC_top_level:
1681 return true;
1682
1683 case DeclSpecContext::DSC_alias_declaration:
1684 case DeclSpecContext::DSC_objc_method_result:
1685 case DeclSpecContext::DSC_condition:
1686 case DeclSpecContext::DSC_template_param:
1687 case DeclSpecContext::DSC_template_type_arg:
1688 case DeclSpecContext::DSC_type_specifier:
1689 case DeclSpecContext::DSC_trailing:
1690 case DeclSpecContext::DSC_association:
1691 case DeclSpecContext::DSC_conv_operator:
1692 case DeclSpecContext::DSC_template_arg:
1693 case DeclSpecContext::DSC_new:
1694
1695 return false;
1696 }
1697 llvm_unreachable("Missing DeclSpecContext case");
1698 }
1699
1700 /// Is this a context in which we can perform class template argument
1701 /// deduction?
1702 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
1703 switch (DSC) {
1704 case DeclSpecContext::DSC_normal:
1705 case DeclSpecContext::DSC_template_param:
1706 case DeclSpecContext::DSC_template_arg:
1707 case DeclSpecContext::DSC_class:
1708 case DeclSpecContext::DSC_top_level:
1709 case DeclSpecContext::DSC_condition:
1710 case DeclSpecContext::DSC_type_specifier:
1711 case DeclSpecContext::DSC_association:
1712 case DeclSpecContext::DSC_conv_operator:
1713 case DeclSpecContext::DSC_new:
1714 return true;
1715
1716 case DeclSpecContext::DSC_objc_method_result:
1717 case DeclSpecContext::DSC_template_type_arg:
1718 case DeclSpecContext::DSC_trailing:
1719 case DeclSpecContext::DSC_alias_declaration:
1720 return false;
1721 }
1722 llvm_unreachable("Missing DeclSpecContext case");
1723 }
1724
1725 // Is this a context in which an implicit 'typename' is allowed?
1727 getImplicitTypenameContext(DeclSpecContext DSC) {
1728 switch (DSC) {
1729 case DeclSpecContext::DSC_class:
1730 case DeclSpecContext::DSC_top_level:
1731 case DeclSpecContext::DSC_type_specifier:
1732 case DeclSpecContext::DSC_template_type_arg:
1733 case DeclSpecContext::DSC_trailing:
1734 case DeclSpecContext::DSC_alias_declaration:
1735 case DeclSpecContext::DSC_template_param:
1736 case DeclSpecContext::DSC_new:
1737 case DeclSpecContext::DSC_conv_operator:
1739
1740 case DeclSpecContext::DSC_normal:
1741 case DeclSpecContext::DSC_objc_method_result:
1742 case DeclSpecContext::DSC_condition:
1743 case DeclSpecContext::DSC_template_arg:
1744 case DeclSpecContext::DSC_association:
1746 }
1747 llvm_unreachable("Missing DeclSpecContext case");
1748 }
1749
1750 /// Information on a C++0x for-range-initializer found while parsing a
1751 /// declaration which turns out to be a for-range-declaration.
1752 struct ForRangeInit {
1753 SourceLocation ColonLoc;
1754 ExprResult RangeExpr;
1755 SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
1756 CXXExpansionStmtDecl *ExpansionStmt = nullptr;
1757 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1758 };
1759 struct ForRangeInfo : ForRangeInit {
1760 StmtResult LoopVar;
1761 };
1762
1763 /// ParseDeclaration - Parse a full 'declaration', which consists of
1764 /// declaration-specifiers, some number of declarators, and a semicolon.
1765 /// 'Context' should be a DeclaratorContext value. This returns the
1766 /// location of the semicolon in DeclEnd.
1767 ///
1768 /// \verbatim
1769 /// declaration: [C99 6.7]
1770 /// block-declaration ->
1771 /// simple-declaration
1772 /// others [FIXME]
1773 /// [C++] template-declaration
1774 /// [C++] namespace-definition
1775 /// [C++] using-directive
1776 /// [C++] using-declaration
1777 /// [C++11/C11] static_assert-declaration
1778 /// others... [FIXME]
1779 /// \endverbatim
1780 ///
1781 DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
1782 SourceLocation &DeclEnd,
1783 ParsedAttributes &DeclAttrs,
1784 ParsedAttributes &DeclSpecAttrs,
1785 SourceLocation *DeclSpecStart = nullptr);
1786
1787 /// \verbatim
1788 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1789 /// declaration-specifiers init-declarator-list[opt] ';'
1790 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1791 /// init-declarator-list ';'
1792 ///[C90/C++]init-declarator-list ';' [TODO]
1793 /// [OMP] threadprivate-directive
1794 /// [OMP] allocate-directive [TODO]
1795 ///
1796 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1797 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1798 /// \endverbatim
1799 ///
1800 /// If RequireSemi is false, this does not check for a ';' at the end of the
1801 /// declaration. If it is true, it checks for and eats it.
1802 ///
1803 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1804 /// of a simple-declaration. If we find that we are, we also parse the
1805 /// for-range-initializer, and place it here.
1806 ///
1807 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1808 /// the Declaration. The SourceLocation for this Decl is set to
1809 /// DeclSpecStart if DeclSpecStart is non-null.
1811 ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1812 ParsedAttributes &DeclAttrs,
1813 ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
1814 ForRangeInit *FRI = nullptr,
1815 SourceLocation *DeclSpecStart = nullptr);
1816
1817 /// ParseDeclGroup - Having concluded that this is either a function
1818 /// definition or a group of object declarations, actually parse the
1819 /// result.
1820 ///
1821 /// Returns true if this might be the start of a declarator, or a common typo
1822 /// for a declarator.
1823 bool MightBeDeclarator(DeclaratorContext Context);
1824 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
1825 ParsedAttributes &Attrs,
1826 ParsedTemplateInfo &TemplateInfo,
1827 SourceLocation *DeclEnd = nullptr,
1828 ForRangeInit *FRI = nullptr);
1829
1830 /// Parse 'declaration' after parsing 'declaration-specifiers
1831 /// declarator'. This method parses the remainder of the declaration
1832 /// (including any attributes or initializer, among other things) and
1833 /// finalizes the declaration.
1834 ///
1835 /// \verbatim
1836 /// init-declarator: [C99 6.7]
1837 /// declarator
1838 /// declarator '=' initializer
1839 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1840 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1841 /// [C++] declarator initializer[opt]
1842 ///
1843 /// [C++] initializer:
1844 /// [C++] '=' initializer-clause
1845 /// [C++] '(' expression-list ')'
1846 /// [C++0x] '=' 'default' [TODO]
1847 /// [C++0x] '=' 'delete'
1848 /// [C++0x] braced-init-list
1849 /// \endverbatim
1850 ///
1851 /// According to the standard grammar, =default and =delete are function
1852 /// definitions, but that definitely doesn't fit with the parser here.
1853 ///
1854 Decl *ParseDeclarationAfterDeclarator(
1855 Declarator &D,
1856 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1857
1858 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1859 /// declarator. Returns true on an error.
1860 bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1861 Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1862 Declarator &D,
1863 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1864 ForRangeInit *FRI = nullptr);
1865
1866 /// ParseImplicitInt - This method is called when we have an non-typename
1867 /// identifier in a declspec (which normally terminates the decl spec) when
1868 /// the declspec has no type specifier. In this case, the declspec is either
1869 /// malformed or is "implicit int" (in K&R and C89).
1870 ///
1871 /// This method handles diagnosing this prettily and returns false if the
1872 /// declspec is done being processed. If it recovers and thinks there may be
1873 /// other pieces of declspec after it, it returns true.
1874 ///
1875 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1876 ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
1877 DeclSpecContext DSC, ParsedAttributes &Attrs);
1878
1879 /// Determine the declaration specifier context from the declarator
1880 /// context.
1881 ///
1882 /// \param Context the declarator context, which is one of the
1883 /// DeclaratorContext enumerator values.
1884 DeclSpecContext
1885 getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
1886 void
1887 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1889 DeclSpecContext DSC = DeclSpecContext::DSC_normal,
1890 LateParsedAttrList *LateAttrs = nullptr) {
1891 return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
1892 getImplicitTypenameContext(DSC));
1893 }
1894
1895 /// ParseDeclarationSpecifiers
1896 /// \verbatim
1897 /// declaration-specifiers: [C99 6.7]
1898 /// storage-class-specifier declaration-specifiers[opt]
1899 /// type-specifier declaration-specifiers[opt]
1900 /// [C99] function-specifier declaration-specifiers[opt]
1901 /// [C11] alignment-specifier declaration-specifiers[opt]
1902 /// [GNU] attributes declaration-specifiers[opt]
1903 /// [Clang] '__module_private__' declaration-specifiers[opt]
1904 /// [ObjC1] '__kindof' declaration-specifiers[opt]
1905 ///
1906 /// storage-class-specifier: [C99 6.7.1]
1907 /// 'typedef'
1908 /// 'extern'
1909 /// 'static'
1910 /// 'auto'
1911 /// 'register'
1912 /// [C++] 'mutable'
1913 /// [C++11] 'thread_local'
1914 /// [C11] '_Thread_local'
1915 /// [GNU] '__thread'
1916 /// function-specifier: [C99 6.7.4]
1917 /// [C99] 'inline'
1918 /// [C++] 'virtual'
1919 /// [C++] 'explicit'
1920 /// [OpenCL] '__kernel'
1921 /// 'friend': [C++ dcl.friend]
1922 /// 'constexpr': [C++0x dcl.constexpr]
1923 /// \endverbatim
1924 void
1925 ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
1926 AccessSpecifier AS, DeclSpecContext DSC,
1927 LateParsedAttrList *LateAttrs,
1928 ImplicitTypenameContext AllowImplicitTypename);
1929
1930 /// Determine whether we're looking at something that might be a declarator
1931 /// in a simple-declaration. If it can't possibly be a declarator, maybe
1932 /// diagnose a missing semicolon after a prior tag definition in the decl
1933 /// specifier.
1934 ///
1935 /// \return \c true if an error occurred and this can't be any kind of
1936 /// declaration.
1937 bool DiagnoseMissingSemiAfterTagDefinition(
1938 DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
1939 LateParsedAttrList *LateAttrs = nullptr);
1940
1941 void ParseSpecifierQualifierList(
1942 DeclSpec &DS, AccessSpecifier AS = AS_none,
1943 DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
1944 ParseSpecifierQualifierList(DS, getImplicitTypenameContext(DSC), AS, DSC);
1945 }
1946
1947 /// ParseSpecifierQualifierList
1948 /// \verbatim
1949 /// specifier-qualifier-list:
1950 /// type-specifier specifier-qualifier-list[opt]
1951 /// type-qualifier specifier-qualifier-list[opt]
1952 /// [GNU] attributes specifier-qualifier-list[opt]
1953 /// \endverbatim
1954 ///
1955 void ParseSpecifierQualifierList(
1956 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
1958 DeclSpecContext DSC = DeclSpecContext::DSC_normal);
1959
1960 /// ParseEnumSpecifier
1961 /// \verbatim
1962 /// enum-specifier: [C99 6.7.2.2]
1963 /// 'enum' identifier[opt] '{' enumerator-list '}'
1964 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1965 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1966 /// '}' attributes[opt]
1967 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
1968 /// '}'
1969 /// 'enum' identifier
1970 /// [GNU] 'enum' attributes[opt] identifier
1971 ///
1972 /// [C++11] enum-head '{' enumerator-list[opt] '}'
1973 /// [C++11] enum-head '{' enumerator-list ',' '}'
1974 ///
1975 /// enum-head: [C++11]
1976 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
1977 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
1978 /// identifier enum-base[opt]
1979 ///
1980 /// enum-key: [C++11]
1981 /// 'enum'
1982 /// 'enum' 'class'
1983 /// 'enum' 'struct'
1984 ///
1985 /// enum-base: [C++11]
1986 /// ':' type-specifier-seq
1987 ///
1988 /// [C++] elaborated-type-specifier:
1989 /// [C++] 'enum' nested-name-specifier[opt] identifier
1990 /// \endverbatim
1991 ///
1992 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1993 const ParsedTemplateInfo &TemplateInfo,
1994 AccessSpecifier AS, DeclSpecContext DSC);
1995
1996 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
1997 /// \verbatim
1998 /// enumerator-list:
1999 /// enumerator
2000 /// enumerator-list ',' enumerator
2001 /// enumerator:
2002 /// enumeration-constant attributes[opt]
2003 /// enumeration-constant attributes[opt] '=' constant-expression
2004 /// enumeration-constant:
2005 /// identifier
2006 /// \endverbatim
2007 ///
2008 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl,
2009 SkipBodyInfo *SkipBody = nullptr);
2010
2011 /// ParseStructUnionBody
2012 /// \verbatim
2013 /// struct-contents:
2014 /// struct-declaration-list
2015 /// [EXT] empty
2016 /// [GNU] "struct-declaration-list" without terminating ';'
2017 /// struct-declaration-list:
2018 /// struct-declaration
2019 /// struct-declaration-list struct-declaration
2020 /// [OBC] '@' 'defs' '(' class-name ')'
2021 /// \endverbatim
2022 ///
2023 void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2024 RecordDecl *TagDecl);
2025
2026 /// ParseStructDeclaration - Parse a struct declaration without the
2027 /// terminating semicolon.
2028 ///
2029 /// Note that a struct declaration refers to a declaration in a struct,
2030 /// not to the declaration of a struct.
2031 ///
2032 /// \verbatim
2033 /// struct-declaration:
2034 /// [C23] attributes-specifier-seq[opt]
2035 /// specifier-qualifier-list struct-declarator-list
2036 /// [GNU] __extension__ struct-declaration
2037 /// [GNU] specifier-qualifier-list
2038 /// struct-declarator-list:
2039 /// struct-declarator
2040 /// struct-declarator-list ',' struct-declarator
2041 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
2042 /// struct-declarator:
2043 /// declarator
2044 /// [GNU] declarator attributes[opt]
2045 /// declarator[opt] ':' constant-expression
2046 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
2047 /// \endverbatim
2048 ///
2049 void ParseStructDeclaration(
2050 ParsingDeclSpec &DS,
2051 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
2052 LateParsedAttrList *LateFieldAttrs = nullptr);
2053
2054 DeclGroupPtrTy ParseTopLevelStmtDecl();
2055
2056 /// isDeclarationSpecifier() - Return true if the current token is part of a
2057 /// declaration specifier.
2058 ///
2059 /// \param AllowImplicitTypename whether this is a context where T::type [T
2060 /// dependent] can appear.
2061 /// \param DisambiguatingWithExpression True to indicate that the purpose of
2062 /// this check is to disambiguate between an expression and a declaration.
2063 bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2064 bool DisambiguatingWithExpression = false);
2065
2066 /// isTypeSpecifierQualifier - Return true if the current token could be the
2067 /// start of a specifier-qualifier-list.
2068 bool isTypeSpecifierQualifier(const Token &Tok);
2069
2070 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2071 /// is definitely a type-specifier. Return false if it isn't part of a type
2072 /// specifier or if we're not sure.
2073 bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2074
2075 /// Starting with a scope specifier, identifier, or
2076 /// template-id that refers to the current class, determine whether
2077 /// this is a constructor declarator.
2078 bool isConstructorDeclarator(
2079 bool Unqualified, bool DeductionGuide = false,
2081 const ParsedTemplateInfo *TemplateInfo = nullptr);
2082
2083 /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2084 /// _BitInt as an extension when appropriate.
2085 void DiagnoseBitIntUse(const Token &Tok);
2086
2087 // Check for the start of an attribute-specifier-seq in a context where an
2088 // attribute is not allowed.
2089 bool CheckProhibitedCXX11Attribute() {
2090 assert(Tok.is(tok::l_square));
2091 if (NextToken().isNot(tok::l_square))
2092 return false;
2093 return DiagnoseProhibitedCXX11Attribute();
2094 }
2095
2096 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square
2097 /// brackets of a C++11 attribute-specifier in a location where an attribute
2098 /// is not permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed.
2099 /// Diagnose this situation.
2100 ///
2101 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false
2102 /// if this doesn't appear to actually be an attribute-specifier, and the
2103 /// caller should try to parse it.
2104 bool DiagnoseProhibitedCXX11Attribute();
2105
2106 void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2107 SourceLocation CorrectLocation) {
2108 if (!Tok.isRegularKeywordAttribute() &&
2109 (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2110 Tok.isNot(tok::kw_alignas))
2111 return;
2112 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2113 }
2114
2115 /// We have found the opening square brackets of a C++11
2116 /// attribute-specifier in a location where an attribute is not permitted, but
2117 /// we know where the attributes ought to be written. Parse them anyway, and
2118 /// provide a fixit moving them to the right place.
2119 void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2120 SourceLocation CorrectLocation);
2121
2122 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
2123 // applies to var, not the type Foo.
2124 // As an exception to the rule, __declspec(align(...)) before the
2125 // class-key affects the type instead of the variable.
2126 // Also, Microsoft-style [attributes] seem to affect the type instead of the
2127 // variable.
2128 // This function moves attributes that should apply to the type off DS to
2129 // Attrs.
2130 void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2131 TagUseKind TUK);
2132
2133 // FixItLoc = possible correct location for the attributes
2134 void ProhibitAttributes(ParsedAttributes &Attrs,
2135 SourceLocation FixItLoc = SourceLocation()) {
2136 if (Attrs.Range.isInvalid())
2137 return;
2138 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2139 Attrs.clear();
2140 }
2141
2142 void ProhibitAttributes(ParsedAttributesView &Attrs,
2143 SourceLocation FixItLoc = SourceLocation()) {
2144 if (Attrs.Range.isInvalid())
2145 return;
2146 DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2147 Attrs.clearListOnly();
2148 }
2149 void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2150 SourceLocation FixItLoc);
2151
2152 // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2153 // which standard permits but we don't supported yet, for example, attributes
2154 // appertain to decl specifiers.
2155 // For the most cases we don't want to warn on unknown type attributes, but
2156 // left them to later diagnoses. However, for a few cases like module
2157 // declarations and module import declarations, we should do it.
2158 void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2159 unsigned KeywordDiagId,
2160 bool DiagnoseEmptyAttrs = false,
2161 bool WarnOnUnknownAttrs = false);
2162
2163 /// Emit warnings for C++11 and C23 attributes that are in a position that
2164 /// clang accepts as an extension.
2165 void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2166
2167 ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2168
2169 /// Parses a comma-delimited list of arguments of an attribute \p AttrName,
2170 /// filling \p Exprs. \p ArgsProperties specifies which of the arguments
2171 /// should be parsed as unevaluated string literals. \p Arg is the number
2172 /// of arguments parsed before calling / this function (the index of the
2173 /// argument to be parsed next).
2174 bool ParseAttributeArgumentList(
2175 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
2176 ParsedAttributeArgumentsProperties ArgsProperties, unsigned Arg);
2177
2178 /// Parses syntax-generic attribute arguments for attributes which are
2179 /// known to the implementation, and adds them to the given ParsedAttributes
2180 /// list with the given attribute syntax. Returns the number of arguments
2181 /// parsed for the attribute.
2182 unsigned
2183 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2184 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2185 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2186 ParsedAttr::Form Form);
2187
2188 enum ParseAttrKindMask {
2189 PAKM_GNU = 1 << 0,
2190 PAKM_Declspec = 1 << 1,
2191 PAKM_CXX11 = 1 << 2,
2192 };
2193
2194 /// \brief Parse attributes based on what syntaxes are desired, allowing for
2195 /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2196 /// __attribute__((...)) __declspec(...) __attribute__((...)))
2197 /// Note that Microsoft attributes (spelled with single square brackets) are
2198 /// not supported by this because of parsing ambiguities with other
2199 /// constructs.
2200 ///
2201 /// There are some attribute parse orderings that should not be allowed in
2202 /// arbitrary order. e.g.,
2203 ///
2204 /// \verbatim
2205 /// [[]] __attribute__(()) int i; // OK
2206 /// __attribute__(()) [[]] int i; // Not OK
2207 /// \endverbatim
2208 ///
2209 /// Such situations should use the specific attribute parsing functionality.
2210 void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2211 LateParsedAttrList *LateAttrs = nullptr);
2212 /// \brief Possibly parse attributes based on what syntaxes are desired,
2213 /// allowing for the order to vary.
2214 bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2215 LateParsedAttrList *LateAttrs = nullptr) {
2216 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2217 isAllowedCXX11AttributeSpecifier()) {
2218 ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2219 return true;
2220 }
2221 return false;
2222 }
2223
2224 void MaybeParseGNUAttributes(Declarator &D,
2225 LateParsedAttrList *LateAttrs = nullptr) {
2226 if (Tok.is(tok::kw___attribute)) {
2227 ParsedAttributes Attrs(AttrFactory);
2228 ParseGNUAttributes(Attrs, LateAttrs, &D);
2229 D.takeAttributesAppending(Attrs);
2230 }
2231 }
2232
2233 bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2234 LateParsedAttrList *LateAttrs = nullptr) {
2235 if (Tok.is(tok::kw___attribute)) {
2236 ParseGNUAttributes(Attrs, LateAttrs);
2237 return true;
2238 }
2239 return false;
2240 }
2241
2242 /// ParseSingleGNUAttribute - Parse a single GNU attribute.
2243 ///
2244 /// \verbatim
2245 /// [GNU] attrib:
2246 /// empty
2247 /// attrib-name
2248 /// attrib-name '(' identifier ')'
2249 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2250 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2251 ///
2252 /// [GNU] attrib-name:
2253 /// identifier
2254 /// typespec
2255 /// typequal
2256 /// storageclass
2257 /// \endverbatim
2258 bool ParseSingleGNUAttribute(ParsedAttributes &Attrs, SourceLocation &EndLoc,
2259 LateParsedAttrList *LateAttrs = nullptr,
2260 Declarator *D = nullptr);
2261
2262 /// ParseGNUAttributes - Parse a non-empty attributes list.
2263 ///
2264 /// \verbatim
2265 /// [GNU] attributes:
2266 /// attribute
2267 /// attributes attribute
2268 ///
2269 /// [GNU] attribute:
2270 /// '__attribute__' '(' '(' attribute-list ')' ')'
2271 ///
2272 /// [GNU] attribute-list:
2273 /// attrib
2274 /// attribute_list ',' attrib
2275 ///
2276 /// [GNU] attrib:
2277 /// empty
2278 /// attrib-name
2279 /// attrib-name '(' identifier ')'
2280 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
2281 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
2282 ///
2283 /// [GNU] attrib-name:
2284 /// identifier
2285 /// typespec
2286 /// typequal
2287 /// storageclass
2288 /// \endverbatim
2289 ///
2290 /// Whether an attribute takes an 'identifier' is determined by the
2291 /// attrib-name. GCC's behavior here is not worth imitating:
2292 ///
2293 /// * In C mode, if the attribute argument list starts with an identifier
2294 /// followed by a ',' or an ')', and the identifier doesn't resolve to
2295 /// a type, it is parsed as an identifier. If the attribute actually
2296 /// wanted an expression, it's out of luck (but it turns out that no
2297 /// attributes work that way, because C constant expressions are very
2298 /// limited).
2299 /// * In C++ mode, if the attribute argument list starts with an identifier,
2300 /// and the attribute *wants* an identifier, it is parsed as an identifier.
2301 /// At block scope, any additional tokens between the identifier and the
2302 /// ',' or ')' are ignored, otherwise they produce a parse error.
2303 ///
2304 /// We follow the C++ model, but don't allow junk after the identifier.
2305 void ParseGNUAttributes(ParsedAttributes &Attrs,
2306 LateParsedAttrList *LateAttrs = nullptr,
2307 Declarator *D = nullptr);
2308
2309 /// Parse the arguments to a parameterized GNU attribute or
2310 /// a C++11 attribute in "gnu" namespace.
2311 void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2312 SourceLocation AttrNameLoc,
2313 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2314 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2315 ParsedAttr::Form Form, Declarator *D);
2316 IdentifierLoc *ParseIdentifierLoc();
2317
2318 unsigned
2319 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2320 ParsedAttributes &Attrs, SourceLocation *EndLoc,
2321 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2322 ParsedAttr::Form Form);
2323
2324 void MaybeParseCXX11Attributes(Declarator &D) {
2325 if (isAllowedCXX11AttributeSpecifier()) {
2326 ParsedAttributes Attrs(AttrFactory);
2327 ParseCXX11Attributes(Attrs);
2328 D.takeAttributesAppending(Attrs);
2329 }
2330 }
2331
2332 bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2333 bool OuterMightBeMessageSend = false) {
2334 if (isAllowedCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2335 ParseCXX11Attributes(Attrs);
2336 return true;
2337 }
2338 return false;
2339 }
2340
2341 bool MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
2342 bool AttrsParsed = false;
2343 if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
2344 Tok.is(tok::l_square)) {
2345 ParsedAttributes AttrsWithRange(AttrFactory);
2346 ParseMicrosoftAttributes(AttrsWithRange);
2347 AttrsParsed = !AttrsWithRange.empty();
2348 Attrs.takeAllAppendingFrom(AttrsWithRange);
2349 }
2350 return AttrsParsed;
2351 }
2352 bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
2353 if (getLangOpts().DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
2354 ParseMicrosoftDeclSpecs(Attrs);
2355 return true;
2356 }
2357 return false;
2358 }
2359
2360 /// \verbatim
2361 /// [MS] decl-specifier:
2362 /// __declspec ( extended-decl-modifier-seq )
2363 ///
2364 /// [MS] extended-decl-modifier-seq:
2365 /// extended-decl-modifier[opt]
2366 /// extended-decl-modifier extended-decl-modifier-seq
2367 /// \endverbatim
2368 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
2369 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2370 SourceLocation AttrNameLoc,
2371 ParsedAttributes &Attrs);
2372 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2373 void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
2374 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2375 SourceLocation SkipExtendedMicrosoftTypeAttributes();
2376
2377 void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2378 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2379 void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2380 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2381 void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
2382 bool isHLSLQualifier(const Token &Tok) const;
2383 void ParseHLSLQualifiers(ParsedAttributes &Attrs);
2384
2385 /// Parse a version number.
2386 ///
2387 /// \verbatim
2388 /// version:
2389 /// simple-integer
2390 /// simple-integer '.' simple-integer
2391 /// simple-integer '_' simple-integer
2392 /// simple-integer '.' simple-integer '.' simple-integer
2393 /// simple-integer '_' simple-integer '_' simple-integer
2394 /// \endverbatim
2395 VersionTuple ParseVersionTuple(SourceRange &Range);
2396
2397 /// Parse the contents of the "availability" attribute.
2398 ///
2399 /// \verbatim
2400 /// availability-attribute:
2401 /// 'availability' '(' platform ',' opt-strict version-arg-list,
2402 /// opt-replacement, opt-message')'
2403 ///
2404 /// platform:
2405 /// identifier
2406 ///
2407 /// opt-strict:
2408 /// 'strict' ','
2409 ///
2410 /// version-arg-list:
2411 /// version-arg
2412 /// version-arg ',' version-arg-list
2413 ///
2414 /// version-arg:
2415 /// 'introduced' '=' version
2416 /// 'deprecated' '=' version
2417 /// 'obsoleted' = version
2418 /// 'unavailable'
2419 /// opt-replacement:
2420 /// 'replacement' '=' <string>
2421 /// opt-message:
2422 /// 'message' '=' <string>
2423 /// \endverbatim
2424 void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2425 SourceLocation AvailabilityLoc,
2426 ParsedAttributes &attrs,
2427 SourceLocation *endLoc,
2428 IdentifierInfo *ScopeName,
2429 SourceLocation ScopeLoc,
2430 ParsedAttr::Form Form);
2431
2432 /// Parse the contents of the "external_source_symbol" attribute.
2433 ///
2434 /// \verbatim
2435 /// external-source-symbol-attribute:
2436 /// 'external_source_symbol' '(' keyword-arg-list ')'
2437 ///
2438 /// keyword-arg-list:
2439 /// keyword-arg
2440 /// keyword-arg ',' keyword-arg-list
2441 ///
2442 /// keyword-arg:
2443 /// 'language' '=' <string>
2444 /// 'defined_in' '=' <string>
2445 /// 'USR' '=' <string>
2446 /// 'generated_declaration'
2447 /// \endverbatim
2448 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2449 SourceLocation Loc,
2450 ParsedAttributes &Attrs,
2451 SourceLocation *EndLoc,
2452 IdentifierInfo *ScopeName,
2453 SourceLocation ScopeLoc,
2454 ParsedAttr::Form Form);
2455
2456 /// Parse the contents of the "objc_bridge_related" attribute.
2457 /// \verbatim
2458 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
2459 /// related_class:
2460 /// Identifier
2461 ///
2462 /// opt-class_method:
2463 /// Identifier: | <empty>
2464 ///
2465 /// opt-instance_method:
2466 /// Identifier | <empty>
2467 /// \endverbatim
2468 ///
2469 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2470 SourceLocation ObjCBridgeRelatedLoc,
2471 ParsedAttributes &Attrs,
2472 SourceLocation *EndLoc,
2473 IdentifierInfo *ScopeName,
2474 SourceLocation ScopeLoc,
2475 ParsedAttr::Form Form);
2476
2477 void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
2478 SourceLocation AttrNameLoc,
2479 ParsedAttributes &Attrs,
2480 SourceLocation *EndLoc,
2481 IdentifierInfo *ScopeName,
2482 SourceLocation ScopeLoc,
2483 ParsedAttr::Form Form);
2484
2485 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2486 SourceLocation AttrNameLoc,
2487 ParsedAttributes &Attrs,
2488 SourceLocation *EndLoc,
2489 IdentifierInfo *ScopeName,
2490 SourceLocation ScopeLoc,
2491 ParsedAttr::Form Form);
2492
2493 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2494 SourceLocation AttrNameLoc,
2495 ParsedAttributes &Attrs,
2496 IdentifierInfo *ScopeName,
2497 SourceLocation ScopeLoc,
2498 ParsedAttr::Form Form);
2499
2500 void DistributeCLateParsedAttrs(Decl *Dcl, LateParsedAttrList *LateAttrs);
2501
2502 /// Bounds attributes (e.g., counted_by):
2503 /// \verbatim
2504 /// AttrName '(' expression ')'
2505 /// \endverbatim
2506 void ParseBoundsAttribute(IdentifierInfo &AttrName,
2507 SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2508 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2509 ParsedAttr::Form Form);
2510
2511 /// \verbatim
2512 /// [GNU] typeof-specifier:
2513 /// typeof ( expressions )
2514 /// typeof ( type-name )
2515 /// [GNU/C++] typeof unary-expression
2516 /// [C23] typeof-specifier:
2517 /// typeof '(' typeof-specifier-argument ')'
2518 /// typeof_unqual '(' typeof-specifier-argument ')'
2519 ///
2520 /// typeof-specifier-argument:
2521 /// expression
2522 /// type-name
2523 /// \endverbatim
2524 ///
2525 void ParseTypeofSpecifier(DeclSpec &DS);
2526
2527 /// \verbatim
2528 /// [C11] atomic-specifier:
2529 /// _Atomic ( type-name )
2530 /// \endverbatim
2531 ///
2532 void ParseAtomicSpecifier(DeclSpec &DS);
2533
2534 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2535 ///
2536 /// \verbatim
2537 /// [C11] type-id
2538 /// [C11] constant-expression
2539 /// [C++0x] type-id ...[opt]
2540 /// [C++0x] assignment-expression ...[opt]
2541 /// \endverbatim
2542 ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
2543 SourceLocation &EllipsisLoc, bool &IsType,
2544 ParsedType &Ty);
2545
2546 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2547 /// attribute to Attrs.
2548 ///
2549 /// \verbatim
2550 /// alignment-specifier:
2551 /// [C11] '_Alignas' '(' type-id ')'
2552 /// [C11] '_Alignas' '(' constant-expression ')'
2553 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2554 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2555 /// \endverbatim
2556 void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2557 SourceLocation *endLoc = nullptr);
2558 ExprResult ParseExtIntegerArgument();
2559
2560 /// \verbatim
2561 /// type-qualifier:
2562 /// ('__ptrauth') '(' constant-expression
2563 /// (',' constant-expression)[opt]
2564 /// (',' constant-expression)[opt] ')'
2565 /// \endverbatim
2566 void ParsePtrauthQualifier(ParsedAttributes &Attrs);
2567
2568 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2569 /// enter a new C++ declarator scope and exit it when the function is
2570 /// finished.
2571 class DeclaratorScopeObj {
2572 Parser &P;
2573 CXXScopeSpec &SS;
2574 bool EnteredScope;
2575 bool CreatedScope;
2576
2577 public:
2578 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2579 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2580
2581 void EnterDeclaratorScope() {
2582 assert(!EnteredScope && "Already entered the scope!");
2583 assert(SS.isSet() && "C++ scope was not set!");
2584
2585 CreatedScope = true;
2586 P.EnterScope(0); // Not a decl scope.
2587
2588 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2589 EnteredScope = true;
2590 }
2591
2592 ~DeclaratorScopeObj() {
2593 if (EnteredScope) {
2594 assert(SS.isSet() && "C++ scope was cleared ?");
2595 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2596 }
2597 if (CreatedScope)
2598 P.ExitScope();
2599 }
2600 };
2601
2602 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2603 void ParseDeclarator(Declarator &D);
2604 /// A function that parses a variant of direct-declarator.
2605 typedef void (Parser::*DirectDeclParseFunction)(Declarator &);
2606
2607 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The
2608 /// direct-declarator is parsed by the function passed to it. Pass null, and
2609 /// the direct-declarator isn't parsed at all, making this function
2610 /// effectively parse the C++ ptr-operator production.
2611 ///
2612 /// If the grammar of this construct is extended, matching changes must also
2613 /// be made to TryParseDeclarator and MightBeDeclarator, and possibly to
2614 /// isConstructorDeclarator.
2615 ///
2616 /// \verbatim
2617 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2618 /// [C] pointer[opt] direct-declarator
2619 /// [C++] direct-declarator
2620 /// [C++] ptr-operator declarator
2621 ///
2622 /// pointer: [C99 6.7.5]
2623 /// '*' type-qualifier-list[opt]
2624 /// '*' type-qualifier-list[opt] pointer
2625 ///
2626 /// ptr-operator:
2627 /// '*' cv-qualifier-seq[opt]
2628 /// '&'
2629 /// [C++0x] '&&'
2630 /// [GNU] '&' restrict[opt] attributes[opt]
2631 /// [GNU?] '&&' restrict[opt] attributes[opt]
2632 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2633 /// \endverbatim
2634 void ParseDeclaratorInternal(Declarator &D,
2635 DirectDeclParseFunction DirectDeclParser);
2636
2637 enum AttrRequirements {
2638 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2639 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2640 AR_GNUAttributesParsed = 1 << 1,
2641 AR_CXX11AttributesParsed = 1 << 2,
2642 AR_DeclspecAttributesParsed = 1 << 3,
2643 AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed |
2644 AR_DeclspecAttributesParsed,
2645 AR_VendorAttributesParsed =
2646 AR_GNUAttributesParsed | AR_DeclspecAttributesParsed
2647 };
2648
2649 /// ParseTypeQualifierListOpt
2650 /// \verbatim
2651 /// type-qualifier-list: [C99 6.7.5]
2652 /// type-qualifier
2653 /// [vendor] attributes
2654 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2655 /// type-qualifier-list type-qualifier
2656 /// [vendor] type-qualifier-list attributes
2657 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
2658 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2659 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
2660 /// \endverbatim
2661 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
2662 /// AttrRequirements bitmask values.
2663 void ParseTypeQualifierListOpt(
2664 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2665 bool AtomicOrPtrauthAllowed = true, bool IdentifierRequired = false,
2666 llvm::function_ref<void()> CodeCompletionHandler = {});
2667
2668 /// ParseDirectDeclarator
2669 /// \verbatim
2670 /// direct-declarator: [C99 6.7.5]
2671 /// [C99] identifier
2672 /// '(' declarator ')'
2673 /// [GNU] '(' attributes declarator ')'
2674 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2675 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2676 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2677 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2678 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2679 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2680 /// attribute-specifier-seq[opt]
2681 /// direct-declarator '(' parameter-type-list ')'
2682 /// direct-declarator '(' identifier-list[opt] ')'
2683 /// [GNU] direct-declarator '(' parameter-forward-declarations
2684 /// parameter-type-list[opt] ')'
2685 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
2686 /// cv-qualifier-seq[opt] exception-specification[opt]
2687 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
2688 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
2689 /// ref-qualifier[opt] exception-specification[opt]
2690 /// [C++] declarator-id
2691 /// [C++11] declarator-id attribute-specifier-seq[opt]
2692 ///
2693 /// declarator-id: [C++ 8]
2694 /// '...'[opt] id-expression
2695 /// '::'[opt] nested-name-specifier[opt] type-name
2696 ///
2697 /// id-expression: [C++ 5.1]
2698 /// unqualified-id
2699 /// qualified-id
2700 ///
2701 /// unqualified-id: [C++ 5.1]
2702 /// identifier
2703 /// operator-function-id
2704 /// conversion-function-id
2705 /// '~' class-name
2706 /// template-id
2707 ///
2708 /// C++17 adds the following, which we also handle here:
2709 ///
2710 /// simple-declaration:
2711 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
2712 /// \endverbatim
2713 ///
2714 /// Note, any additional constructs added here may need corresponding changes
2715 /// in isConstructorDeclarator.
2716 void ParseDirectDeclarator(Declarator &D);
2717 void ParseDecompositionDeclarator(Declarator &D);
2718
2719 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
2720 /// only called before the identifier, so these are most likely just grouping
2721 /// parens for precedence. If we find that these are actually function
2722 /// parameter parens in an abstract-declarator, we call
2723 /// ParseFunctionDeclarator.
2724 ///
2725 /// \verbatim
2726 /// direct-declarator:
2727 /// '(' declarator ')'
2728 /// [GNU] '(' attributes declarator ')'
2729 /// direct-declarator '(' parameter-type-list ')'
2730 /// direct-declarator '(' identifier-list[opt] ')'
2731 /// [GNU] direct-declarator '(' parameter-forward-declarations
2732 /// parameter-type-list[opt] ')'
2733 /// \endverbatim
2734 ///
2735 void ParseParenDeclarator(Declarator &D);
2736
2737 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
2738 /// declarator D up to a paren, which indicates that we are parsing function
2739 /// arguments.
2740 ///
2741 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
2742 /// immediately after the open paren - they will be applied to the DeclSpec
2743 /// of the first parameter.
2744 ///
2745 /// If RequiresArg is true, then the first argument of the function is
2746 /// required to be present and required to not be an identifier list.
2747 ///
2748 /// For C++, after the parameter-list, it also parses the
2749 /// cv-qualifier-seq[opt], (C++11) ref-qualifier[opt],
2750 /// exception-specification[opt], (C++11) attribute-specifier-seq[opt],
2751 /// (C++11) trailing-return-type[opt] and (C++2a) the trailing
2752 /// requires-clause.
2753 ///
2754 /// \verbatim
2755 /// [C++11] exception-specification:
2756 /// dynamic-exception-specification
2757 /// noexcept-specification
2758 /// \endverbatim
2759 ///
2760 void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
2761 BalancedDelimiterTracker &Tracker,
2762 bool IsAmbiguous, bool RequiresArg = false);
2763 void InitCXXThisScopeForDeclaratorIfRelevant(
2764 const Declarator &D, const DeclSpec &DS,
2765 std::optional<Sema::CXXThisScopeRAII> &ThisScope);
2766
2767 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
2768 /// true if a ref-qualifier is found.
2769 bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2770 SourceLocation &RefQualifierLoc);
2771
2772 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
2773 /// identifier list form for a K&R-style function: void foo(a,b,c)
2774 ///
2775 /// Note that identifier-lists are only allowed for normal declarators, not
2776 /// for abstract-declarators.
2777 bool isFunctionDeclaratorIdentifierList();
2778
2779 /// ParseFunctionDeclaratorIdentifierList - While parsing a function
2780 /// declarator we found a K&R-style identifier list instead of a typed
2781 /// parameter list.
2782 ///
2783 /// After returning, ParamInfo will hold the parsed parameters.
2784 ///
2785 /// \verbatim
2786 /// identifier-list: [C99 6.7.5]
2787 /// identifier
2788 /// identifier-list ',' identifier
2789 /// \endverbatim
2790 ///
2791 void ParseFunctionDeclaratorIdentifierList(
2792 Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2793 void ParseParameterDeclarationClause(
2794 Declarator &D, ParsedAttributes &attrs,
2795 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2796 SourceLocation &EllipsisLoc) {
2797 return ParseParameterDeclarationClause(
2798 D.getContext(), attrs, ParamInfo, EllipsisLoc,
2799 D.getCXXScopeSpec().isSet() &&
2800 D.isFunctionDeclaratorAFunctionDeclaration());
2801 }
2802
2803 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
2804 /// after the opening parenthesis. This function will not parse a K&R-style
2805 /// identifier list.
2806 ///
2807 /// DeclContext is the context of the declarator being parsed. If
2808 /// FirstArgAttrs is non-null, then the caller parsed those attributes
2809 /// immediately after the open paren - they will be applied to the DeclSpec of
2810 /// the first parameter.
2811 ///
2812 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc
2813 /// will be the location of the ellipsis, if any was parsed.
2814 ///
2815 /// \verbatim
2816 /// parameter-type-list: [C99 6.7.5]
2817 /// parameter-list
2818 /// parameter-list ',' '...'
2819 /// [C++] parameter-list '...'
2820 ///
2821 /// parameter-list: [C99 6.7.5]
2822 /// parameter-declaration
2823 /// parameter-list ',' parameter-declaration
2824 ///
2825 /// parameter-declaration: [C99 6.7.5]
2826 /// declaration-specifiers declarator
2827 /// [C++] declaration-specifiers declarator '=' assignment-expression
2828 /// [C++11] initializer-clause
2829 /// [GNU] declaration-specifiers declarator attributes
2830 /// declaration-specifiers abstract-declarator[opt]
2831 /// [C++] declaration-specifiers abstract-declarator[opt]
2832 /// '=' assignment-expression
2833 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
2834 /// [C++11] attribute-specifier-seq parameter-declaration
2835 /// [C++2b] attribute-specifier-seq 'this' parameter-declaration
2836 /// \endverbatim
2837 ///
2838 void ParseParameterDeclarationClause(
2839 DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
2840 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2841 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
2842
2843 /// \verbatim
2844 /// [C90] direct-declarator '[' constant-expression[opt] ']'
2845 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2846 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2847 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2848 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
2849 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
2850 /// attribute-specifier-seq[opt]
2851 /// \endverbatim
2852 void ParseBracketDeclarator(Declarator &D);
2853
2854 /// Diagnose brackets before an identifier.
2855 void ParseMisplacedBracketDeclarator(Declarator &D);
2856
2857 /// Parse the given string as a type.
2858 ///
2859 /// This is a dangerous utility function currently employed only by API notes.
2860 /// It is not a general entry-point for safely parsing types from strings.
2861 ///
2862 /// \param TypeStr The string to be parsed as a type.
2863 /// \param Context The name of the context in which this string is being
2864 /// parsed, which will be used in diagnostics.
2865 /// \param IncludeLoc The location at which this parse was triggered.
2866 TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
2867 SourceLocation IncludeLoc);
2868
2869 ///@}
2870
2871 //
2872 //
2873 // -------------------------------------------------------------------------
2874 //
2875 //
2876
2877 /// \name C++ Declarations
2878 /// Implementations are in ParseDeclCXX.cpp
2879 ///@{
2880
2881private:
2882 /// Contextual keywords for Microsoft extensions.
2883 mutable IdentifierInfo *Ident_sealed;
2884 mutable IdentifierInfo *Ident_abstract;
2885
2886 /// C++11 contextual keywords.
2887 mutable IdentifierInfo *Ident_final;
2888 mutable IdentifierInfo *Ident_GNU_final;
2889 mutable IdentifierInfo *Ident_override;
2890
2891 /// Representation of a class that has been parsed, including
2892 /// any member function declarations or definitions that need to be
2893 /// parsed after the corresponding top-level class is complete.
2894 struct ParsingClass {
2895 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
2896 : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
2897 TagOrTemplate(TagOrTemplate) {}
2898
2899 /// Whether this is a "top-level" class, meaning that it is
2900 /// not nested within another class.
2901 bool TopLevelClass : 1;
2902
2903 /// Whether this class is an __interface.
2904 bool IsInterface : 1;
2905
2906 /// The class or class template whose definition we are parsing.
2907 Decl *TagOrTemplate;
2908
2909 /// LateParsedDeclarations - Method declarations, inline definitions and
2910 /// nested classes that contain pieces whose parsing will be delayed until
2911 /// the top-level class is fully defined.
2912 LateParsedDeclarationsContainer LateParsedDeclarations;
2913 };
2914
2915 /// The stack of classes that is currently being
2916 /// parsed. Nested and local classes will be pushed onto this stack
2917 /// when they are parsed, and removed afterward.
2918 std::stack<ParsingClass *> ClassStack;
2919
2920 ParsingClass &getCurrentClass() {
2921 assert(!ClassStack.empty() && "No lexed method stacks!");
2922 return *ClassStack.top();
2923 }
2924
2925 /// RAII object used to manage the parsing of a class definition.
2926 class ParsingClassDefinition {
2927 Parser &P;
2928 bool Popped;
2930
2931 public:
2932 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
2933 bool IsInterface)
2934 : P(P), Popped(false),
2935 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
2936 }
2937
2938 /// Pop this class of the stack.
2939 void Pop() {
2940 assert(!Popped && "Nested class has already been popped");
2941 Popped = true;
2942 P.PopParsingClass(State);
2943 }
2944
2945 ~ParsingClassDefinition() {
2946 if (!Popped)
2947 P.PopParsingClass(State);
2948 }
2949 };
2950
2951 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
2952 ///
2953 /// \verbatim
2954 /// exception-specification:
2955 /// dynamic-exception-specification
2956 /// noexcept-specification
2957 ///
2958 /// noexcept-specification:
2959 /// 'noexcept'
2960 /// 'noexcept' '(' constant-expression ')'
2961 /// \endverbatim
2962 ExceptionSpecificationType tryParseExceptionSpecification(
2963 bool Delayed, SourceRange &SpecificationRange,
2964 SmallVectorImpl<ParsedType> &DynamicExceptions,
2965 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2966 ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens);
2967
2968 /// ParseDynamicExceptionSpecification - Parse a C++
2969 /// dynamic-exception-specification (C++ [except.spec]).
2970 /// EndLoc is filled with the location of the last token of the specification.
2971 ///
2972 /// \verbatim
2973 /// dynamic-exception-specification:
2974 /// 'throw' '(' type-id-list [opt] ')'
2975 /// [MS] 'throw' '(' '...' ')'
2976 ///
2977 /// type-id-list:
2978 /// type-id ... [opt]
2979 /// type-id-list ',' type-id ... [opt]
2980 /// \endverbatim
2981 ///
2983 ParseDynamicExceptionSpecification(SourceRange &SpecificationRange,
2984 SmallVectorImpl<ParsedType> &Exceptions,
2985 SmallVectorImpl<SourceRange> &Ranges);
2986
2987 //===--------------------------------------------------------------------===//
2988 // C++0x 8: Function declaration trailing-return-type
2989
2990 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2991 /// function declaration.
2992 TypeResult ParseTrailingReturnType(SourceRange &Range,
2993 bool MayBeFollowedByDirectInit);
2994
2995 /// Parse a requires-clause as part of a function declaration.
2996 void ParseTrailingRequiresClauseWithScope(Declarator &D);
2997 void ParseTrailingRequiresClause(Declarator &D);
2998
2999 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3000 ParsedAttributes &AccessAttrs,
3001 AccessSpecifier &CurAS);
3002
3003 SourceLocation ParsePackIndexingType(DeclSpec &DS);
3004 void AnnotateExistingIndexedTypeNamePack(ParsedType T,
3005 SourceLocation StartLoc,
3006 SourceLocation EndLoc);
3007
3008 TemplateNameKind isPackIndexingTemplateName(UnqualifiedId &Name,
3010
3011 bool AnnotatePackIndexingTemplateName(CXXScopeSpec &SS, UnqualifiedId &Name,
3013 TemplateNameKind TNK);
3014
3015 /// Return true if the next token should be treated as a [[]] attribute,
3016 /// or as a keyword that behaves like one. The former is only true if
3017 /// [[]] attributes are enabled, whereas the latter is true whenever
3018 /// such a keyword appears. The arguments are as for
3019 /// isCXX11AttributeSpecifier.
3020 bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
3021 bool OuterMightBeMessageSend = false) {
3022 return (Tok.isRegularKeywordAttribute() ||
3023 isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend) !=
3025 }
3026
3027 /// Skip C++11 and C23 attributes and return the end location of the
3028 /// last one.
3029 /// \returns SourceLocation() if there are no attributes.
3030 SourceLocation SkipCXX11Attributes();
3031
3032 /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
3033 /// locations where attributes are not allowed.
3034 void DiagnoseAndSkipCXX11Attributes();
3035
3036 void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
3037 CachedTokens &OpenMPTokens);
3038
3039 /// Parse a C++11 or C23 attribute-specifier.
3040 ///
3041 /// \verbatim
3042 /// [C++11] attribute-specifier:
3043 /// '[' '[' attribute-list ']' ']'
3044 /// alignment-specifier
3045 ///
3046 /// [C++11] attribute-list:
3047 /// attribute[opt]
3048 /// attribute-list ',' attribute[opt]
3049 /// attribute '...'
3050 /// attribute-list ',' attribute '...'
3051 ///
3052 /// [C++11] attribute:
3053 /// attribute-token attribute-argument-clause[opt]
3054 ///
3055 /// [C++11] attribute-token:
3056 /// identifier
3057 /// attribute-scoped-token
3058 ///
3059 /// [C++11] attribute-scoped-token:
3060 /// attribute-namespace '::' identifier
3061 ///
3062 /// [C++11] attribute-namespace:
3063 /// identifier
3064 /// \endverbatim
3065 void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
3066 CachedTokens &OpenMPTokens,
3067 SourceLocation *EndLoc = nullptr);
3068 void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
3069 SourceLocation *EndLoc = nullptr) {
3070 CachedTokens OpenMPTokens;
3071 ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
3072 ReplayOpenMPAttributeTokens(OpenMPTokens);
3073 }
3074
3075 /// ParseCXX11Attributes - Parse a C++11 or C23 attribute-specifier-seq.
3076 ///
3077 /// \verbatim
3078 /// attribute-specifier-seq:
3079 /// attribute-specifier-seq[opt] attribute-specifier
3080 /// \endverbatim
3081 void ParseCXX11Attributes(ParsedAttributes &attrs);
3082
3083 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3084 /// Parses a C++11 (or C23)-style attribute argument list. Returns true
3085 /// if this results in adding an attribute to the ParsedAttributes list.
3086 ///
3087 /// \verbatim
3088 /// [C++11] attribute-argument-clause:
3089 /// '(' balanced-token-seq ')'
3090 ///
3091 /// [C++11] balanced-token-seq:
3092 /// balanced-token
3093 /// balanced-token-seq balanced-token
3094 ///
3095 /// [C++11] balanced-token:
3096 /// '(' balanced-token-seq ')'
3097 /// '[' balanced-token-seq ']'
3098 /// '{' balanced-token-seq '}'
3099 /// any token but '(', ')', '[', ']', '{', or '}'
3100 /// \endverbatim
3101 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3102 SourceLocation AttrNameLoc,
3103 ParsedAttributes &Attrs, SourceLocation *EndLoc,
3104 IdentifierInfo *ScopeName,
3105 SourceLocation ScopeLoc,
3106 CachedTokens &OpenMPTokens);
3107
3108 /// Parse the argument to C++23's [[assume()]] attribute. Returns true on
3109 /// error.
3110 bool
3111 ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs, IdentifierInfo *AttrName,
3112 SourceLocation AttrNameLoc,
3113 IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3114 SourceLocation *EndLoc, ParsedAttr::Form Form);
3115
3116 /// Try to parse an 'identifier' which appears within an attribute-token.
3117 ///
3118 /// \return the parsed identifier on success, and 0 if the next token is not
3119 /// an attribute-token.
3120 ///
3121 /// C++11 [dcl.attr.grammar]p3:
3122 /// If a keyword or an alternative token that satisfies the syntactic
3123 /// requirements of an identifier is contained in an attribute-token,
3124 /// it is considered an identifier.
3125 IdentifierInfo *TryParseCXX11AttributeIdentifier(
3126 SourceLocation &Loc,
3129 const IdentifierInfo *EnclosingScope = nullptr);
3130
3131 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
3132 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3133
3134 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3135 ///
3136 /// \verbatim
3137 /// [MS] ms-attribute:
3138 /// '[' token-seq ']'
3139 ///
3140 /// [MS] ms-attribute-seq:
3141 /// ms-attribute[opt]
3142 /// ms-attribute ms-attribute-seq
3143 /// \endverbatim
3144 void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3145
3146 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3147 void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3148
3149 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
3150 ///
3151 /// \verbatim
3152 /// 'decltype' ( expression )
3153 /// 'decltype' ( 'auto' ) [C++1y]
3154 /// \endverbatim
3155 ///
3156 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3157 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3158 SourceLocation StartLoc,
3159 SourceLocation EndLoc);
3160
3161 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
3162 /// virt-specifier.
3163 ///
3164 /// \verbatim
3165 /// virt-specifier:
3166 /// override
3167 /// final
3168 /// __final
3169 /// \endverbatim
3170 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3171 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3172 return isCXX11VirtSpecifier(Tok);
3173 }
3174
3175 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
3176 ///
3177 /// \verbatim
3178 /// virt-specifier-seq:
3179 /// virt-specifier
3180 /// virt-specifier-seq virt-specifier
3181 /// \endverbatim
3182 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3183 SourceLocation FriendLoc);
3184
3185 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
3186 /// 'final' or Microsoft 'sealed' contextual keyword.
3187 bool isCXX11FinalKeyword() const;
3188
3189 /// isClassCompatibleKeyword - Determine whether the next token is a C++11
3190 /// 'final', a C++26 'trivially_relocatable_if_eligible',
3191 /// or Microsoft 'sealed' or 'abstract' contextual
3192 /// keyword.
3193 bool isClassCompatibleKeyword() const;
3194
3195 bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3196 DeclSpec::TST TypeTransformTokToDeclSpec();
3197
3198 void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3199
3200 /// ParseNamespace - We know that the current token is a namespace keyword.
3201 /// This may either be a top level namespace or a block-level namespace alias.
3202 /// If there was an inline keyword, it has already been parsed.
3203 ///
3204 /// \verbatim
3205 /// namespace-definition: [C++: namespace.def]
3206 /// named-namespace-definition
3207 /// unnamed-namespace-definition
3208 /// nested-namespace-definition
3209 ///
3210 /// named-namespace-definition:
3211 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
3212 /// namespace-body '}'
3213 ///
3214 /// unnamed-namespace-definition:
3215 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
3216 ///
3217 /// nested-namespace-definition:
3218 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
3219 /// identifier '{' namespace-body '}'
3220 ///
3221 /// enclosing-namespace-specifier:
3222 /// identifier
3223 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
3224 ///
3225 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
3226 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
3227 /// \endverbatim
3228 ///
3229 DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3230 SourceLocation &DeclEnd,
3231 SourceLocation InlineLoc = SourceLocation());
3232
3233 struct InnerNamespaceInfo {
3234 SourceLocation NamespaceLoc;
3235 SourceLocation InlineLoc;
3236 SourceLocation IdentLoc;
3237 IdentifierInfo *Ident;
3238 };
3239 using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3240
3241 /// ParseInnerNamespace - Parse the contents of a namespace.
3242 void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3243 unsigned int index, SourceLocation &InlineLoc,
3244 ParsedAttributes &attrs,
3245 BalancedDelimiterTracker &Tracker);
3246
3247 /// ParseLinkage - We know that the current token is a string_literal
3248 /// and just before that, that extern was seen.
3249 ///
3250 /// \verbatim
3251 /// linkage-specification: [C++ 7.5p2: dcl.link]
3252 /// 'extern' string-literal '{' declaration-seq[opt] '}'
3253 /// 'extern' string-literal declaration
3254 /// \endverbatim
3255 ///
3256 Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3257
3258 /// Parse a standard C++ Modules export-declaration.
3259 ///
3260 /// \verbatim
3261 /// export-declaration:
3262 /// 'export' declaration
3263 /// 'export' '{' declaration-seq[opt] '}'
3264 /// \endverbatim
3265 ///
3266 /// HLSL: Parse export function declaration.
3267 ///
3268 /// \verbatim
3269 /// export-function-declaration:
3270 /// 'export' function-declaration
3271 ///
3272 /// export-declaration-group:
3273 /// 'export' '{' function-declaration-seq[opt] '}'
3274 /// \endverbatim
3275 ///
3276 Decl *ParseExportDeclaration();
3277
3278 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
3279 /// using-directive. Assumes that current token is 'using'.
3280 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3281 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3282 SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3283
3284 /// ParseUsingDirective - Parse C++ using-directive, assumes
3285 /// that current token is 'namespace' and 'using' was already parsed.
3286 ///
3287 /// \verbatim
3288 /// using-directive: [C++ 7.3.p4: namespace.udir]
3289 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3290 /// namespace-name ;
3291 /// [GNU] using-directive:
3292 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
3293 /// namespace-name attributes[opt] ;
3294 /// \endverbatim
3295 ///
3296 Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc,
3297 SourceLocation &DeclEnd, ParsedAttributes &attrs);
3298
3299 struct UsingDeclarator {
3300 SourceLocation TypenameLoc;
3301 CXXScopeSpec SS;
3302 UnqualifiedId Name;
3303 SourceLocation EllipsisLoc;
3304
3305 void clear() {
3306 TypenameLoc = EllipsisLoc = SourceLocation();
3307 SS.clear();
3308 Name.clear();
3309 }
3310 };
3311
3312 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
3313 ///
3314 /// \verbatim
3315 /// using-declarator:
3316 /// 'typename'[opt] nested-name-specifier unqualified-id
3317 /// \endverbatim
3318 ///
3319 bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3320
3321 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
3322 /// Assumes that 'using' was already seen.
3323 ///
3324 /// \verbatim
3325 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
3326 /// 'using' using-declarator-list[opt] ;
3327 ///
3328 /// using-declarator-list: [C++1z]
3329 /// using-declarator '...'[opt]
3330 /// using-declarator-list ',' using-declarator '...'[opt]
3331 ///
3332 /// using-declarator-list: [C++98-14]
3333 /// using-declarator
3334 ///
3335 /// alias-declaration: C++11 [dcl.dcl]p1
3336 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
3337 ///
3338 /// using-enum-declaration: [C++20, dcl.enum]
3339 /// 'using' elaborated-enum-specifier ;
3340 /// The terminal name of the elaborated-enum-specifier undergoes
3341 /// type-only lookup
3342 ///
3343 /// elaborated-enum-specifier:
3344 /// 'enum' nested-name-specifier[opt] identifier
3345 /// \endverbatim
3346 DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3347 const ParsedTemplateInfo &TemplateInfo,
3348 SourceLocation UsingLoc,
3349 SourceLocation &DeclEnd,
3350 ParsedAttributes &Attrs,
3352 Decl *ParseAliasDeclarationAfterDeclarator(
3353 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3354 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3355 ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3356
3357 /// ParseStaticAssertDeclaration - Parse C++0x or C11
3358 /// static_assert-declaration.
3359 ///
3360 /// \verbatim
3361 /// [C++0x] static_assert-declaration:
3362 /// static_assert ( constant-expression , string-literal ) ;
3363 ///
3364 /// [C11] static_assert-declaration:
3365 /// _Static_assert ( constant-expression , string-literal ) ;
3366 /// \endverbatim
3367 ///
3368 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3369
3370 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
3371 /// alias definition.
3372 ///
3373 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3374 SourceLocation AliasLoc, IdentifierInfo *Alias,
3375 SourceLocation &DeclEnd);
3376
3377 //===--------------------------------------------------------------------===//
3378 // C++ 9: classes [class] and C structs/unions.
3379
3380 /// Determine whether the following tokens are valid after a type-specifier
3381 /// which could be a standalone declaration. This will conservatively return
3382 /// true if there's any doubt, and is appropriate for insert-';' fixits.
3383 bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3384
3385 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
3386 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
3387 /// until we reach the start of a definition or see a token that
3388 /// cannot start a definition.
3389 ///
3390 /// \verbatim
3391 /// class-specifier: [C++ class]
3392 /// class-head '{' member-specification[opt] '}'
3393 /// class-head '{' member-specification[opt] '}' attributes[opt]
3394 /// class-head:
3395 /// class-key identifier[opt] base-clause[opt]
3396 /// class-key nested-name-specifier identifier base-clause[opt]
3397 /// class-key nested-name-specifier[opt] simple-template-id
3398 /// base-clause[opt]
3399 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
3400 /// [GNU] class-key attributes[opt] nested-name-specifier
3401 /// identifier base-clause[opt]
3402 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
3403 /// simple-template-id base-clause[opt]
3404 /// class-key:
3405 /// 'class'
3406 /// 'struct'
3407 /// 'union'
3408 ///
3409 /// elaborated-type-specifier: [C++ dcl.type.elab]
3410 /// class-key ::[opt] nested-name-specifier[opt] identifier
3411 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
3412 /// simple-template-id
3413 ///
3414 /// Note that the C++ class-specifier and elaborated-type-specifier,
3415 /// together, subsume the C99 struct-or-union-specifier:
3416 ///
3417 /// struct-or-union-specifier: [C99 6.7.2.1]
3418 /// struct-or-union identifier[opt] '{' struct-contents '}'
3419 /// struct-or-union identifier
3420 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
3421 /// '}' attributes[opt]
3422 /// [GNU] struct-or-union attributes[opt] identifier
3423 /// struct-or-union:
3424 /// 'struct'
3425 /// 'union'
3426 /// \endverbatim
3427 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3428 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3429 AccessSpecifier AS, bool EnteringContext,
3430 DeclSpecContext DSC, ParsedAttributes &Attributes);
3431 void SkipCXXMemberSpecification(SourceLocation StartLoc,
3432 SourceLocation AttrFixitLoc, unsigned TagType,
3433 Decl *TagDecl);
3434
3435 /// ParseCXXMemberSpecification - Parse the class definition.
3436 ///
3437 /// \verbatim
3438 /// member-specification:
3439 /// member-declaration member-specification[opt]
3440 /// access-specifier ':' member-specification[opt]
3441 /// \endverbatim
3442 ///
3443 void ParseCXXMemberSpecification(SourceLocation StartLoc,
3444 SourceLocation AttrFixitLoc,
3445 ParsedAttributes &Attrs, unsigned TagType,
3446 Decl *TagDecl);
3447
3448 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
3449 /// Also detect and reject any attempted defaulted/deleted function
3450 /// definition. The location of the '=', if any, will be placed in EqualLoc.
3451 ///
3452 /// This does not check for a pure-specifier; that's handled elsewhere.
3453 ///
3454 /// \verbatim
3455 /// brace-or-equal-initializer:
3456 /// '=' initializer-expression
3457 /// braced-init-list
3458 ///
3459 /// initializer-clause:
3460 /// assignment-expression
3461 /// braced-init-list
3462 ///
3463 /// defaulted/deleted function-definition:
3464 /// '=' 'default'
3465 /// '=' 'delete'
3466 /// \endverbatim
3467 ///
3468 /// Prior to C++0x, the assignment-expression in an initializer-clause must
3469 /// be a constant-expression.
3470 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3471 SourceLocation &EqualLoc);
3472
3473 /// Parse a C++ member-declarator up to, but not including, the optional
3474 /// brace-or-equal-initializer or pure-specifier.
3475 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3476 VirtSpecifiers &VS,
3477 ExprResult &BitfieldSize,
3478 LateParsedAttrList &LateAttrs);
3479
3480 /// Look for declaration specifiers possibly occurring after C++11
3481 /// virt-specifier-seq and diagnose them.
3482 void
3483 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3484 VirtSpecifiers &VS);
3485
3486 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
3487 ///
3488 /// \verbatim
3489 /// member-declaration:
3490 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
3491 /// function-definition ';'[opt]
3492 /// [C++26] friend-type-declaration
3493 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
3494 /// using-declaration [TODO]
3495 /// [C++0x] static_assert-declaration
3496 /// template-declaration
3497 /// [GNU] '__extension__' member-declaration
3498 ///
3499 /// member-declarator-list:
3500 /// member-declarator
3501 /// member-declarator-list ',' member-declarator
3502 ///
3503 /// member-declarator:
3504 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
3505 /// [C++2a] declarator requires-clause
3506 /// declarator constant-initializer[opt]
3507 /// [C++11] declarator brace-or-equal-initializer[opt]
3508 /// identifier[opt] ':' constant-expression
3509 ///
3510 /// virt-specifier-seq:
3511 /// virt-specifier
3512 /// virt-specifier-seq virt-specifier
3513 ///
3514 /// virt-specifier:
3515 /// override
3516 /// final
3517 /// [MS] sealed
3518 ///
3519 /// pure-specifier:
3520 /// '= 0'
3521 ///
3522 /// constant-initializer:
3523 /// '=' constant-expression
3524 ///
3525 /// friend-type-declaration:
3526 /// 'friend' friend-type-specifier-list ;
3527 ///
3528 /// friend-type-specifier-list:
3529 /// friend-type-specifier ...[opt]
3530 /// friend-type-specifier-list , friend-type-specifier ...[opt]
3531 ///
3532 /// friend-type-specifier:
3533 /// simple-type-specifier
3534 /// elaborated-type-specifier
3535 /// typename-specifier
3536 /// \endverbatim
3537 ///
3538 DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3539 AccessSpecifier AS, ParsedAttributes &Attr,
3540 ParsedTemplateInfo &TemplateInfo,
3541 ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3543 ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3544 ParsedAttributes &AccessAttrs,
3545 DeclSpec::TST TagType, Decl *Tag);
3546
3547 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3548 /// which explicitly initializes the members or base classes of a
3549 /// class (C++ [class.base.init]). For example, the three initializers
3550 /// after the ':' in the Derived constructor below:
3551 ///
3552 /// @code
3553 /// class Base { };
3554 /// class Derived : Base {
3555 /// int x;
3556 /// float f;
3557 /// public:
3558 /// Derived(float f) : Base(), x(17), f(f) { }
3559 /// };
3560 /// @endcode
3561 ///
3562 /// \verbatim
3563 /// [C++] ctor-initializer:
3564 /// ':' mem-initializer-list
3565 ///
3566 /// [C++] mem-initializer-list:
3567 /// mem-initializer ...[opt]
3568 /// mem-initializer ...[opt] , mem-initializer-list
3569 /// \endverbatim
3570 void ParseConstructorInitializer(Decl *ConstructorDecl);
3571
3572 /// ParseMemInitializer - Parse a C++ member initializer, which is
3573 /// part of a constructor initializer that explicitly initializes one
3574 /// member or base class (C++ [class.base.init]). See
3575 /// ParseConstructorInitializer for an example.
3576 ///
3577 /// \verbatim
3578 /// [C++] mem-initializer:
3579 /// mem-initializer-id '(' expression-list[opt] ')'
3580 /// [C++0x] mem-initializer-id braced-init-list
3581 ///
3582 /// [C++] mem-initializer-id:
3583 /// '::'[opt] nested-name-specifier[opt] class-name
3584 /// identifier
3585 /// \endverbatim
3586 MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3587
3588 /// If the given declarator has any parts for which parsing has to be
3589 /// delayed, e.g., default arguments or an exception-specification, create a
3590 /// late-parsed method declaration record to handle the parsing at the end of
3591 /// the class definition.
3592 void HandleMemberFunctionDeclDelays(Declarator &DeclaratorInfo,
3593 Decl *ThisDecl);
3594
3595 //===--------------------------------------------------------------------===//
3596 // C++ 10: Derived classes [class.derived]
3597
3598 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
3599 /// class name or decltype-specifier. Note that we only check that the result
3600 /// names a type; semantic analysis will need to verify that the type names a
3601 /// class. The result is either a type or null, depending on whether a type
3602 /// name was found.
3603 ///
3604 /// \verbatim
3605 /// base-type-specifier: [C++11 class.derived]
3606 /// class-or-decltype
3607 /// class-or-decltype: [C++11 class.derived]
3608 /// nested-name-specifier[opt] class-name
3609 /// decltype-specifier
3610 /// class-name: [C++ class.name]
3611 /// identifier
3612 /// simple-template-id
3613 /// \endverbatim
3614 ///
3615 /// In C++98, instead of base-type-specifier, we have:
3616 ///
3617 /// \verbatim
3618 /// ::[opt] nested-name-specifier[opt] class-name
3619 /// \endverbatim
3620 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3621 SourceLocation &EndLocation);
3622
3623 /// ParseBaseClause - Parse the base-clause of a C++ class [C++
3624 /// class.derived].
3625 ///
3626 /// \verbatim
3627 /// base-clause : [C++ class.derived]
3628 /// ':' base-specifier-list
3629 /// base-specifier-list:
3630 /// base-specifier '...'[opt]
3631 /// base-specifier-list ',' base-specifier '...'[opt]
3632 /// \endverbatim
3633 void ParseBaseClause(Decl *ClassDecl);
3634
3635 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
3636 /// one entry in the base class list of a class specifier, for example:
3637 /// class foo : public bar, virtual private baz {
3638 /// 'public bar' and 'virtual private baz' are each base-specifiers.
3639 ///
3640 /// \verbatim
3641 /// base-specifier: [C++ class.derived]
3642 /// attribute-specifier-seq[opt] base-type-specifier
3643 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
3644 /// base-type-specifier
3645 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
3646 /// base-type-specifier
3647 /// \endverbatim
3648 BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3649
3650 /// getAccessSpecifierIfPresent - Determine whether the next token is
3651 /// a C++ access-specifier.
3652 ///
3653 /// \verbatim
3654 /// access-specifier: [C++ class.derived]
3655 /// 'private'
3656 /// 'protected'
3657 /// 'public'
3658 /// \endverbatim
3659 AccessSpecifier getAccessSpecifierIfPresent() const;
3660
3661 /// 'final', a C++26 'trivially_relocatable_if_eligible',
3662 /// or Microsoft 'sealed' or 'abstract' contextual
3663 /// keyword.
3664 bool isClassCompatibleKeyword(Token Tok) const;
3665
3666 void ParseHLSLRootSignatureAttributeArgs(ParsedAttributes &Attrs);
3667
3668 ///@}
3669
3670 //
3671 //
3672 // -------------------------------------------------------------------------
3673 //
3674 //
3675
3676 /// \name Expressions
3677 /// Implementations are in ParseExpr.cpp
3678 ///@{
3679
3680public:
3682
3684
3685 //===--------------------------------------------------------------------===//
3686 // C99 6.5: Expressions.
3687
3688 /// Simple precedence-based parser for binary/ternary operators.
3689 ///
3690 /// Note: we diverge from the C99 grammar when parsing the
3691 /// assignment-expression production. C99 specifies that the LHS of an
3692 /// assignment operator should be parsed as a unary-expression, but
3693 /// consistency dictates that it be a conditional-expession. In practice, the
3694 /// important thing here is that the LHS of an assignment has to be an
3695 /// l-value, which productions between unary-expression and
3696 /// conditional-expression don't produce. Because we want consistency, we
3697 /// parse the LHS as a conditional-expression, then check for l-value-ness in
3698 /// semantic analysis stages.
3699 ///
3700 /// \verbatim
3701 /// pm-expression: [C++ 5.5]
3702 /// cast-expression
3703 /// pm-expression '.*' cast-expression
3704 /// pm-expression '->*' cast-expression
3705 ///
3706 /// multiplicative-expression: [C99 6.5.5]
3707 /// Note: in C++, apply pm-expression instead of cast-expression
3708 /// cast-expression
3709 /// multiplicative-expression '*' cast-expression
3710 /// multiplicative-expression '/' cast-expression
3711 /// multiplicative-expression '%' cast-expression
3712 ///
3713 /// additive-expression: [C99 6.5.6]
3714 /// multiplicative-expression
3715 /// additive-expression '+' multiplicative-expression
3716 /// additive-expression '-' multiplicative-expression
3717 ///
3718 /// shift-expression: [C99 6.5.7]
3719 /// additive-expression
3720 /// shift-expression '<<' additive-expression
3721 /// shift-expression '>>' additive-expression
3722 ///
3723 /// compare-expression: [C++20 expr.spaceship]
3724 /// shift-expression
3725 /// compare-expression '<=>' shift-expression
3726 ///
3727 /// relational-expression: [C99 6.5.8]
3728 /// compare-expression
3729 /// relational-expression '<' compare-expression
3730 /// relational-expression '>' compare-expression
3731 /// relational-expression '<=' compare-expression
3732 /// relational-expression '>=' compare-expression
3733 ///
3734 /// equality-expression: [C99 6.5.9]
3735 /// relational-expression
3736 /// equality-expression '==' relational-expression
3737 /// equality-expression '!=' relational-expression
3738 ///
3739 /// AND-expression: [C99 6.5.10]
3740 /// equality-expression
3741 /// AND-expression '&' equality-expression
3742 ///
3743 /// exclusive-OR-expression: [C99 6.5.11]
3744 /// AND-expression
3745 /// exclusive-OR-expression '^' AND-expression
3746 ///
3747 /// inclusive-OR-expression: [C99 6.5.12]
3748 /// exclusive-OR-expression
3749 /// inclusive-OR-expression '|' exclusive-OR-expression
3750 ///
3751 /// logical-AND-expression: [C99 6.5.13]
3752 /// inclusive-OR-expression
3753 /// logical-AND-expression '&&' inclusive-OR-expression
3754 ///
3755 /// logical-OR-expression: [C99 6.5.14]
3756 /// logical-AND-expression
3757 /// logical-OR-expression '||' logical-AND-expression
3758 ///
3759 /// conditional-expression: [C99 6.5.15]
3760 /// logical-OR-expression
3761 /// logical-OR-expression '?' expression ':' conditional-expression
3762 /// [GNU] logical-OR-expression '?' ':' conditional-expression
3763 /// [C++] the third operand is an assignment-expression
3764 ///
3765 /// assignment-expression: [C99 6.5.16]
3766 /// conditional-expression
3767 /// unary-expression assignment-operator assignment-expression
3768 /// [C++] throw-expression [C++ 15]
3769 ///
3770 /// assignment-operator: one of
3771 /// = *= /= %= += -= <<= >>= &= ^= |=
3772 ///
3773 /// expression: [C99 6.5.17]
3774 /// assignment-expression ...[opt]
3775 /// expression ',' assignment-expression ...[opt]
3776 /// \endverbatim
3779
3781 TypoCorrectionTypeBehavior CorrectionBehavior =
3786
3787 /// Parse a constraint-expression.
3788 ///
3789 /// \verbatim
3790 /// constraint-expression: C++2a[temp.constr.decl]p1
3791 /// logical-or-expression
3792 /// \endverbatim
3794
3795 /// \brief Parse a constraint-logical-and-expression.
3796 ///
3797 /// \verbatim
3798 /// C++2a[temp.constr.decl]p1
3799 /// constraint-logical-and-expression:
3800 /// primary-expression
3801 /// constraint-logical-and-expression '&&' primary-expression
3802 ///
3803 /// \endverbatim
3804 ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
3805
3806 /// \brief Parse a constraint-logical-or-expression.
3807 ///
3808 /// \verbatim
3809 /// C++2a[temp.constr.decl]p1
3810 /// constraint-logical-or-expression:
3811 /// constraint-logical-and-expression
3812 /// constraint-logical-or-expression '||'
3813 /// constraint-logical-and-expression
3814 ///
3815 /// \endverbatim
3816 ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
3817
3818 /// Parse an expr that doesn't include (top-level) commas.
3822
3824
3825 /// ParseStringLiteralExpression - This handles the various token types that
3826 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3827 /// translation phase #6].
3828 ///
3829 /// \verbatim
3830 /// primary-expression: [C99 6.5.1]
3831 /// string-literal
3832 /// \endverbatim
3833 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
3835
3836private:
3837 /// Whether the '>' token acts as an operator or not. This will be
3838 /// true except when we are parsing an expression within a C++
3839 /// template argument list, where the '>' closes the template
3840 /// argument list.
3841 bool GreaterThanIsOperator;
3842
3843 // C++ type trait keywords that can be reverted to identifiers and still be
3844 // used as type traits.
3845 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
3846
3847 OffsetOfKind OffsetOfState = OffsetOfKind::Outside;
3848
3849 /// The location of the expression statement that is being parsed right now.
3850 /// Used to determine if an expression that is being parsed is a statement or
3851 /// just a regular sub-expression.
3852 SourceLocation ExprStatementTokLoc;
3853
3854 /// Checks if the \p Level is valid for use in a fold expression.
3855 bool isFoldOperator(prec::Level Level) const;
3856
3857 /// Checks if the \p Kind is a valid operator for fold expressions.
3858 bool isFoldOperator(tok::TokenKind Kind) const;
3859
3860 /// We have just started parsing the definition of a new class,
3861 /// so push that class onto our stack of classes that is currently
3862 /// being parsed.
3864 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
3865
3866 /// Deallocate the given parsed class and all of its nested
3867 /// classes.
3868 void DeallocateParsedClasses(ParsingClass *Class);
3869
3870 /// Pop the top class of the stack of classes that are
3871 /// currently being parsed.
3872 ///
3873 /// This routine should be called when we have finished parsing the
3874 /// definition of a class, but have not yet popped the Scope
3875 /// associated with the class's definition.
3876 void PopParsingClass(Sema::ParsingClassState);
3877
3878 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
3879 bool Unevaluated);
3880
3881 /// This routine is called when the '@' is seen and consumed.
3882 /// Current token is an Identifier and is not a 'try'. This
3883 /// routine is necessary to disambiguate \@try-statement from,
3884 /// for example, \@encode-expression.
3885 ///
3886 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
3887
3888 /// This routine is called when a leading '__extension__' is seen and
3889 /// consumed. This is necessary because the token gets consumed in the
3890 /// process of disambiguating between an expression and a declaration.
3891 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
3892
3893 /// Parse a binary expression that starts with \p LHS and has a
3894 /// precedence of at least \p MinPrec.
3895 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec);
3896
3897 bool isRevertibleTypeTrait(const IdentifierInfo *Id,
3898 clang::tok::TokenKind *Kind = nullptr);
3899
3900 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
3901 /// a unary-expression.
3902 ///
3903 /// \p isAddressOfOperand exists because an id-expression that is the operand
3904 /// of address-of gets special treatment due to member pointers. NotCastExpr
3905 /// is set to true if the token is not the start of a cast-expression, and no
3906 /// diagnostic is emitted in this case and no tokens are consumed.
3907 /// In addition, isAddressOfOperand is propagated to SemaCodeCompletion
3908 /// as a heuristic for function completions (to provide different behavior
3909 /// when the user is likely taking the address of a function vs. calling it).
3910 ///
3911 /// \verbatim
3912 /// cast-expression: [C99 6.5.4]
3913 /// unary-expression
3914 /// '(' type-name ')' cast-expression
3915 ///
3916 /// unary-expression: [C99 6.5.3]
3917 /// postfix-expression
3918 /// '++' unary-expression
3919 /// '--' unary-expression
3920 /// [Coro] 'co_await' cast-expression
3921 /// unary-operator cast-expression
3922 /// 'sizeof' unary-expression
3923 /// 'sizeof' '(' type-name ')'
3924 /// [C++11] 'sizeof' '...' '(' identifier ')'
3925 /// [GNU] '__alignof' unary-expression
3926 /// [GNU] '__alignof' '(' type-name ')'
3927 /// [C11] '_Alignof' '(' type-name ')'
3928 /// [C++11] 'alignof' '(' type-id ')'
3929 /// [C2y] '_Countof' unary-expression
3930 /// [C2y] '_Countof' '(' type-name ')'
3931 /// [GNU] '&&' identifier
3932 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
3933 /// [C++] new-expression
3934 /// [C++] delete-expression
3935 ///
3936 /// unary-operator: one of
3937 /// '&' '*' '+' '-' '~' '!'
3938 /// [GNU] '__extension__' '__real' '__imag'
3939 ///
3940 /// primary-expression: [C99 6.5.1]
3941 /// [C99] identifier
3942 /// [C++] id-expression
3943 /// constant
3944 /// string-literal
3945 /// [C++] boolean-literal [C++ 2.13.5]
3946 /// [C++11] 'nullptr' [C++11 2.14.7]
3947 /// [C++11] user-defined-literal
3948 /// '(' expression ')'
3949 /// [C11] generic-selection
3950 /// [C++2a] requires-expression
3951 /// '__func__' [C99 6.4.2.2]
3952 /// [GNU] '__FUNCTION__'
3953 /// [MS] '__FUNCDNAME__'
3954 /// [MS] 'L__FUNCTION__'
3955 /// [MS] '__FUNCSIG__'
3956 /// [MS] 'L__FUNCSIG__'
3957 /// [GNU] '__PRETTY_FUNCTION__'
3958 /// [GNU] '(' compound-statement ')'
3959 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
3960 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
3961 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
3962 /// assign-expr ')'
3963 /// [GNU] '__builtin_FILE' '(' ')'
3964 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
3965 /// [GNU] '__builtin_FUNCTION' '(' ')'
3966 /// [MS] '__builtin_FUNCSIG' '(' ')'
3967 /// [GNU] '__builtin_LINE' '(' ')'
3968 /// [CLANG] '__builtin_COLUMN' '(' ')'
3969 /// [GNU] '__builtin_source_location' '(' ')'
3970 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
3971 /// [GNU] '__null'
3972 /// [OBJC] '[' objc-message-expr ']'
3973 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
3974 /// [OBJC] '\@protocol' '(' identifier ')'
3975 /// [OBJC] '\@encode' '(' type-name ')'
3976 /// [OBJC] objc-string-literal
3977 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
3978 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
3979 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
3980 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
3981 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3982 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3983 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3984 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
3985 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
3986 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
3987 /// [C++] 'this' [C++ 9.3.2]
3988 /// [G++] unary-type-trait '(' type-id ')'
3989 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
3990 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
3991 /// [clang] '^' block-literal
3992 ///
3993 /// constant: [C99 6.4.4]
3994 /// integer-constant
3995 /// floating-constant
3996 /// enumeration-constant -> identifier
3997 /// character-constant
3998 ///
3999 /// id-expression: [C++ 5.1]
4000 /// unqualified-id
4001 /// qualified-id
4002 ///
4003 /// unqualified-id: [C++ 5.1]
4004 /// identifier
4005 /// operator-function-id
4006 /// conversion-function-id
4007 /// '~' class-name
4008 /// template-id
4009 ///
4010 /// new-expression: [C++ 5.3.4]
4011 /// '::'[opt] 'new' new-placement[opt] new-type-id
4012 /// new-initializer[opt]
4013 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4014 /// new-initializer[opt]
4015 ///
4016 /// delete-expression: [C++ 5.3.5]
4017 /// '::'[opt] 'delete' cast-expression
4018 /// '::'[opt] 'delete' '[' ']' cast-expression
4019 ///
4020 /// [GNU/Embarcadero] unary-type-trait:
4021 /// '__is_arithmetic'
4022 /// '__is_floating_point'
4023 /// '__is_integral'
4024 /// '__is_lvalue_expr'
4025 /// '__is_rvalue_expr'
4026 /// '__is_complete_type'
4027 /// '__is_void'
4028 /// '__is_array'
4029 /// '__is_function'
4030 /// '__is_reference'
4031 /// '__is_lvalue_reference'
4032 /// '__is_rvalue_reference'
4033 /// '__is_fundamental'
4034 /// '__is_object'
4035 /// '__is_scalar'
4036 /// '__is_compound'
4037 /// '__is_pointer'
4038 /// '__is_member_object_pointer'
4039 /// '__is_member_function_pointer'
4040 /// '__is_member_pointer'
4041 /// '__is_const'
4042 /// '__is_volatile'
4043 /// '__is_trivial'
4044 /// '__is_standard_layout'
4045 /// '__is_signed'
4046 /// '__is_unsigned'
4047 ///
4048 /// [GNU] unary-type-trait:
4049 /// '__has_nothrow_assign'
4050 /// '__has_nothrow_copy'
4051 /// '__has_nothrow_constructor'
4052 /// '__has_trivial_assign' [TODO]
4053 /// '__has_trivial_copy' [TODO]
4054 /// '__has_trivial_constructor'
4055 /// '__has_trivial_destructor'
4056 /// '__has_virtual_destructor'
4057 /// '__is_abstract' [TODO]
4058 /// '__is_class'
4059 /// '__is_empty' [TODO]
4060 /// '__is_enum'
4061 /// '__is_final'
4062 /// '__is_pod'
4063 /// '__is_polymorphic'
4064 /// '__is_sealed' [MS]
4065 /// '__is_trivial'
4066 /// '__is_union'
4067 /// '__has_unique_object_representations'
4068 ///
4069 /// [Clang] unary-type-trait:
4070 /// '__is_aggregate'
4071 /// '__trivially_copyable'
4072 ///
4073 /// binary-type-trait:
4074 /// [GNU] '__is_base_of'
4075 /// [MS] '__is_convertible_to'
4076 /// '__is_convertible'
4077 /// '__is_same'
4078 ///
4079 /// [Embarcadero] array-type-trait:
4080 /// '__array_rank'
4081 /// '__array_extent'
4082 ///
4083 /// [Embarcadero] expression-trait:
4084 /// '__is_lvalue_expr'
4085 /// '__is_rvalue_expr'
4086 /// \endverbatim
4087 ///
4088 ExprResult ParseCastExpression(CastParseKind ParseKind,
4089 bool isAddressOfOperand, bool &NotCastExpr,
4090 TypoCorrectionTypeBehavior CorrectionBehavior,
4091 bool isVectorLiteral = false,
4092 bool *NotPrimaryExpression = nullptr);
4093 ExprResult ParseCastExpression(CastParseKind ParseKind,
4094 bool isAddressOfOperand = false,
4095 TypoCorrectionTypeBehavior CorrectionBehavior =
4097 bool isVectorLiteral = false,
4098 bool *NotPrimaryExpression = nullptr);
4099
4100 /// Returns true if the next token cannot start an expression.
4101 bool isNotExpressionStart();
4102
4103 /// Returns true if the next token would start a postfix-expression
4104 /// suffix.
4105 bool isPostfixExpressionSuffixStart() {
4106 tok::TokenKind K = Tok.getKind();
4107 return (K == tok::l_square || K == tok::l_paren || K == tok::period ||
4108 K == tok::arrow || K == tok::plusplus || K == tok::minusminus);
4109 }
4110
4111 /// Once the leading part of a postfix-expression is parsed, this
4112 /// method parses any suffixes that apply.
4113 ///
4114 /// \verbatim
4115 /// postfix-expression: [C99 6.5.2]
4116 /// primary-expression
4117 /// postfix-expression '[' expression ']'
4118 /// postfix-expression '[' braced-init-list ']'
4119 /// postfix-expression '[' expression-list [opt] ']' [C++23 12.4.5]
4120 /// postfix-expression '(' argument-expression-list[opt] ')'
4121 /// postfix-expression '.' identifier
4122 /// postfix-expression '->' identifier
4123 /// postfix-expression '++'
4124 /// postfix-expression '--'
4125 /// '(' type-name ')' '{' initializer-list '}'
4126 /// '(' type-name ')' '{' initializer-list ',' '}'
4127 ///
4128 /// argument-expression-list: [C99 6.5.2]
4129 /// argument-expression ...[opt]
4130 /// argument-expression-list ',' assignment-expression ...[opt]
4131 /// \endverbatim
4132 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
4133
4134 /// Parse a sizeof or alignof expression.
4135 ///
4136 /// \verbatim
4137 /// unary-expression: [C99 6.5.3]
4138 /// 'sizeof' unary-expression
4139 /// 'sizeof' '(' type-name ')'
4140 /// [C++11] 'sizeof' '...' '(' identifier ')'
4141 /// [Clang] '__datasizeof' unary-expression
4142 /// [Clang] '__datasizeof' '(' type-name ')'
4143 /// [GNU] '__alignof' unary-expression
4144 /// [GNU] '__alignof' '(' type-name ')'
4145 /// [C11] '_Alignof' '(' type-name ')'
4146 /// [C++11] 'alignof' '(' type-id ')'
4147 /// [C2y] '_Countof' unary-expression
4148 /// [C2y] '_Countof' '(' type-name ')'
4149 /// \endverbatim
4150 ExprResult ParseUnaryExprOrTypeTraitExpression();
4151
4152 /// ParseBuiltinPrimaryExpression
4153 ///
4154 /// \verbatim
4155 /// primary-expression: [C99 6.5.1]
4156 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
4157 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
4158 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
4159 /// assign-expr ')'
4160 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
4161 /// [GNU] '__builtin_FILE' '(' ')'
4162 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
4163 /// [GNU] '__builtin_FUNCTION' '(' ')'
4164 /// [MS] '__builtin_FUNCSIG' '(' ')'
4165 /// [GNU] '__builtin_LINE' '(' ')'
4166 /// [CLANG] '__builtin_COLUMN' '(' ')'
4167 /// [GNU] '__builtin_source_location' '(' ')'
4168 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
4169 ///
4170 /// [GNU] offsetof-member-designator:
4171 /// [GNU] identifier
4172 /// [GNU] offsetof-member-designator '.' identifier
4173 /// [GNU] offsetof-member-designator '[' expression ']'
4174 /// \endverbatim
4175 ExprResult ParseBuiltinPrimaryExpression();
4176
4177 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id
4178 /// as a parameter.
4179 ExprResult ParseSYCLUniqueStableNameExpression();
4180
4181 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
4182 /// vec_step and we are at the start of an expression or a parenthesized
4183 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
4184 /// expression (isCastExpr == false) or the type (isCastExpr == true).
4185 ///
4186 /// \verbatim
4187 /// unary-expression: [C99 6.5.3]
4188 /// 'sizeof' unary-expression
4189 /// 'sizeof' '(' type-name ')'
4190 /// [Clang] '__datasizeof' unary-expression
4191 /// [Clang] '__datasizeof' '(' type-name ')'
4192 /// [GNU] '__alignof' unary-expression
4193 /// [GNU] '__alignof' '(' type-name ')'
4194 /// [C11] '_Alignof' '(' type-name ')'
4195 /// [C++0x] 'alignof' '(' type-id ')'
4196 ///
4197 /// [GNU] typeof-specifier:
4198 /// typeof ( expressions )
4199 /// typeof ( type-name )
4200 /// [GNU/C++] typeof unary-expression
4201 /// [C23] typeof-specifier:
4202 /// typeof '(' typeof-specifier-argument ')'
4203 /// typeof_unqual '(' typeof-specifier-argument ')'
4204 ///
4205 /// typeof-specifier-argument:
4206 /// expression
4207 /// type-name
4208 ///
4209 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
4210 /// vec_step ( expressions )
4211 /// vec_step ( type-name )
4212 /// \endverbatim
4213 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
4214 bool &isCastExpr,
4215 ParsedType &CastTy,
4216 SourceRange &CastRange);
4217
4218 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
4219 ///
4220 /// \verbatim
4221 /// argument-expression-list:
4222 /// assignment-expression
4223 /// argument-expression-list , assignment-expression
4224 ///
4225 /// [C++] expression-list:
4226 /// [C++] assignment-expression
4227 /// [C++] expression-list , assignment-expression
4228 ///
4229 /// [C++0x] expression-list:
4230 /// [C++0x] initializer-list
4231 ///
4232 /// [C++0x] initializer-list
4233 /// [C++0x] initializer-clause ...[opt]
4234 /// [C++0x] initializer-list , initializer-clause ...[opt]
4235 ///
4236 /// [C++0x] initializer-clause:
4237 /// [C++0x] assignment-expression
4238 /// [C++0x] braced-init-list
4239 /// \endverbatim
4240 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
4241 llvm::function_ref<void()> ExpressionStarts =
4242 llvm::function_ref<void()>(),
4243 bool FailImmediatelyOnInvalidExpr = false,
4244 bool ParsingExpansionStmtInitList = false);
4245
4246 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
4247 /// used for misc language extensions.
4248 ///
4249 /// \verbatim
4250 /// simple-expression-list:
4251 /// assignment-expression
4252 /// simple-expression-list , assignment-expression
4253 /// \endverbatim
4254 bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
4255
4256 /// This parses the unit that starts with a '(' token, based on what is
4257 /// allowed by ExprType. The actual thing parsed is returned in ExprType. If
4258 /// StopIfCastExpr is true, it will only return the parsed type, not the
4259 /// parsed cast-expression. If ParenBehavior is ParenExprKind::PartOfOperator,
4260 /// the initial open paren and its matching close paren are known to be part
4261 /// of another grammar production and not part of the operand. e.g., the
4262 /// typeof and typeof_unqual operators in C. Otherwise, the function has to
4263 /// parse the parens to determine whether they're part of a cast or compound
4264 /// literal expression rather than a parenthesized type.
4265 ///
4266 /// \verbatim
4267 /// primary-expression: [C99 6.5.1]
4268 /// '(' expression ')'
4269 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
4270 /// postfix-expression: [C99 6.5.2]
4271 /// '(' type-name ')' '{' initializer-list '}'
4272 /// '(' type-name ')' '{' initializer-list ',' '}'
4273 /// cast-expression: [C99 6.5.4]
4274 /// '(' type-name ')' cast-expression
4275 /// [ARC] bridged-cast-expression
4276 /// [ARC] bridged-cast-expression:
4277 /// (__bridge type-name) cast-expression
4278 /// (__bridge_transfer type-name) cast-expression
4279 /// (__bridge_retained type-name) cast-expression
4280 /// fold-expression: [C++1z]
4281 /// '(' cast-expression fold-operator '...' ')'
4282 /// '(' '...' fold-operator cast-expression ')'
4283 /// '(' cast-expression fold-operator '...'
4284 /// fold-operator cast-expression ')'
4285 /// [OPENMP] Array shaping operation
4286 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
4287 /// \endverbatim
4288 ExprResult ParseParenExpression(ParenParseOption &ExprType,
4289 bool StopIfCastExpr,
4290 ParenExprKind ParenBehavior,
4291 TypoCorrectionTypeBehavior CorrectionBehavior,
4292 ParsedType &CastTy,
4293 SourceLocation &RParenLoc);
4294
4295 /// ParseCompoundLiteralExpression - We have parsed the parenthesized
4296 /// type-name and we are at the left brace.
4297 ///
4298 /// \verbatim
4299 /// postfix-expression: [C99 6.5.2]
4300 /// '(' type-name ')' '{' initializer-list '}'
4301 /// '(' type-name ')' '{' initializer-list ',' '}'
4302 /// \endverbatim
4303 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
4304 SourceLocation LParenLoc,
4305 SourceLocation RParenLoc);
4306
4307 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
4308 /// [C11 6.5.1.1].
4309 ///
4310 /// \verbatim
4311 /// generic-selection:
4312 /// _Generic ( assignment-expression , generic-assoc-list )
4313 /// generic-assoc-list:
4314 /// generic-association
4315 /// generic-assoc-list , generic-association
4316 /// generic-association:
4317 /// type-name : assignment-expression
4318 /// default : assignment-expression
4319 /// \endverbatim
4320 ///
4321 /// As an extension, Clang also accepts:
4322 /// \verbatim
4323 /// generic-selection:
4324 /// _Generic ( type-name, generic-assoc-list )
4325 /// \endverbatim
4326 ExprResult ParseGenericSelectionExpression();
4327
4328 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
4329 ///
4330 /// '__objc_yes'
4331 /// '__objc_no'
4332 ExprResult ParseObjCBoolLiteral();
4333
4334 /// Parse A C++1z fold-expression after the opening paren and optional
4335 /// left-hand-side expression.
4336 ///
4337 /// \verbatim
4338 /// fold-expression:
4339 /// ( cast-expression fold-operator ... )
4340 /// ( ... fold-operator cast-expression )
4341 /// ( cast-expression fold-operator ... fold-operator cast-expression )
4342 /// \endverbatim
4343 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
4344
4345 void injectEmbedTokens();
4346
4347 //===--------------------------------------------------------------------===//
4348 // clang Expressions
4349
4350 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
4351 /// like ^(int x){ return x+1; }
4352 ///
4353 /// \verbatim
4354 /// block-literal:
4355 /// [clang] '^' block-args[opt] compound-statement
4356 /// [clang] '^' block-id compound-statement
4357 /// [clang] block-args:
4358 /// [clang] '(' parameter-list ')'
4359 /// \endverbatim
4360 ExprResult ParseBlockLiteralExpression(); // ^{...}
4361
4362 /// Parse an assignment expression where part of an Objective-C message
4363 /// send has already been parsed.
4364 ///
4365 /// In this case \p LBracLoc indicates the location of the '[' of the message
4366 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
4367 /// the receiver of the message.
4368 ///
4369 /// Since this handles full assignment-expression's, it handles postfix
4370 /// expressions and other binary operators for these expressions as well.
4371 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
4372 SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType,
4373 Expr *ReceiverExpr);
4374
4375 /// Return true if we know that we are definitely looking at a
4376 /// decl-specifier, and isn't part of an expression such as a function-style
4377 /// cast. Return false if it's no a decl-specifier, or we're not sure.
4378 bool isKnownToBeDeclarationSpecifier() {
4379 if (getLangOpts().CPlusPlus)
4380 return isCXXDeclarationSpecifier(ImplicitTypenameContext::No) ==
4381 TPResult::True;
4382 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
4383 }
4384
4385 /// Checks whether the current tokens form a type-id or an expression for the
4386 /// purposes of use as the initial operand to a generic selection expression.
4387 /// This requires special handling in C++ because it accepts either a type or
4388 /// an expression, and we need to disambiguate which is which. However, we
4389 /// cannot use the same logic as we've used for sizeof expressions, because
4390 /// that logic relies on the operator only accepting a single argument,
4391 /// whereas _Generic accepts a list of arguments.
4392 bool isTypeIdForGenericSelection() {
4393 if (getLangOpts().CPlusPlus) {
4394 bool isAmbiguous;
4396 isAmbiguous);
4397 }
4398 return isTypeSpecifierQualifier(Tok);
4399 }
4400
4401 /// Checks if the current tokens form type-id or expression.
4402 /// It is similar to isTypeIdInParens but does not suppose that type-id
4403 /// is in parenthesis.
4404 bool isTypeIdUnambiguously() {
4405 if (getLangOpts().CPlusPlus) {
4406 bool isAmbiguous;
4407 return isCXXTypeId(TentativeCXXTypeIdContext::Unambiguous, isAmbiguous);
4408 }
4409 return isTypeSpecifierQualifier(Tok);
4410 }
4411
4412 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
4413 ///
4414 /// \verbatim
4415 /// [clang] block-id:
4416 /// [clang] specifier-qualifier-list block-declarator
4417 /// \endverbatim
4418 void ParseBlockId(SourceLocation CaretLoc);
4419
4420 /// Parse availability query specification.
4421 ///
4422 /// \verbatim
4423 /// availability-spec:
4424 /// '*'
4425 /// identifier version-tuple
4426 /// \endverbatim
4427 std::optional<AvailabilitySpec> ParseAvailabilitySpec();
4428 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
4429
4430 /// Tries to parse cast part of OpenMP array shaping operation:
4431 /// \verbatim
4432 /// '[' expression ']' { '[' expression ']' } ')'
4433 /// \endverbatim
4434 bool tryParseOpenMPArrayShapingCastPart();
4435
4436 ExprResult ParseBuiltinPtrauthTypeDiscriminator();
4437
4438 ///@}
4439
4440 //
4441 //
4442 // -------------------------------------------------------------------------
4443 //
4444 //
4445
4446 /// \name C++ Expressions
4447 /// Implementations are in ParseExprCXX.cpp
4448 ///@{
4449
4450public:
4451 /// Parse a C++ unqualified-id (or a C identifier), which describes the
4452 /// name of an entity.
4453 ///
4454 /// \verbatim
4455 /// unqualified-id: [C++ expr.prim.general]
4456 /// identifier
4457 /// operator-function-id
4458 /// conversion-function-id
4459 /// [C++0x] literal-operator-id [TODO]
4460 /// ~ class-name
4461 /// template-id
4462 /// \endverbatim
4463 ///
4464 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
4465 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
4466 ///
4467 /// \param ObjectType if this unqualified-id occurs within a member access
4468 /// expression, the type of the base object whose member is being accessed.
4469 ///
4470 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4471 /// access expression, indicates whether the original subexpressions had any
4472 /// errors. When true, diagnostics for missing 'template' keyword will be
4473 /// supressed.
4474 ///
4475 /// \param EnteringContext whether we are entering the scope of the
4476 /// nested-name-specifier.
4477 ///
4478 /// \param AllowDestructorName whether we allow parsing of a destructor name.
4479 ///
4480 /// \param AllowConstructorName whether we allow parsing a constructor name.
4481 ///
4482 /// \param AllowDeductionGuide whether we allow parsing a deduction guide
4483 /// name.
4484 ///
4485 /// \param Result on a successful parse, contains the parsed unqualified-id.
4486 ///
4487 /// \returns true if parsing fails, false otherwise.
4488 bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
4489 bool ObjectHadErrors, bool EnteringContext,
4490 bool AllowDestructorName, bool AllowConstructorName,
4491 bool AllowDeductionGuide,
4492 SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
4493
4494private:
4495 /// ColonIsSacred - When this is false, we aggressively try to recover from
4496 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
4497 /// safe in case statements and a few other things. This is managed by the
4498 /// ColonProtectionRAIIObject RAII object.
4499 bool ColonIsSacred;
4500
4501 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
4502 /// parenthesized ambiguous type-id. This uses tentative parsing to
4503 /// disambiguate based on the context past the parens.
4504 ExprResult ParseCXXAmbiguousParenExpression(
4505 ParenParseOption &ExprType, ParsedType &CastTy,
4507
4508 //===--------------------------------------------------------------------===//
4509 // C++ Expressions
4510 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand);
4511
4512 ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4513 ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4514
4515 /// ParseCXXIdExpression - Handle id-expression.
4516 ///
4517 /// \verbatim
4518 /// id-expression:
4519 /// unqualified-id
4520 /// qualified-id
4521 ///
4522 /// qualified-id:
4523 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4524 /// '::' identifier
4525 /// '::' operator-function-id
4526 /// '::' template-id
4527 ///
4528 /// NOTE: The standard specifies that, for qualified-id, the parser does not
4529 /// expect:
4530 ///
4531 /// '::' conversion-function-id
4532 /// '::' '~' class-name
4533 /// \endverbatim
4534 ///
4535 /// This may cause a slight inconsistency on diagnostics:
4536 ///
4537 /// class C {};
4538 /// namespace A {}
4539 /// void f() {
4540 /// :: A :: ~ C(); // Some Sema error about using destructor with a
4541 /// // namespace.
4542 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
4543 /// }
4544 ///
4545 /// We simplify the parser a bit and make it work like:
4546 ///
4547 /// \verbatim
4548 /// qualified-id:
4549 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4550 /// '::' unqualified-id
4551 /// \endverbatim
4552 ///
4553 /// That way Sema can handle and report similar errors for namespaces and the
4554 /// global scope.
4555 ///
4556 /// The isAddressOfOperand parameter indicates that this id-expression is a
4557 /// direct operand of the address-of operator. This is, besides member
4558 /// contexts, the only place where a qualified-id naming a non-static class
4559 /// member may appear.
4560 ///
4561 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
4562
4563 // Are the two tokens adjacent in the same source file?
4564 bool areTokensAdjacent(const Token &A, const Token &B);
4565
4566 // Check for '<::' which should be '< ::' instead of '[:' when following
4567 // a template name.
4568 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
4569 bool EnteringContext, IdentifierInfo &II,
4570 CXXScopeSpec &SS);
4571
4572 /// Parse global scope or nested-name-specifier if present.
4573 ///
4574 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
4575 /// may be preceded by '::'). Note that this routine will not parse ::new or
4576 /// ::delete; it will just leave them in the token stream.
4577 ///
4578 /// \verbatim
4579 /// '::'[opt] nested-name-specifier
4580 /// '::'
4581 ///
4582 /// nested-name-specifier:
4583 /// type-name '::'
4584 /// namespace-name '::'
4585 /// nested-name-specifier identifier '::'
4586 /// nested-name-specifier 'template'[opt] simple-template-id '::'
4587 /// \endverbatim
4588 ///
4589 ///
4590 /// \param SS the scope specifier that will be set to the parsed
4591 /// nested-name-specifier (or empty)
4592 ///
4593 /// \param ObjectType if this nested-name-specifier is being parsed following
4594 /// the "." or "->" of a member access expression, this parameter provides the
4595 /// type of the object whose members are being accessed.
4596 ///
4597 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4598 /// access expression, indicates whether the original subexpressions had any
4599 /// errors. When true, diagnostics for missing 'template' keyword will be
4600 /// supressed.
4601 ///
4602 /// \param EnteringContext whether we will be entering into the context of
4603 /// the nested-name-specifier after parsing it.
4604 ///
4605 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
4606 /// indicates whether this nested-name-specifier may be part of a
4607 /// pseudo-destructor name. In this case, the flag will be set false
4608 /// if we don't actually end up parsing a destructor name. Moreover,
4609 /// if we do end up determining that we are parsing a destructor name,
4610 /// the last component of the nested-name-specifier is not parsed as
4611 /// part of the scope specifier.
4612 ///
4613 /// \param IsTypename If \c true, this nested-name-specifier is known to be
4614 /// part of a type name. This is used to improve error recovery.
4615 ///
4616 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
4617 /// filled in with the leading identifier in the last component of the
4618 /// nested-name-specifier, if any.
4619 ///
4620 /// \param OnlyNamespace If true, only considers namespaces in lookup.
4621 ///
4622 /// \param IsAddressOfOperand A hint indicating the expression is part of
4623 /// an address-of operation (e.g. '&'). Used by code completion to filter
4624 /// results; may not be set by all callers.
4625 ///
4626 /// \param IsInDeclarationContext A hint indicating whether the current
4627 /// context is likely a declaration. Used by code completion to filter
4628 /// results; may not be set by all callers.
4629 ///
4630 ///
4631 /// \returns true if there was an error parsing a scope specifier
4632 bool ParseOptionalCXXScopeSpecifier(
4633 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
4634 bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
4635 bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
4636 bool OnlyNamespace = false, bool InUsingDeclaration = false,
4637 bool Disambiguation = false, bool IsAddressOfOperand = false,
4638 bool IsInDeclarationContext = false);
4639
4640 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType,
4641 bool ObjectHasErrors,
4642 bool EnteringContext,
4643 bool IsAddressOfOperand) {
4644 return ParseOptionalCXXScopeSpecifier(
4645 SS, ObjectType, ObjectHasErrors, EnteringContext,
4646 /*MayBePseudoDestructor=*/nullptr,
4647 /*IsTypename=*/false,
4648 /*LastII=*/nullptr,
4649 /*OnlyNamespace=*/false,
4650 /*InUsingDeclaration=*/false,
4651 /*Disambiguation=*/false,
4652 /*IsAddressOfOperand=*/IsAddressOfOperand);
4653 }
4654
4655 //===--------------------------------------------------------------------===//
4656 // C++11 5.1.2: Lambda expressions
4657
4658 /// Result of tentatively parsing a lambda-introducer.
4659 enum class LambdaIntroducerTentativeParse {
4660 /// This appears to be a lambda-introducer, which has been fully parsed.
4661 Success,
4662 /// This is a lambda-introducer, but has not been fully parsed, and this
4663 /// function needs to be called again to parse it.
4664 Incomplete,
4665 /// This is definitely an Objective-C message send expression, rather than
4666 /// a lambda-introducer, attribute-specifier, or array designator.
4667 MessageSend,
4668 /// This is not a lambda-introducer.
4669 Invalid,
4670 };
4671
4672 /// ParseLambdaExpression - Parse a C++11 lambda expression.
4673 ///
4674 /// \verbatim
4675 /// lambda-expression:
4676 /// lambda-introducer lambda-declarator compound-statement
4677 /// lambda-introducer '<' template-parameter-list '>'
4678 /// requires-clause[opt] lambda-declarator compound-statement
4679 ///
4680 /// lambda-introducer:
4681 /// '[' lambda-capture[opt] ']'
4682 ///
4683 /// lambda-capture:
4684 /// capture-default
4685 /// capture-list
4686 /// capture-default ',' capture-list
4687 ///
4688 /// capture-default:
4689 /// '&'
4690 /// '='
4691 ///
4692 /// capture-list:
4693 /// capture
4694 /// capture-list ',' capture
4695 ///
4696 /// capture:
4697 /// simple-capture
4698 /// init-capture [C++1y]
4699 ///
4700 /// simple-capture:
4701 /// identifier
4702 /// '&' identifier
4703 /// 'this'
4704 ///
4705 /// init-capture: [C++1y]
4706 /// identifier initializer
4707 /// '&' identifier initializer
4708 ///
4709 /// lambda-declarator:
4710 /// lambda-specifiers [C++23]
4711 /// '(' parameter-declaration-clause ')' lambda-specifiers
4712 /// requires-clause[opt]
4713 ///
4714 /// lambda-specifiers:
4715 /// decl-specifier-seq[opt] noexcept-specifier[opt]
4716 /// attribute-specifier-seq[opt] trailing-return-type[opt]
4717 /// \endverbatim
4718 ///
4719 ExprResult ParseLambdaExpression();
4720
4721 /// Use lookahead and potentially tentative parsing to determine if we are
4722 /// looking at a C++11 lambda expression, and parse it if we are.
4723 ///
4724 /// If we are not looking at a lambda expression, returns ExprError().
4725 ExprResult TryParseLambdaExpression();
4726
4727 /// Parse a lambda introducer.
4728 /// \param Intro A LambdaIntroducer filled in with information about the
4729 /// contents of the lambda-introducer.
4730 /// \param Tentative If non-null, we are disambiguating between a
4731 /// lambda-introducer and some other construct. In this mode, we do not
4732 /// produce any diagnostics or take any other irreversible action
4733 /// unless we're sure that this is a lambda-expression.
4734 /// \return \c true if parsing (or disambiguation) failed with a diagnostic
4735 /// and the caller should bail out / recover.
4736 bool
4737 ParseLambdaIntroducer(LambdaIntroducer &Intro,
4738 LambdaIntroducerTentativeParse *Tentative = nullptr);
4739
4740 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
4741 /// expression.
4742 ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
4743
4744 /// Whether the current token can begin a lambda specifier sequence.
4745 bool isLambdaSpecifier();
4746
4747 //===--------------------------------------------------------------------===//
4748 // C++ 5.2p1: C++ Casts
4749
4750 /// ParseCXXCasts - This handles the various ways to cast expressions to
4751 /// another type.
4752 ///
4753 /// \verbatim
4754 /// postfix-expression: [C++ 5.2p1]
4755 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
4756 /// 'static_cast' '<' type-name '>' '(' expression ')'
4757 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
4758 /// 'const_cast' '<' type-name '>' '(' expression ')'
4759 /// \endverbatim
4760 ///
4761 /// C++ for OpenCL s2.3.1 adds:
4762 /// 'addrspace_cast' '<' type-name '>' '(' expression ')'
4763 ExprResult ParseCXXCasts();
4764
4765 /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
4766 ExprResult ParseBuiltinBitCast();
4767
4768 //===--------------------------------------------------------------------===//
4769 // C++ 5.2p1: C++ Type Identification
4770
4771 /// ParseCXXTypeid - This handles the C++ typeid expression.
4772 ///
4773 /// \verbatim
4774 /// postfix-expression: [C++ 5.2p1]
4775 /// 'typeid' '(' expression ')'
4776 /// 'typeid' '(' type-id ')'
4777 /// \endverbatim
4778 ///
4779 ExprResult ParseCXXTypeid();
4780
4781 //===--------------------------------------------------------------------===//
4782 // C++ : Microsoft __uuidof Expression
4783
4784 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
4785 ///
4786 /// \verbatim
4787 /// '__uuidof' '(' expression ')'
4788 /// '__uuidof' '(' type-id ')'
4789 /// \endverbatim
4790 ///
4791 ExprResult ParseCXXUuidof();
4792
4793 //===--------------------------------------------------------------------===//
4794 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
4795
4796 /// Parse a C++ pseudo-destructor expression after the base,
4797 /// . or -> operator, and nested-name-specifier have already been
4798 /// parsed. We're handling this fragment of the grammar:
4799 ///
4800 /// \verbatim
4801 /// postfix-expression: [C++2a expr.post]
4802 /// postfix-expression . template[opt] id-expression
4803 /// postfix-expression -> template[opt] id-expression
4804 ///
4805 /// id-expression:
4806 /// qualified-id
4807 /// unqualified-id
4808 ///
4809 /// qualified-id:
4810 /// nested-name-specifier template[opt] unqualified-id
4811 ///
4812 /// nested-name-specifier:
4813 /// type-name ::
4814 /// decltype-specifier :: FIXME: not implemented, but probably only
4815 /// allowed in C++ grammar by accident
4816 /// nested-name-specifier identifier ::
4817 /// nested-name-specifier template[opt] simple-template-id ::
4818 /// [...]
4819 ///
4820 /// unqualified-id:
4821 /// ~ type-name
4822 /// ~ decltype-specifier
4823 /// [...]
4824 /// \endverbatim
4825 ///
4826 /// ... where the all but the last component of the nested-name-specifier
4827 /// has already been parsed, and the base expression is not of a non-dependent
4828 /// class type.
4829 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
4830 tok::TokenKind OpKind, CXXScopeSpec &SS,
4831 ParsedType ObjectType);
4832
4833 //===--------------------------------------------------------------------===//
4834 // C++ 9.3.2: C++ 'this' pointer
4835
4836 /// ParseCXXThis - This handles the C++ 'this' pointer.
4837 ///
4838 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
4839 /// is a non-lvalue expression whose value is the address of the object for
4840 /// which the function is called.
4841 ExprResult ParseCXXThis();
4842
4843 //===--------------------------------------------------------------------===//
4844 // C++ 15: C++ Throw Expression
4845
4846 /// ParseThrowExpression - This handles the C++ throw expression.
4847 ///
4848 /// \verbatim
4849 /// throw-expression: [C++ 15]
4850 /// 'throw' assignment-expression[opt]
4851 /// \endverbatim
4852 ExprResult ParseThrowExpression();
4853
4854 //===--------------------------------------------------------------------===//
4855 // C++ 2.13.5: C++ Boolean Literals
4856
4857 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
4858 ///
4859 /// \verbatim
4860 /// boolean-literal: [C++ 2.13.5]
4861 /// 'true'
4862 /// 'false'
4863 /// \endverbatim
4864 ExprResult ParseCXXBoolLiteral();
4865
4866 //===--------------------------------------------------------------------===//
4867 // C++ 5.2.3: Explicit type conversion (functional notation)
4868
4869 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
4870 /// Can be interpreted either as function-style casting ("int(x)")
4871 /// or class type construction ("ClassType(x,y,z)")
4872 /// or creation of a value-initialized type ("int()").
4873 /// See [C++ 5.2.3].
4874 ///
4875 /// \verbatim
4876 /// postfix-expression: [C++ 5.2p1]
4877 /// simple-type-specifier '(' expression-list[opt] ')'
4878 /// [C++0x] simple-type-specifier braced-init-list
4879 /// typename-specifier '(' expression-list[opt] ')'
4880 /// [C++0x] typename-specifier braced-init-list
4881 /// \endverbatim
4882 ///
4883 /// In C++1z onwards, the type specifier can also be a template-name.
4884 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
4885
4886 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
4887 /// This should only be called when the current token is known to be part of
4888 /// simple-type-specifier.
4889 ///
4890 /// \verbatim
4891 /// simple-type-specifier:
4892 /// '::'[opt] nested-name-specifier[opt] type-name
4893 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
4894 /// char
4895 /// wchar_t
4896 /// bool
4897 /// short
4898 /// int
4899 /// long
4900 /// signed
4901 /// unsigned
4902 /// float
4903 /// double
4904 /// void
4905 /// [GNU] typeof-specifier
4906 /// [C++0x] auto [TODO]
4907 ///
4908 /// type-name:
4909 /// class-name
4910 /// enum-name
4911 /// typedef-name
4912 /// \endverbatim
4913 ///
4914 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
4915
4916 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
4917 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
4918 /// e.g., "const short int". Note that the DeclSpec is *not* finished
4919 /// by parsing the type-specifier-seq, because these sequences are
4920 /// typically followed by some form of declarator. Returns true and
4921 /// emits diagnostics if this is not a type-specifier-seq, false
4922 /// otherwise.
4923 ///
4924 /// \verbatim
4925 /// type-specifier-seq: [C++ 8.1]
4926 /// type-specifier type-specifier-seq[opt]
4927 /// \endverbatim
4928 ///
4929 bool ParseCXXTypeSpecifierSeq(
4930 DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
4931
4932 //===--------------------------------------------------------------------===//
4933 // C++ 5.3.4 and 5.3.5: C++ new and delete
4934
4935 /// ParseExpressionListOrTypeId - Parse either an expression-list or a
4936 /// type-id. This ambiguity appears in the syntax of the C++ new operator.
4937 ///
4938 /// \verbatim
4939 /// new-expression:
4940 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4941 /// new-initializer[opt]
4942 ///
4943 /// new-placement:
4944 /// '(' expression-list ')'
4945 /// \endverbatim
4946 ///
4947 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr *> &Exprs,
4948 Declarator &D);
4949
4950 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
4951 /// passed to ParseDeclaratorInternal.
4952 ///
4953 /// \verbatim
4954 /// direct-new-declarator:
4955 /// '[' expression[opt] ']'
4956 /// direct-new-declarator '[' constant-expression ']'
4957 /// \endverbatim
4958 ///
4959 void ParseDirectNewDeclarator(Declarator &D);
4960
4961 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to
4962 /// allocate memory in a typesafe manner and call constructors.
4963 ///
4964 /// This method is called to parse the new expression after the optional ::
4965 /// has been already parsed. If the :: was present, "UseGlobal" is true and
4966 /// "Start" is its location. Otherwise, "Start" is the location of the 'new'
4967 /// token.
4968 ///
4969 /// \verbatim
4970 /// new-expression:
4971 /// '::'[opt] 'new' new-placement[opt] new-type-id
4972 /// new-initializer[opt]
4973 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4974 /// new-initializer[opt]
4975 ///
4976 /// new-placement:
4977 /// '(' expression-list ')'
4978 ///
4979 /// new-type-id:
4980 /// type-specifier-seq new-declarator[opt]
4981 /// [GNU] attributes type-specifier-seq new-declarator[opt]
4982 ///
4983 /// new-declarator:
4984 /// ptr-operator new-declarator[opt]
4985 /// direct-new-declarator
4986 ///
4987 /// new-initializer:
4988 /// '(' expression-list[opt] ')'
4989 /// [C++0x] braced-init-list
4990 /// \endverbatim
4991 ///
4992 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
4993
4994 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
4995 /// to free memory allocated by new.
4996 ///
4997 /// This method is called to parse the 'delete' expression after the optional
4998 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is
4999 /// true and "Start" is its location. Otherwise, "Start" is the location of
5000 /// the 'delete' token.
5001 ///
5002 /// \verbatim
5003 /// delete-expression:
5004 /// '::'[opt] 'delete' cast-expression
5005 /// '::'[opt] 'delete' '[' ']' cast-expression
5006 /// \endverbatim
5007 ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start);
5008
5009 //===--------------------------------------------------------------------===//
5010 // C++ if/switch/while/for condition expression.
5011
5012 /// ParseCondition - if/switch/while condition expression.
5013 ///
5014 /// \verbatim
5015 /// condition:
5016 /// expression
5017 /// type-specifier-seq declarator '=' assignment-expression
5018 /// [C++11] type-specifier-seq declarator '=' initializer-clause
5019 /// [C++11] type-specifier-seq declarator braced-init-list
5020 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
5021 /// brace-or-equal-initializer
5022 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
5023 /// '=' assignment-expression
5024 /// \endverbatim
5025 ///
5026 /// In C++1z, a condition may in some contexts be preceded by an
5027 /// optional init-statement. This function will parse that too.
5028 ///
5029 /// \param InitStmt If non-null, an init-statement is permitted, and if
5030 /// present will be parsed and stored here.
5031 ///
5032 /// \param Loc The location of the start of the statement that requires this
5033 /// condition, e.g., the "for" in a for loop.
5034 ///
5035 /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
5036 /// it is considered an error to be recovered from.
5037 ///
5038 /// \param FRI If non-null, a for range declaration is permitted, and if
5039 /// present will be parsed and stored here, and a null result will be
5040 /// returned.
5041 ///
5042 /// \returns The parsed condition.
5043 Sema::ConditionResult ParseCondition(StmtResult *InitStmt, SourceLocation Loc,
5044 Sema::ConditionKind CK, bool MissingOK,
5045 ForRangeInfo *FRI = nullptr);
5046 DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
5047 ParsedAttributes &Attrs);
5048
5049 //===--------------------------------------------------------------------===//
5050 // C++ Coroutines
5051
5052 /// Parse the C++ Coroutines co_yield expression.
5053 ///
5054 /// \verbatim
5055 /// co_yield-expression:
5056 /// 'co_yield' assignment-expression[opt]
5057 /// \endverbatim
5058 ExprResult ParseCoyieldExpression();
5059
5060 //===--------------------------------------------------------------------===//
5061 // C++ Concepts
5062
5063 /// ParseRequiresExpression - Parse a C++2a requires-expression.
5064 /// C++2a [expr.prim.req]p1
5065 /// A requires-expression provides a concise way to express requirements
5066 /// on template arguments. A requirement is one that can be checked by
5067 /// name lookup (6.4) or by checking properties of types and expressions.
5068 ///
5069 /// \verbatim
5070 /// requires-expression:
5071 /// 'requires' requirement-parameter-list[opt] requirement-body
5072 ///
5073 /// requirement-parameter-list:
5074 /// '(' parameter-declaration-clause[opt] ')'
5075 ///
5076 /// requirement-body:
5077 /// '{' requirement-seq '}'
5078 ///
5079 /// requirement-seq:
5080 /// requirement
5081 /// requirement-seq requirement
5082 ///
5083 /// requirement:
5084 /// simple-requirement
5085 /// type-requirement
5086 /// compound-requirement
5087 /// nested-requirement
5088 /// \endverbatim
5089 ExprResult ParseRequiresExpression();
5090
5091 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
5092 /// whether the parens contain an expression or a type-id.
5093 /// Returns true for a type-id and false for an expression.
5094 bool isTypeIdInParens(bool &isAmbiguous) {
5095 if (getLangOpts().CPlusPlus)
5096 return isCXXTypeId(TentativeCXXTypeIdContext::InParens, isAmbiguous);
5097 isAmbiguous = false;
5098 return isTypeSpecifierQualifier(Tok);
5099 }
5100 bool isTypeIdInParens() {
5101 bool isAmbiguous;
5102 return isTypeIdInParens(isAmbiguous);
5103 }
5104
5105 /// Finish parsing a C++ unqualified-id that is a template-id of
5106 /// some form.
5107 ///
5108 /// This routine is invoked when a '<' is encountered after an identifier or
5109 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
5110 /// whether the unqualified-id is actually a template-id. This routine will
5111 /// then parse the template arguments and form the appropriate template-id to
5112 /// return to the caller.
5113 ///
5114 /// \param SS the nested-name-specifier that precedes this template-id, if
5115 /// we're actually parsing a qualified-id.
5116 ///
5117 /// \param ObjectType if this unqualified-id occurs within a member access
5118 /// expression, the type of the base object whose member is being accessed.
5119 ///
5120 /// \param ObjectHadErrors this unqualified-id occurs within a member access
5121 /// expression, indicates whether the original subexpressions had any errors.
5122 ///
5123 /// \param Name for constructor and destructor names, this is the actual
5124 /// identifier that may be a template-name.
5125 ///
5126 /// \param NameLoc the location of the class-name in a constructor or
5127 /// destructor.
5128 ///
5129 /// \param EnteringContext whether we're entering the scope of the
5130 /// nested-name-specifier.
5131 ///
5132 /// \param Id as input, describes the template-name or operator-function-id
5133 /// that precedes the '<'. If template arguments were parsed successfully,
5134 /// will be updated with the template-id.
5135 ///
5136 /// \param AssumeTemplateId When true, this routine will assume that the name
5137 /// refers to a template without performing name lookup to verify.
5138 ///
5139 /// \returns true if a parse error occurred, false otherwise.
5140 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType,
5141 bool ObjectHadErrors,
5142 SourceLocation TemplateKWLoc,
5143 IdentifierInfo *Name,
5144 SourceLocation NameLoc,
5145 bool EnteringContext, UnqualifiedId &Id,
5146 bool AssumeTemplateId);
5147
5148 /// Parse an operator-function-id or conversion-function-id as part
5149 /// of a C++ unqualified-id.
5150 ///
5151 /// This routine is responsible only for parsing the operator-function-id or
5152 /// conversion-function-id; it does not handle template arguments in any way.
5153 ///
5154 /// \verbatim
5155 /// operator-function-id: [C++ 13.5]
5156 /// 'operator' operator
5157 ///
5158 /// operator: one of
5159 /// new delete new[] delete[]
5160 /// + - * / % ^ & | ~
5161 /// ! = < > += -= *= /= %=
5162 /// ^= &= |= << >> >>= <<= == !=
5163 /// <= >= && || ++ -- , ->* ->
5164 /// () [] <=>
5165 ///
5166 /// conversion-function-id: [C++ 12.3.2]
5167 /// operator conversion-type-id
5168 ///
5169 /// conversion-type-id:
5170 /// type-specifier-seq conversion-declarator[opt]
5171 ///
5172 /// conversion-declarator:
5173 /// ptr-operator conversion-declarator[opt]
5174 /// \endverbatim
5175 ///
5176 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
5177 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
5178 ///
5179 /// \param EnteringContext whether we are entering the scope of the
5180 /// nested-name-specifier.
5181 ///
5182 /// \param ObjectType if this unqualified-id occurs within a member access
5183 /// expression, the type of the base object whose member is being accessed.
5184 ///
5185 /// \param Result on a successful parse, contains the parsed unqualified-id.
5186 ///
5187 /// \returns true if parsing fails, false otherwise.
5188 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
5189 ParsedType ObjectType, UnqualifiedId &Result);
5190
5191 //===--------------------------------------------------------------------===//
5192 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
5193
5194 /// Parse the built-in type-trait pseudo-functions that allow
5195 /// implementation of the TR1/C++11 type traits templates.
5196 ///
5197 /// \verbatim
5198 /// primary-expression:
5199 /// unary-type-trait '(' type-id ')'
5200 /// binary-type-trait '(' type-id ',' type-id ')'
5201 /// type-trait '(' type-id-seq ')'
5202 ///
5203 /// type-id-seq:
5204 /// type-id ...[opt] type-id-seq[opt]
5205 /// \endverbatim
5206 ///
5207 ExprResult ParseTypeTrait();
5208
5209 //===--------------------------------------------------------------------===//
5210 // Embarcadero: Arary and Expression Traits
5211
5212 /// ParseArrayTypeTrait - Parse the built-in array type-trait
5213 /// pseudo-functions.
5214 ///
5215 /// \verbatim
5216 /// primary-expression:
5217 /// [Embarcadero] '__array_rank' '(' type-id ')'
5218 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
5219 /// \endverbatim
5220 ///
5221 ExprResult ParseArrayTypeTrait();
5222
5223 /// ParseExpressionTrait - Parse built-in expression-trait
5224 /// pseudo-functions like __is_lvalue_expr( xxx ).
5225 ///
5226 /// \verbatim
5227 /// primary-expression:
5228 /// [Embarcadero] expression-trait '(' expression ')'
5229 /// \endverbatim
5230 ///
5231 ExprResult ParseExpressionTrait();
5232
5233 ///@}
5234
5235 //===--------------------------------------------------------------------===//
5236 // Reflection parsing
5237
5238 /// ParseCXXReflectExpression - parses the operand of reflection operator.
5239 ///
5240 /// \returns on success, an expression holding the constructed CXXReflectExpr;
5241 /// on failure, an ExprError.
5242 ExprResult ParseCXXReflectExpression();
5243
5244 //
5245 //
5246 // -------------------------------------------------------------------------
5247 //
5248 //
5249
5250 /// \name HLSL Constructs
5251 /// Implementations are in ParseHLSL.cpp
5252 ///@{
5253
5254private:
5255 bool MaybeParseHLSLAnnotations(Declarator &D,
5256 SourceLocation *EndLoc = nullptr,
5257 bool CouldBeBitField = false) {
5258 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5259 if (Tok.is(tok::colon)) {
5260 ParsedAttributes Attrs(AttrFactory);
5261 ParseHLSLAnnotations(Attrs, EndLoc, CouldBeBitField);
5262 D.takeAttributesAppending(Attrs);
5263 return true;
5264 }
5265 return false;
5266 }
5267
5268 void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
5269 SourceLocation *EndLoc = nullptr) {
5270 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5271 if (Tok.is(tok::colon))
5272 ParseHLSLAnnotations(Attrs, EndLoc);
5273 }
5274
5275 struct ParsedSemantic {
5276 StringRef Name = "";
5277 unsigned Index = 0;
5278 bool Explicit = false;
5279 };
5280
5281 ParsedSemantic ParseHLSLSemantic();
5282
5283 void ParseHLSLAnnotations(ParsedAttributes &Attrs,
5284 SourceLocation *EndLoc = nullptr,
5285 bool CouldBeBitField = false);
5286 Decl *ParseHLSLBuffer(SourceLocation &DeclEnd, ParsedAttributes &Attrs);
5287
5288 ///@}
5289
5290 //
5291 //
5292 // -------------------------------------------------------------------------
5293 //
5294 //
5295
5296 /// \name Initializers
5297 /// Implementations are in ParseInit.cpp
5298 ///@{
5299
5300private:
5301 //===--------------------------------------------------------------------===//
5302 // C99 6.7.8: Initialization.
5303
5304 /// ParseInitializer
5305 /// \verbatim
5306 /// initializer: [C99 6.7.8]
5307 /// assignment-expression
5308 /// '{' ...
5309 /// \endverbatim
5310 ExprResult ParseInitializer(Decl *DeclForInitializer = nullptr);
5311
5312 /// MayBeDesignationStart - Return true if the current token might be the
5313 /// start of a designator. If we can tell it is impossible that it is a
5314 /// designator, return false.
5315 bool MayBeDesignationStart();
5316
5317 /// ParseBraceInitializer - Called when parsing an initializer that has a
5318 /// leading open brace.
5319 ///
5320 /// \verbatim
5321 /// initializer: [C99 6.7.8]
5322 /// '{' initializer-list '}'
5323 /// '{' initializer-list ',' '}'
5324 /// [C23] '{' '}'
5325 ///
5326 /// initializer-list:
5327 /// designation[opt] initializer ...[opt]
5328 /// initializer-list ',' designation[opt] initializer ...[opt]
5329 /// \endverbatim
5330 ///
5331 ExprResult ParseBraceInitializer();
5332
5333 /// ParseExpansionInitList - Called when the initializer of an expansion
5334 /// statement starts with an open brace.
5335 ///
5336 /// \verbatim
5337 /// expansion-init-list: [C++26 [stmt.expand]]
5338 /// '{' expression-list ','[opt] '}'
5339 /// '{' '}'
5340 /// \endverbatim
5341 ExprResult ParseExpansionInitList();
5342
5343 struct DesignatorCompletionInfo {
5344 SmallVectorImpl<Expr *> &InitExprs;
5345 QualType PreferredBaseType;
5346 };
5347
5348 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer'
5349 /// production checking to see if the token stream starts with a designator.
5350 ///
5351 /// C99:
5352 ///
5353 /// \verbatim
5354 /// designation:
5355 /// designator-list '='
5356 /// [GNU] array-designator
5357 /// [GNU] identifier ':'
5358 ///
5359 /// designator-list:
5360 /// designator
5361 /// designator-list designator
5362 ///
5363 /// designator:
5364 /// array-designator
5365 /// '.' identifier
5366 ///
5367 /// array-designator:
5368 /// '[' constant-expression ']'
5369 /// [GNU] '[' constant-expression '...' constant-expression ']'
5370 /// \endverbatim
5371 ///
5372 /// C++20:
5373 ///
5374 /// \verbatim
5375 /// designated-initializer-list:
5376 /// designated-initializer-clause
5377 /// designated-initializer-list ',' designated-initializer-clause
5378 ///
5379 /// designated-initializer-clause:
5380 /// designator brace-or-equal-initializer
5381 ///
5382 /// designator:
5383 /// '.' identifier
5384 /// \endverbatim
5385 ///
5386 /// We allow the C99 syntax extensions in C++20, but do not allow the C++20
5387 /// extension (a braced-init-list after the designator with no '=') in C99.
5388 ///
5389 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
5390 /// initializer (because it is an expression). We need to consider this case
5391 /// when parsing array designators.
5392 ///
5393 /// \p CodeCompleteCB is called with Designation parsed so far.
5394 ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
5395
5396 ExprResult createEmbedExpr();
5397
5398 /// A SmallVector of expressions.
5399 typedef SmallVector<Expr *, 12> ExprVector;
5400
5401 // Return true if a comma (or closing brace) is necessary after the
5402 // __if_exists/if_not_exists statement.
5403 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
5404 bool &InitExprsOk);
5405
5406 ///@}
5407
5408 //
5409 //
5410 // -------------------------------------------------------------------------
5411 //
5412 //
5413
5414 /// \name Objective-C Constructs
5415 /// Implementations are in ParseObjc.cpp
5416 ///@{
5417
5418public:
5420 friend class ObjCDeclContextSwitch;
5421
5423 return Actions.ObjC().getObjCDeclContext();
5424 }
5425
5426 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
5427 /// to the given nullability kind.
5429 return Actions.getNullabilityKeyword(nullability);
5430 }
5431
5432private:
5433 /// Objective-C contextual keywords.
5434 IdentifierInfo *Ident_instancetype;
5435
5436 /// Ident_super - IdentifierInfo for "super", to support fast
5437 /// comparison.
5438 IdentifierInfo *Ident_super;
5439
5440 /// When true, we are directly inside an Objective-C message
5441 /// send expression.
5442 ///
5443 /// This is managed by the \c InMessageExpressionRAIIObject class, and
5444 /// should not be set directly.
5445 bool InMessageExpression;
5446
5447 /// True if we are within an Objective-C container while parsing C-like decls.
5448 ///
5449 /// This is necessary because Sema thinks we have left the container
5450 /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
5451 /// will be NULL.
5452 bool ParsingInObjCContainer;
5453
5454 /// Returns true if the current token is the identifier 'instancetype'.
5455 ///
5456 /// Should only be used in Objective-C language modes.
5457 bool isObjCInstancetype() {
5458 assert(getLangOpts().ObjC);
5459 if (Tok.isAnnotation())
5460 return false;
5461 if (!Ident_instancetype)
5462 Ident_instancetype = PP.getIdentifierInfo("instancetype");
5463 return Tok.getIdentifierInfo() == Ident_instancetype;
5464 }
5465
5466 /// ObjCDeclContextSwitch - An object used to switch context from
5467 /// an objective-c decl context to its enclosing decl context and
5468 /// back.
5469 class ObjCDeclContextSwitch {
5470 Parser &P;
5471 ObjCContainerDecl *DC;
5472 SaveAndRestore<bool> WithinObjCContainer;
5473
5474 public:
5475 explicit ObjCDeclContextSwitch(Parser &p)
5476 : P(p), DC(p.getObjCDeclContext()),
5477 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
5478 if (DC)
5479 P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(DC);
5480 }
5481 ~ObjCDeclContextSwitch() {
5482 if (DC)
5483 P.Actions.ObjC().ActOnObjCReenterContainerContext(DC);
5484 }
5485 };
5486
5487 void CheckNestedObjCContexts(SourceLocation AtLoc);
5488
5489 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
5490
5491 // Objective-C External Declarations
5492
5493 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
5494 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
5495
5496 /// ParseObjCAtDirectives - Handle parts of the external-declaration
5497 /// production:
5498 /// \verbatim
5499 /// external-declaration: [C99 6.9]
5500 /// [OBJC] objc-class-definition
5501 /// [OBJC] objc-class-declaration
5502 /// [OBJC] objc-alias-declaration
5503 /// [OBJC] objc-protocol-definition
5504 /// [OBJC] objc-method-definition
5505 /// [OBJC] '@' 'end'
5506 /// \endverbatim
5507 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
5508 ParsedAttributes &DeclSpecAttrs);
5509
5510 ///
5511 /// \verbatim
5512 /// objc-class-declaration:
5513 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
5514 ///
5515 /// objc-class-forward-decl:
5516 /// identifier objc-type-parameter-list[opt]
5517 /// \endverbatim
5518 ///
5519 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
5520
5521 ///
5522 /// \verbatim
5523 /// objc-interface:
5524 /// objc-class-interface-attributes[opt] objc-class-interface
5525 /// objc-category-interface
5526 ///
5527 /// objc-class-interface:
5528 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5529 /// objc-superclass[opt] objc-protocol-refs[opt]
5530 /// objc-class-instance-variables[opt]
5531 /// objc-interface-decl-list
5532 /// @end
5533 ///
5534 /// objc-category-interface:
5535 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5536 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
5537 /// objc-interface-decl-list
5538 /// @end
5539 ///
5540 /// objc-superclass:
5541 /// ':' identifier objc-type-arguments[opt]
5542 ///
5543 /// objc-class-interface-attributes:
5544 /// __attribute__((visibility("default")))
5545 /// __attribute__((visibility("hidden")))
5546 /// __attribute__((deprecated))
5547 /// __attribute__((unavailable))
5548 /// __attribute__((objc_exception)) - used by NSException on 64-bit
5549 /// __attribute__((objc_root_class))
5550 /// \endverbatim
5551 ///
5552 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
5553 ParsedAttributes &prefixAttrs);
5554
5555 /// Class to handle popping type parameters when leaving the scope.
5557
5558 /// Parse an objc-type-parameter-list.
5559 ObjCTypeParamList *parseObjCTypeParamList();
5560
5561 /// Parse an Objective-C type parameter list, if present, or capture
5562 /// the locations of the protocol identifiers for a list of protocol
5563 /// references.
5564 ///
5565 /// \verbatim
5566 /// objc-type-parameter-list:
5567 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
5568 ///
5569 /// objc-type-parameter:
5570 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
5571 ///
5572 /// objc-type-parameter-bound:
5573 /// ':' type-name
5574 ///
5575 /// objc-type-parameter-variance:
5576 /// '__covariant'
5577 /// '__contravariant'
5578 /// \endverbatim
5579 ///
5580 /// \param lAngleLoc The location of the starting '<'.
5581 ///
5582 /// \param protocolIdents Will capture the list of identifiers, if the
5583 /// angle brackets contain a list of protocol references rather than a
5584 /// type parameter list.
5585 ///
5586 /// \param rAngleLoc The location of the ending '>'.
5587 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
5588 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
5589 SmallVectorImpl<IdentifierLoc> &protocolIdents, SourceLocation &rAngleLoc,
5590 bool mayBeProtocolList = true);
5591
5592 void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
5593 SourceLocation atLoc,
5595 SmallVectorImpl<Decl *> &AllIvarDecls,
5596 bool RBraceMissing);
5597
5598 /// \verbatim
5599 /// objc-class-instance-variables:
5600 /// '{' objc-instance-variable-decl-list[opt] '}'
5601 ///
5602 /// objc-instance-variable-decl-list:
5603 /// objc-visibility-spec
5604 /// objc-instance-variable-decl ';'
5605 /// ';'
5606 /// objc-instance-variable-decl-list objc-visibility-spec
5607 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
5608 /// objc-instance-variable-decl-list static_assert-declaration
5609 /// objc-instance-variable-decl-list ';'
5610 ///
5611 /// objc-visibility-spec:
5612 /// @private
5613 /// @protected
5614 /// @public
5615 /// @package [OBJC2]
5616 ///
5617 /// objc-instance-variable-decl:
5618 /// struct-declaration
5619 /// \endverbatim
5620 ///
5621 void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
5622 tok::ObjCKeywordKind visibility,
5623 SourceLocation atLoc);
5624
5625 /// \verbatim
5626 /// objc-protocol-refs:
5627 /// '<' identifier-list '>'
5628 /// \endverbatim
5629 ///
5630 bool ParseObjCProtocolReferences(
5631 SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs,
5632 bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc,
5633 SourceLocation &EndProtoLoc, bool consumeLastToken);
5634
5635 /// Parse the first angle-bracket-delimited clause for an
5636 /// Objective-C object or object pointer type, which may be either
5637 /// type arguments or protocol qualifiers.
5638 ///
5639 /// \verbatim
5640 /// objc-type-arguments:
5641 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
5642 /// \endverbatim
5643 ///
5644 void parseObjCTypeArgsOrProtocolQualifiers(
5645 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5646 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5647 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5648 SmallVectorImpl<SourceLocation> &protocolLocs,
5649 SourceLocation &protocolRAngleLoc, bool consumeLastToken,
5650 bool warnOnIncompleteProtocols);
5651
5652 /// Parse either Objective-C type arguments or protocol qualifiers; if the
5653 /// former, also parse protocol qualifiers afterward.
5654 void parseObjCTypeArgsAndProtocolQualifiers(
5655 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5656 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5657 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5658 SmallVectorImpl<SourceLocation> &protocolLocs,
5659 SourceLocation &protocolRAngleLoc, bool consumeLastToken);
5660
5661 /// Parse a protocol qualifier type such as '<NSCopying>', which is
5662 /// an anachronistic way of writing 'id<NSCopying>'.
5663 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
5664
5665 /// Parse Objective-C type arguments and protocol qualifiers, extending the
5666 /// current type with the parsed result.
5667 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
5669 bool consumeLastToken,
5670 SourceLocation &endLoc);
5671
5672 /// \verbatim
5673 /// objc-interface-decl-list:
5674 /// empty
5675 /// objc-interface-decl-list objc-property-decl [OBJC2]
5676 /// objc-interface-decl-list objc-method-requirement [OBJC2]
5677 /// objc-interface-decl-list objc-method-proto ';'
5678 /// objc-interface-decl-list declaration
5679 /// objc-interface-decl-list ';'
5680 ///
5681 /// objc-method-requirement: [OBJC2]
5682 /// @required
5683 /// @optional
5684 /// \endverbatim
5685 ///
5686 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl);
5687
5688 /// \verbatim
5689 /// objc-protocol-declaration:
5690 /// objc-protocol-definition
5691 /// objc-protocol-forward-reference
5692 ///
5693 /// objc-protocol-definition:
5694 /// \@protocol identifier
5695 /// objc-protocol-refs[opt]
5696 /// objc-interface-decl-list
5697 /// \@end
5698 ///
5699 /// objc-protocol-forward-reference:
5700 /// \@protocol identifier-list ';'
5701 /// \endverbatim
5702 ///
5703 /// "\@protocol identifier ;" should be resolved as "\@protocol
5704 /// identifier-list ;": objc-interface-decl-list may not start with a
5705 /// semicolon in the first alternative if objc-protocol-refs are omitted.
5706 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
5707 ParsedAttributes &prefixAttrs);
5708
5709 struct ObjCImplParsingDataRAII {
5710 Parser &P;
5711 Decl *Dcl;
5712 bool HasCFunction;
5713 typedef SmallVector<LexedMethod *, 8> LateParsedObjCMethodContainer;
5714 LateParsedObjCMethodContainer LateParsedObjCMethods;
5715
5716 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
5717 : P(parser), Dcl(D), HasCFunction(false),
5718 PrevParsedObjCImpl(parser.CurParsedObjCImpl) {
5719 P.CurParsedObjCImpl = this;
5720 Finished = false;
5721 }
5722 ~ObjCImplParsingDataRAII();
5723
5724 void finish(SourceRange AtEnd);
5725 bool isFinished() const { return Finished; }
5726
5727 private:
5728 /// The \@implementation that was still open when this one started; made
5729 /// current again once this one finishes. Only invalid code has one: an
5730 /// \@implementation that starts while a previous \@implementation is
5731 /// still open (e.g. through an intervening namespace). For valid code
5732 /// this is always null.
5733 ObjCImplParsingDataRAII *PrevParsedObjCImpl;
5734 bool Finished;
5735 };
5736 ObjCImplParsingDataRAII *CurParsedObjCImpl;
5737
5738 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
5739 /// for later parsing.
5740 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
5741
5742 /// \verbatim
5743 /// objc-implementation:
5744 /// objc-class-implementation-prologue
5745 /// objc-category-implementation-prologue
5746 ///
5747 /// objc-class-implementation-prologue:
5748 /// @implementation identifier objc-superclass[opt]
5749 /// objc-class-instance-variables[opt]
5750 ///
5751 /// objc-category-implementation-prologue:
5752 /// @implementation identifier ( identifier )
5753 /// \endverbatim
5754 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
5755 ParsedAttributes &Attrs);
5756 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
5757
5758 /// \verbatim
5759 /// compatibility-alias-decl:
5760 /// @compatibility_alias alias-name class-name ';'
5761 /// \endverbatim
5762 ///
5763 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
5764
5765 /// \verbatim
5766 /// property-synthesis:
5767 /// @synthesize property-ivar-list ';'
5768 ///
5769 /// property-ivar-list:
5770 /// property-ivar
5771 /// property-ivar-list ',' property-ivar
5772 ///
5773 /// property-ivar:
5774 /// identifier
5775 /// identifier '=' identifier
5776 /// \endverbatim
5777 ///
5778 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
5779
5780 /// \verbatim
5781 /// property-dynamic:
5782 /// @dynamic property-list
5783 ///
5784 /// property-list:
5785 /// identifier
5786 /// property-list ',' identifier
5787 /// \endverbatim
5788 ///
5789 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
5790
5791 /// \verbatim
5792 /// objc-selector:
5793 /// identifier
5794 /// one of
5795 /// enum struct union if else while do for switch case default
5796 /// break continue return goto asm sizeof typeof __alignof
5797 /// unsigned long const short volatile signed restrict _Complex
5798 /// in out inout bycopy byref oneway int char float double void _Bool
5799 /// \endverbatim
5800 ///
5801 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
5802
5803 IdentifierInfo *ObjCTypeQuals[llvm::to_underlying(ObjCTypeQual::NumQuals)];
5804
5805 /// \verbatim
5806 /// objc-for-collection-in: 'in'
5807 /// \endverbatim
5808 ///
5809 bool isTokIdentifier_in() const;
5810
5811 /// \verbatim
5812 /// objc-type-name:
5813 /// '(' objc-type-qualifiers[opt] type-name ')'
5814 /// '(' objc-type-qualifiers[opt] ')'
5815 /// \endverbatim
5816 ///
5817 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
5818 ParsedAttributes *ParamAttrs);
5819
5820 /// \verbatim
5821 /// objc-method-proto:
5822 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
5823 /// objc-class-method objc-method-decl objc-method-attributes[opt]
5824 ///
5825 /// objc-instance-method: '-'
5826 /// objc-class-method: '+'
5827 ///
5828 /// objc-method-attributes: [OBJC2]
5829 /// __attribute__((deprecated))
5830 /// \endverbatim
5831 ///
5832 Decl *ParseObjCMethodPrototype(
5833 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5834 bool MethodDefinition = true);
5835
5836 /// \verbatim
5837 /// objc-method-decl:
5838 /// objc-selector
5839 /// objc-keyword-selector objc-parmlist[opt]
5840 /// objc-type-name objc-selector
5841 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
5842 ///
5843 /// objc-keyword-selector:
5844 /// objc-keyword-decl
5845 /// objc-keyword-selector objc-keyword-decl
5846 ///
5847 /// objc-keyword-decl:
5848 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
5849 /// objc-selector ':' objc-keyword-attributes[opt] identifier
5850 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
5851 /// ':' objc-keyword-attributes[opt] identifier
5852 ///
5853 /// objc-parmlist:
5854 /// objc-parms objc-ellipsis[opt]
5855 ///
5856 /// objc-parms:
5857 /// objc-parms , parameter-declaration
5858 ///
5859 /// objc-ellipsis:
5860 /// , ...
5861 ///
5862 /// objc-keyword-attributes: [OBJC2]
5863 /// __attribute__((unused))
5864 /// \endverbatim
5865 ///
5866 Decl *ParseObjCMethodDecl(
5867 SourceLocation mLoc, tok::TokenKind mType,
5868 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5869 bool MethodDefinition = true);
5870
5871 /// Parse property attribute declarations.
5872 ///
5873 /// \verbatim
5874 /// property-attr-decl: '(' property-attrlist ')'
5875 /// property-attrlist:
5876 /// property-attribute
5877 /// property-attrlist ',' property-attribute
5878 /// property-attribute:
5879 /// getter '=' identifier
5880 /// setter '=' identifier ':'
5881 /// direct
5882 /// readonly
5883 /// readwrite
5884 /// assign
5885 /// retain
5886 /// copy
5887 /// nonatomic
5888 /// atomic
5889 /// strong
5890 /// weak
5891 /// unsafe_unretained
5892 /// nonnull
5893 /// nullable
5894 /// null_unspecified
5895 /// null_resettable
5896 /// class
5897 /// \endverbatim
5898 ///
5899 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
5900
5901 /// \verbatim
5902 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
5903 /// \endverbatim
5904 ///
5905 Decl *ParseObjCMethodDefinition();
5906
5907 //===--------------------------------------------------------------------===//
5908 // Objective-C Expressions
5909 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
5910 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
5911
5912 /// ParseObjCCharacterLiteral -
5913 /// \verbatim
5914 /// objc-scalar-literal : '@' character-literal
5915 /// ;
5916 /// \endverbatim
5917 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
5918
5919 /// ParseObjCNumericLiteral -
5920 /// \verbatim
5921 /// objc-scalar-literal : '@' scalar-literal
5922 /// ;
5923 /// scalar-literal : | numeric-constant /* any numeric constant. */
5924 /// ;
5925 /// \endverbatim
5926 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
5927
5928 /// ParseObjCBooleanLiteral -
5929 /// \verbatim
5930 /// objc-scalar-literal : '@' boolean-keyword
5931 /// ;
5932 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
5933 /// ;
5934 /// \endverbatim
5935 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
5936
5937 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
5938 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
5939
5940 /// ParseObjCBoxedExpr -
5941 /// \verbatim
5942 /// objc-box-expression:
5943 /// @( assignment-expression )
5944 /// \endverbatim
5945 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
5946
5947 /// \verbatim
5948 /// objc-encode-expression:
5949 /// \@encode ( type-name )
5950 /// \endverbatim
5951 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
5952
5953 /// \verbatim
5954 /// objc-selector-expression
5955 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
5956 /// \endverbatim
5957 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
5958
5959 /// \verbatim
5960 /// objc-protocol-expression
5961 /// \@protocol ( protocol-name )
5962 /// \endverbatim
5963 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
5964
5965 /// Determine whether the parser is currently referring to a an
5966 /// Objective-C message send, using a simplified heuristic to avoid overhead.
5967 ///
5968 /// This routine will only return true for a subset of valid message-send
5969 /// expressions.
5970 bool isSimpleObjCMessageExpression();
5971
5972 /// \verbatim
5973 /// objc-message-expr:
5974 /// '[' objc-receiver objc-message-args ']'
5975 ///
5976 /// objc-receiver: [C]
5977 /// 'super'
5978 /// expression
5979 /// class-name
5980 /// type-name
5981 /// \endverbatim
5982 ///
5983 ExprResult ParseObjCMessageExpression();
5984
5985 /// Parse the remainder of an Objective-C message following the
5986 /// '[' objc-receiver.
5987 ///
5988 /// This routine handles sends to super, class messages (sent to a
5989 /// class name), and instance messages (sent to an object), and the
5990 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
5991 /// ReceiverExpr, respectively. Only one of these parameters may have
5992 /// a valid value.
5993 ///
5994 /// \param LBracLoc The location of the opening '['.
5995 ///
5996 /// \param SuperLoc If this is a send to 'super', the location of the
5997 /// 'super' keyword that indicates a send to the superclass.
5998 ///
5999 /// \param ReceiverType If this is a class message, the type of the
6000 /// class we are sending a message to.
6001 ///
6002 /// \param ReceiverExpr If this is an instance message, the expression
6003 /// used to compute the receiver object.
6004 ///
6005 /// \verbatim
6006 /// objc-message-args:
6007 /// objc-selector
6008 /// objc-keywordarg-list
6009 ///
6010 /// objc-keywordarg-list:
6011 /// objc-keywordarg
6012 /// objc-keywordarg-list objc-keywordarg
6013 ///
6014 /// objc-keywordarg:
6015 /// selector-name[opt] ':' objc-keywordexpr
6016 ///
6017 /// objc-keywordexpr:
6018 /// nonempty-expr-list
6019 ///
6020 /// nonempty-expr-list:
6021 /// assignment-expression
6022 /// nonempty-expr-list , assignment-expression
6023 /// \endverbatim
6024 ///
6025 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
6026 SourceLocation SuperLoc,
6027 ParsedType ReceiverType,
6028 Expr *ReceiverExpr);
6029
6030 /// Parse the receiver of an Objective-C++ message send.
6031 ///
6032 /// This routine parses the receiver of a message send in
6033 /// Objective-C++ either as a type or as an expression. Note that this
6034 /// routine must not be called to parse a send to 'super', since it
6035 /// has no way to return such a result.
6036 ///
6037 /// \param IsExpr Whether the receiver was parsed as an expression.
6038 ///
6039 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
6040 /// IsExpr is true), the parsed expression. If the receiver was parsed
6041 /// as a type (\c IsExpr is false), the parsed type.
6042 ///
6043 /// \returns True if an error occurred during parsing or semantic
6044 /// analysis, in which case the arguments do not have valid
6045 /// values. Otherwise, returns false for a successful parse.
6046 ///
6047 /// \verbatim
6048 /// objc-receiver: [C++]
6049 /// 'super' [not parsed here]
6050 /// expression
6051 /// simple-type-specifier
6052 /// typename-specifier
6053 /// \endverbatim
6054 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
6055
6056 //===--------------------------------------------------------------------===//
6057 // Objective-C Statements
6058
6059 enum class ParsedStmtContext;
6060
6061 StmtResult ParseObjCAtStatement(SourceLocation atLoc,
6062 ParsedStmtContext StmtCtx);
6063
6064 /// \verbatim
6065 /// objc-try-catch-statement:
6066 /// @try compound-statement objc-catch-list[opt]
6067 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
6068 ///
6069 /// objc-catch-list:
6070 /// @catch ( parameter-declaration ) compound-statement
6071 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
6072 /// catch-parameter-declaration:
6073 /// parameter-declaration
6074 /// '...' [OBJC2]
6075 /// \endverbatim
6076 ///
6077 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
6078
6079 /// \verbatim
6080 /// objc-throw-statement:
6081 /// throw expression[opt];
6082 /// \endverbatim
6083 ///
6084 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
6085
6086 /// \verbatim
6087 /// objc-synchronized-statement:
6088 /// @synchronized '(' expression ')' compound-statement
6089 /// \endverbatim
6090 ///
6091 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
6092
6093 /// \verbatim
6094 /// objc-autoreleasepool-statement:
6095 /// @autoreleasepool compound-statement
6096 /// \endverbatim
6097 ///
6098 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
6099
6100 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
6101 /// qualifier list and builds their bitmask representation in the input
6102 /// argument.
6103 ///
6104 /// \verbatim
6105 /// objc-type-qualifiers:
6106 /// objc-type-qualifier
6107 /// objc-type-qualifiers objc-type-qualifier
6108 ///
6109 /// objc-type-qualifier:
6110 /// 'in'
6111 /// 'out'
6112 /// 'inout'
6113 /// 'oneway'
6114 /// 'bycopy's
6115 /// 'byref'
6116 /// 'nonnull'
6117 /// 'nullable'
6118 /// 'null_unspecified'
6119 /// \endverbatim
6120 ///
6121 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context);
6122
6123 /// Determine whether we are currently at the start of an Objective-C
6124 /// class message that appears to be missing the open bracket '['.
6125 bool isStartOfObjCClassMessageMissingOpenBracket();
6126
6127 ///@}
6128
6129 //
6130 //
6131 // -------------------------------------------------------------------------
6132 //
6133 //
6134
6135 /// \name OpenACC Constructs
6136 /// Implementations are in ParseOpenACC.cpp
6137 ///@{
6138
6139public:
6141
6142 /// Parse OpenACC directive on a declaration.
6143 ///
6144 /// Placeholder for now, should just ignore the directives after emitting a
6145 /// diagnostic. Eventually will be split into a few functions to parse
6146 /// different situations.
6148 ParsedAttributes &Attrs,
6149 DeclSpec::TST TagType,
6150 Decl *TagDecl);
6151
6152 // Parse OpenACC Directive on a Statement.
6154
6155private:
6156 /// Parsing OpenACC directive mode.
6157 bool OpenACCDirectiveParsing = false;
6158
6159 /// Currently parsing a situation where an OpenACC array section could be
6160 /// legal, such as a 'var-list'.
6161 bool AllowOpenACCArraySections = false;
6162
6163 /// RAII object to set reset OpenACC parsing a context where Array Sections
6164 /// are allowed.
6165 class OpenACCArraySectionRAII {
6166 Parser &P;
6167
6168 public:
6169 OpenACCArraySectionRAII(Parser &P) : P(P) {
6170 assert(!P.AllowOpenACCArraySections);
6171 P.AllowOpenACCArraySections = true;
6172 }
6173 ~OpenACCArraySectionRAII() {
6174 assert(P.AllowOpenACCArraySections);
6175 P.AllowOpenACCArraySections = false;
6176 }
6177 };
6178
6179 /// A struct to hold the information that got parsed by ParseOpenACCDirective,
6180 /// so that the callers of it can use that to construct the appropriate AST
6181 /// nodes.
6182 struct OpenACCDirectiveParseInfo {
6183 OpenACCDirectiveKind DirKind;
6184 SourceLocation StartLoc;
6185 SourceLocation DirLoc;
6186 SourceLocation LParenLoc;
6187 SourceLocation RParenLoc;
6188 SourceLocation EndLoc;
6189 SourceLocation MiscLoc;
6190 OpenACCAtomicKind AtomicKind;
6191 SmallVector<Expr *> Exprs;
6192 SmallVector<OpenACCClause *> Clauses;
6193 // TODO OpenACC: As we implement support for the Atomic, Routine, and Cache
6194 // constructs, we likely want to put that information in here as well.
6195 };
6196
6197 struct OpenACCWaitParseInfo {
6198 bool Failed = false;
6199 Expr *DevNumExpr = nullptr;
6200 SourceLocation QueuesLoc;
6201 SmallVector<Expr *> QueueIdExprs;
6202
6203 SmallVector<Expr *> getAllExprs() {
6204 SmallVector<Expr *> Out;
6205 Out.push_back(DevNumExpr);
6206 llvm::append_range(Out, QueueIdExprs);
6207 return Out;
6208 }
6209 };
6210 struct OpenACCCacheParseInfo {
6211 bool Failed = false;
6212 SourceLocation ReadOnlyLoc;
6213 SmallVector<Expr *> Vars;
6214 };
6215
6216 /// Represents the 'error' state of parsing an OpenACC Clause, and stores
6217 /// whether we can continue parsing, or should give up on the directive.
6218 enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
6219
6220 /// A type to represent the state of parsing an OpenACC Clause. Situations
6221 /// that result in an OpenACCClause pointer are a success and can continue
6222 /// parsing, however some other situations can also continue.
6223 /// FIXME: This is better represented as a std::expected when we get C++23.
6224 using OpenACCClauseParseResult =
6225 llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
6226
6227 OpenACCClauseParseResult OpenACCCanContinue();
6228 OpenACCClauseParseResult OpenACCCannotContinue();
6229 OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
6230
6231 /// Parses the OpenACC directive (the entire pragma) including the clause
6232 /// list, but does not produce the main AST node.
6233 OpenACCDirectiveParseInfo ParseOpenACCDirective();
6234 /// Helper that parses an ID Expression based on the language options.
6235 ExprResult ParseOpenACCIDExpression();
6236
6237 /// Parses the variable list for the `cache` construct.
6238 ///
6239 /// OpenACC 3.3, section 2.10:
6240 /// In C and C++, the syntax of the cache directive is:
6241 ///
6242 /// #pragma acc cache ([readonly:]var-list) new-line
6243 OpenACCCacheParseInfo ParseOpenACCCacheVarList();
6244
6245 /// Tries to parse the 'modifier-list' for a 'copy', 'copyin', 'copyout', or
6246 /// 'create' clause.
6247 OpenACCModifierKind tryParseModifierList(OpenACCClauseKind CK);
6248
6249 using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
6250
6251 /// Parses a single variable in a variable list for OpenACC.
6252 ///
6253 /// OpenACC 3.3, section 1.6:
6254 /// In this spec, a 'var' (in italics) is one of the following:
6255 /// - a variable name (a scalar, array, or composite variable name)
6256 /// - a subarray specification with subscript ranges
6257 /// - an array element
6258 /// - a member of a composite variable
6259 /// - a common block name between slashes (fortran only)
6260 OpenACCVarParseResult ParseOpenACCVar(OpenACCDirectiveKind DK,
6262
6263 /// Parses the variable list for the variety of places that take a var-list.
6264 llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCDirectiveKind DK,
6266
6267 /// Parses any parameters for an OpenACC Clause, including required/optional
6268 /// parens.
6269 ///
6270 /// The OpenACC Clause List is a comma or space-delimited list of clauses (see
6271 /// the comment on ParseOpenACCClauseList). The concept of a 'clause' doesn't
6272 /// really have its owner grammar and each individual one has its own
6273 /// definition. However, they all are named with a single-identifier (or
6274 /// auto/default!) token, followed in some cases by either braces or parens.
6275 OpenACCClauseParseResult
6276 ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
6278 SourceLocation ClauseLoc);
6279
6280 /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
6281 /// error.
6282 OpenACCClauseParseResult
6283 ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
6284 OpenACCDirectiveKind DirKind);
6285
6286 /// Parses the clause-list for an OpenACC directive.
6287 ///
6288 /// OpenACC 3.3, section 1.7:
6289 /// To simplify the specification and convey appropriate constraint
6290 /// information, a pqr-list is a comma-separated list of pdr items. The one
6291 /// exception is a clause-list, which is a list of one or more clauses
6292 /// optionally separated by commas.
6293 SmallVector<OpenACCClause *>
6294 ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
6295
6296 /// OpenACC 3.3, section 2.16:
6297 /// In this section and throughout the specification, the term wait-argument
6298 /// means:
6299 /// \verbatim
6300 /// [ devnum : int-expr : ] [ queues : ] async-argument-list
6301 /// \endverbatim
6302 OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
6303 bool IsDirective);
6304
6305 /// Parses the clause of the 'bind' argument, which can be a string literal or
6306 /// an identifier.
6307 std::variant<std::monostate, StringLiteral *, IdentifierInfo *>
6308 ParseOpenACCBindClauseArgument();
6309
6310 /// A type to represent the state of parsing after an attempt to parse an
6311 /// OpenACC int-expr. This is useful to determine whether an int-expr list can
6312 /// continue parsing after a failed int-expr.
6313 using OpenACCIntExprParseResult =
6314 std::pair<ExprResult, OpenACCParseCanContinue>;
6315 /// Parses the clause kind of 'int-expr', which can be any integral
6316 /// expression.
6317 OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
6319 SourceLocation Loc);
6320 /// Parses the argument list for 'num_gangs', which allows up to 3
6321 /// 'int-expr's.
6322 bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
6323 SourceLocation Loc,
6324 llvm::SmallVectorImpl<Expr *> &IntExprs);
6325
6326 /// Parses the 'device-type-list', which is a list of identifiers.
6327 ///
6328 /// OpenACC 3.3 Section 2.4:
6329 /// The argument to the device_type clause is a comma-separated list of one or
6330 /// more device architecture name identifiers, or an asterisk.
6331 ///
6332 /// The syntax of the device_type clause is
6333 /// device_type( * )
6334 /// device_type( device-type-list )
6335 ///
6336 /// The device_type clause may be abbreviated to dtype.
6337 bool ParseOpenACCDeviceTypeList(llvm::SmallVector<IdentifierLoc> &Archs);
6338
6339 /// Parses the 'async-argument', which is an integral value with two
6340 /// 'special' values that are likely negative (but come from Macros).
6341 ///
6342 /// OpenACC 3.3 section 2.16:
6343 /// In this section and throughout the specification, the term async-argument
6344 /// means a nonnegative scalar integer expression (int for C or C++, integer
6345 /// for Fortran), or one of the special values acc_async_noval or
6346 /// acc_async_sync, as defined in the C header file and the Fortran openacc
6347 /// module. The special values are negative values, so as not to conflict with
6348 /// a user-specified nonnegative async-argument.
6349 OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
6351 SourceLocation Loc);
6352
6353 /// Parses the 'size-expr', which is an integral value, or an asterisk.
6354 /// Asterisk is represented by a OpenACCAsteriskSizeExpr
6355 ///
6356 /// OpenACC 3.3 Section 2.9:
6357 /// size-expr is one of:
6358 /// *
6359 /// int-expr
6360 /// Note that this is specified under 'gang-arg-list', but also applies to
6361 /// 'tile' via reference.
6362 ExprResult ParseOpenACCSizeExpr(OpenACCClauseKind CK);
6363
6364 /// Parses a comma delimited list of 'size-expr's.
6365 bool ParseOpenACCSizeExprList(OpenACCClauseKind CK,
6366 llvm::SmallVectorImpl<Expr *> &SizeExprs);
6367
6368 /// Parses a 'gang-arg-list', used for the 'gang' clause.
6369 ///
6370 /// OpenACC 3.3 Section 2.9:
6371 ///
6372 /// where gang-arg is one of:
6373 /// \verbatim
6374 /// [num:]int-expr
6375 /// dim:int-expr
6376 /// static:size-expr
6377 /// \endverbatim
6378 bool ParseOpenACCGangArgList(SourceLocation GangLoc,
6379 llvm::SmallVectorImpl<OpenACCGangKind> &GKs,
6380 llvm::SmallVectorImpl<Expr *> &IntExprs);
6381
6382 using OpenACCGangArgRes = std::pair<OpenACCGangKind, ExprResult>;
6383 /// Parses a 'gang-arg', used for the 'gang' clause. Returns a pair of the
6384 /// ExprResult (which contains the validity of the expression), plus the gang
6385 /// kind for the current argument.
6386 OpenACCGangArgRes ParseOpenACCGangArg(SourceLocation GangLoc);
6387 /// Parses a 'condition' expr, ensuring it results in a
6388 ExprResult ParseOpenACCConditionExpr();
6390 ParseOpenACCAfterRoutineDecl(AccessSpecifier &AS, ParsedAttributes &Attrs,
6391 DeclSpec::TST TagType, Decl *TagDecl,
6392 OpenACCDirectiveParseInfo &DirInfo);
6393 StmtResult ParseOpenACCAfterRoutineStmt(OpenACCDirectiveParseInfo &DirInfo);
6394
6395 ///@}
6396
6397 //
6398 //
6399 // -------------------------------------------------------------------------
6400 //
6401 //
6402
6403 /// \name OpenMP Constructs
6404 /// Implementations are in ParseOpenMP.cpp
6405 ///@{
6406
6407private:
6409
6410 /// Parsing OpenMP directive mode.
6411 bool OpenMPDirectiveParsing = false;
6412
6413 /// Current kind of OpenMP clause
6414 OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
6415
6416 void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
6417 // If parsing the attributes found an OpenMP directive, emit those tokens
6418 // to the parse stream now.
6419 if (!OpenMPTokens.empty()) {
6420 PP.EnterToken(Tok, /*IsReinject*/ true);
6421 PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
6422 /*IsReinject*/ true);
6423 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
6424 }
6425 }
6426
6427 //===--------------------------------------------------------------------===//
6428 // OpenMP: Directives and clauses.
6429
6430 /// Parse clauses for '#pragma omp declare simd'.
6431 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
6432 CachedTokens &Toks,
6433 SourceLocation Loc);
6434
6435 /// Parse a property kind into \p TIProperty for the selector set \p Set and
6436 /// selector \p Selector.
6437 void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
6438 llvm::omp::TraitSet Set,
6439 llvm::omp::TraitSelector Selector,
6440 llvm::StringMap<SourceLocation> &Seen);
6441
6442 /// Parse a selector kind into \p TISelector for the selector set \p Set.
6443 void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
6444 llvm::omp::TraitSet Set,
6445 llvm::StringMap<SourceLocation> &Seen);
6446
6447 /// Parse a selector set kind into \p TISet.
6448 void parseOMPTraitSetKind(OMPTraitSet &TISet,
6449 llvm::StringMap<SourceLocation> &Seen);
6450
6451 /// Parses an OpenMP context property.
6452 void parseOMPContextProperty(OMPTraitSelector &TISelector,
6453 llvm::omp::TraitSet Set,
6454 llvm::StringMap<SourceLocation> &Seen);
6455
6456 /// Parses an OpenMP context selector.
6457 ///
6458 /// \verbatim
6459 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
6460 /// \endverbatim
6461 void parseOMPContextSelector(OMPTraitSelector &TISelector,
6462 llvm::omp::TraitSet Set,
6463 llvm::StringMap<SourceLocation> &SeenSelectors);
6464
6465 /// Parses an OpenMP context selector set.
6466 ///
6467 /// \verbatim
6468 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
6469 /// \endverbatim
6470 void parseOMPContextSelectorSet(OMPTraitSet &TISet,
6471 llvm::StringMap<SourceLocation> &SeenSets);
6472
6473 /// Parse OpenMP context selectors:
6474 ///
6475 /// \verbatim
6476 /// <trait-set-selector> [, <trait-set-selector>]*
6477 /// \endverbatim
6478 bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
6479
6480 /// Parse an 'append_args' clause for '#pragma omp declare variant'.
6481 bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
6482
6483 /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
6484 /// if there was an error.
6485 bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
6486 OMPTraitInfo *ParentTI);
6487
6488 /// Parse clauses for '#pragma omp declare variant ( variant-func-id )
6489 /// clause'.
6490 void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
6491 SourceLocation Loc);
6492
6493 /// Parse 'omp [begin] assume[s]' directive.
6494 ///
6495 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
6496 /// where
6497 ///
6498 /// \verbatim
6499 /// clause:
6500 /// 'ext_IMPL_DEFINED'
6501 /// 'absent' '(' directive-name [, directive-name]* ')'
6502 /// 'contains' '(' directive-name [, directive-name]* ')'
6503 /// 'holds' '(' scalar-expression ')'
6504 /// 'no_openmp'
6505 /// 'no_openmp_routines'
6506 /// 'no_openmp_constructs' (OpenMP 6.0)
6507 /// 'no_parallelism'
6508 /// \endverbatim
6509 ///
6510 void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
6511 SourceLocation Loc);
6512
6513 /// Parse 'omp end assumes' directive.
6514 void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
6515
6516 /// Parses clauses for directive.
6517 ///
6518 /// \verbatim
6519 /// <clause> [clause[ [,] clause] ... ]
6520 ///
6521 /// clauses: for error directive
6522 /// 'at' '(' compilation | execution ')'
6523 /// 'severity' '(' fatal | warning ')'
6524 /// 'message' '(' msg-string ')'
6525 /// ....
6526 /// \endverbatim
6527 ///
6528 /// \param DKind Kind of current directive.
6529 /// \param clauses for current directive.
6530 /// \param start location for clauses of current directive
6531 void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
6532 SmallVectorImpl<clang::OMPClause *> &Clauses,
6533 SourceLocation Loc);
6534
6535 /// Parse clauses for '#pragma omp [begin] declare target'.
6536 void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
6537
6538 /// Parse '#pragma omp end declare target'.
6539 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
6540 OpenMPDirectiveKind EndDKind,
6541 SourceLocation Loc);
6542
6543 /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
6544 /// it is not the current token.
6545 void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
6546
6547 /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
6548 /// that the "end" matching the "begin" directive of kind \p BeginKind was not
6549 /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
6550 /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
6551 void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
6552 OpenMPDirectiveKind ExpectedKind,
6553 OpenMPDirectiveKind FoundKind,
6554 SourceLocation MatchingLoc, SourceLocation FoundLoc,
6555 bool SkipUntilOpenMPEnd);
6556
6557 /// Parses declarative OpenMP directives.
6558 ///
6559 /// \verbatim
6560 /// threadprivate-directive:
6561 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6562 /// annot_pragma_openmp_end
6563 ///
6564 /// allocate-directive:
6565 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
6566 /// annot_pragma_openmp_end
6567 ///
6568 /// declare-reduction-directive:
6569 /// annot_pragma_openmp 'declare' 'reduction' [...]
6570 /// annot_pragma_openmp_end
6571 ///
6572 /// declare-mapper-directive:
6573 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6574 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6575 /// annot_pragma_openmp_end
6576 ///
6577 /// declare-simd-directive:
6578 /// annot_pragma_openmp 'declare simd' {<clause> [,]}
6579 /// annot_pragma_openmp_end
6580 /// <function declaration/definition>
6581 ///
6582 /// requires directive:
6583 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
6584 /// annot_pragma_openmp_end
6585 ///
6586 /// assumes directive:
6587 /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
6588 /// annot_pragma_openmp_end
6589 /// or
6590 /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
6591 /// annot_pragma_openmp 'end assumes'
6592 /// annot_pragma_openmp_end
6593 /// \endverbatim
6594 ///
6595 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
6596 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
6598 Decl *TagDecl = nullptr);
6599
6600 /// Parse 'omp declare reduction' construct.
6601 ///
6602 /// \verbatim
6603 /// declare-reduction-directive:
6604 /// annot_pragma_openmp 'declare' 'reduction'
6605 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
6606 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
6607 /// annot_pragma_openmp_end
6608 /// \endverbatim
6609 /// <reduction_id> is either a base language identifier or one of the
6610 /// following operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
6611 ///
6612 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
6613
6614 /// Parses initializer for provided omp_priv declaration inside the reduction
6615 /// initializer.
6616 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
6617
6618 /// Parses 'omp declare mapper' directive.
6619 ///
6620 /// \verbatim
6621 /// declare-mapper-directive:
6622 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
6623 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6624 /// annot_pragma_openmp_end
6625 /// \endverbatim
6626 /// <mapper-identifier> and <var> are base language identifiers.
6627 ///
6628 DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
6629
6630 /// Parses variable declaration in 'omp declare mapper' directive.
6631 TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
6632 DeclarationName &Name,
6633 AccessSpecifier AS = AS_none);
6634
6635 /// Parses simple list of variables.
6636 ///
6637 /// \verbatim
6638 /// simple-variable-list:
6639 /// '(' id-expression {, id-expression} ')'
6640 /// \endverbatim
6641 ///
6642 /// \param Kind Kind of the directive.
6643 /// \param Callback Callback function to be called for the list elements.
6644 /// \param AllowScopeSpecifier true, if the variables can have fully
6645 /// qualified names.
6646 ///
6647 bool ParseOpenMPSimpleVarList(
6648 OpenMPDirectiveKind Kind,
6649 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
6650 &Callback,
6651 bool AllowScopeSpecifier);
6652
6653 /// Parses declarative or executable directive.
6654 ///
6655 /// \verbatim
6656 /// threadprivate-directive:
6657 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6658 /// annot_pragma_openmp_end
6659 ///
6660 /// allocate-directive:
6661 /// annot_pragma_openmp 'allocate' simple-variable-list
6662 /// annot_pragma_openmp_end
6663 ///
6664 /// declare-reduction-directive:
6665 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
6666 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
6667 /// ('omp_priv' '=' <expression>|<function_call>) ')']
6668 /// annot_pragma_openmp_end
6669 ///
6670 /// declare-mapper-directive:
6671 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6672 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6673 /// annot_pragma_openmp_end
6674 ///
6675 /// executable-directive:
6676 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
6677 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
6678 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task'
6679 /// | 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' |
6680 /// 'error' | 'atomic' | 'for simd' | 'parallel for simd' | 'target' |
6681 /// 'target data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop
6682 /// simd' | 'master taskloop' | 'master taskloop simd' | 'parallel
6683 /// master taskloop' | 'parallel master taskloop simd' | 'distribute'
6684 /// | 'target enter data' | 'target exit data' | 'target parallel' |
6685 /// 'target parallel for' | 'target update' | 'distribute parallel
6686 /// for' | 'distribute paralle for simd' | 'distribute simd' | 'target
6687 /// parallel for simd' | 'target simd' | 'teams distribute' | 'teams
6688 /// distribute simd' | 'teams distribute parallel for simd' | 'teams
6689 /// distribute parallel for' | 'target teams' | 'target teams
6690 /// distribute' | 'target teams distribute parallel for' | 'target
6691 /// teams distribute parallel for simd' | 'target teams distribute
6692 /// simd' | 'masked' | 'parallel masked' {clause}
6693 /// annot_pragma_openmp_end
6694 /// \endverbatim
6695 ///
6696 ///
6697 /// \param StmtCtx The context in which we're parsing the directive.
6698 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6699 /// metadirective and therefore ends on the closing paren.
6700 StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
6701 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
6702
6703 /// Parses executable directive.
6704 ///
6705 /// \param StmtCtx The context in which we're parsing the directive.
6706 /// \param DKind The kind of the executable directive.
6707 /// \param Loc Source location of the beginning of the directive.
6708 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6709 /// metadirective and therefore ends on the closing paren.
6710 StmtResult
6711 ParseOpenMPExecutableDirective(ParsedStmtContext StmtCtx,
6712 OpenMPDirectiveKind DKind, SourceLocation Loc,
6713 bool ReadDirectiveWithinMetadirective);
6714
6715 /// Parses informational directive.
6716 ///
6717 /// \param StmtCtx The context in which we're parsing the directive.
6718 /// \param DKind The kind of the informational directive.
6719 /// \param Loc Source location of the beginning of the directive.
6720 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6721 /// metadirective and therefore ends on the closing paren.
6722 StmtResult ParseOpenMPInformationalDirective(
6723 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
6724 bool ReadDirectiveWithinMetadirective);
6725
6726 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
6727 ///
6728 /// \verbatim
6729 /// clause:
6730 /// if-clause | final-clause | num_threads-clause | safelen-clause |
6731 /// default-clause | private-clause | firstprivate-clause |
6732 /// shared-clause | linear-clause | aligned-clause | collapse-clause |
6733 /// bind-clause | lastprivate-clause | reduction-clause |
6734 /// proc_bind-clause | schedule-clause | copyin-clause |
6735 /// copyprivate-clause | untied-clause | mergeable-clause | flush-clause
6736 /// | read-clause | write-clause | update-clause | capture-clause |
6737 /// seq_cst-clause | device-clause | simdlen-clause | threads-clause |
6738 /// simd-clause | num_teams-clause | thread_limit-clause |
6739 /// priority-clause | grainsize-clause | nogroup-clause |
6740 /// num_tasks-clause | hint-clause | to-clause | from-clause |
6741 /// is_device_ptr-clause | task_reduction-clause | in_reduction-clause |
6742 /// allocator-clause | allocate-clause | acq_rel-clause | acquire-clause
6743 /// | release-clause | relaxed-clause | depobj-clause | destroy-clause |
6744 /// detach-clause | inclusive-clause | exclusive-clause |
6745 /// uses_allocators-clause | use_device_addr-clause | has_device_addr
6746 /// \endverbatim
6747 ///
6748 /// \param DKind Kind of current directive.
6749 /// \param CKind Kind of current clause.
6750 /// \param FirstClause true, if this is the first clause of a kind \a CKind
6751 /// in current directive.
6752 ///
6753 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
6754 OpenMPClauseKind CKind, bool FirstClause);
6755
6756 /// Parses clause with a single expression of a kind \a Kind.
6757 ///
6758 /// Parsing of OpenMP clauses with single expressions like 'final',
6759 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
6760 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
6761 /// 'detach'.
6762 ///
6763 /// \verbatim
6764 /// final-clause:
6765 /// 'final' '(' expression ')'
6766 ///
6767 /// num_threads-clause:
6768 /// 'num_threads' '(' expression ')'
6769 ///
6770 /// safelen-clause:
6771 /// 'safelen' '(' expression ')'
6772 ///
6773 /// simdlen-clause:
6774 /// 'simdlen' '(' expression ')'
6775 ///
6776 /// collapse-clause:
6777 /// 'collapse' '(' expression ')'
6778 ///
6779 /// priority-clause:
6780 /// 'priority' '(' expression ')'
6781 ///
6782 /// grainsize-clause:
6783 /// 'grainsize' '(' expression ')'
6784 ///
6785 /// num_tasks-clause:
6786 /// 'num_tasks' '(' expression ')'
6787 ///
6788 /// hint-clause:
6789 /// 'hint' '(' expression ')'
6790 ///
6791 /// allocator-clause:
6792 /// 'allocator' '(' expression ')'
6793 ///
6794 /// detach-clause:
6795 /// 'detach' '(' event-handler-expression ')'
6796 ///
6797 /// align-clause
6798 /// 'align' '(' positive-integer-constant ')'
6799 ///
6800 /// holds-clause
6801 /// 'holds' '(' expression ')'
6802 /// \endverbatim
6803 ///
6804 /// \param Kind Kind of current clause.
6805 /// \param ParseOnly true to skip the clause's semantic actions and return
6806 /// nullptr.
6807 ///
6808 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly);
6809 /// Parses simple clause like 'default' or 'proc_bind' of a kind \a Kind.
6810 ///
6811 /// \verbatim
6812 /// default-clause:
6813 /// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
6814 ///
6815 /// proc_bind-clause:
6816 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')'
6817 ///
6818 /// bind-clause:
6819 /// 'bind' '(' 'teams' | 'parallel' | 'thread' ')'
6820 ///
6821 /// update-clause:
6822 /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
6823 /// 'inoutset' ')'
6824 /// \endverbatim
6825 ///
6826 /// \param Kind Kind of current clause.
6827 /// \param ParseOnly true to skip the clause's semantic actions and return
6828 /// nullptr.
6829 ///
6830 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
6831
6832 /// Parse indirect clause for '#pragma omp declare target' directive.
6833 /// 'indirect' '[' '(' invoked-by-fptr ')' ']'
6834 /// where invoked-by-fptr is a constant boolean expression that evaluates to
6835 /// true or false at compile time.
6836 /// \param ParseOnly true to skip the clause's semantic actions and return
6837 /// false;
6838 bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
6839 bool ParseOnly);
6840 /// Parses clause with a single expression and an additional argument
6841 /// of a kind \a Kind like 'schedule' or 'dist_schedule'.
6842 ///
6843 /// \verbatim
6844 /// schedule-clause:
6845 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
6846 /// ')'
6847 ///
6848 /// if-clause:
6849 /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
6850 ///
6851 /// defaultmap:
6852 /// 'defaultmap' '(' modifier [ ':' kind ] ')'
6853 ///
6854 /// device-clause:
6855 /// 'device' '(' [ device-modifier ':' ] expression ')'
6856 /// \endverbatim
6857 ///
6858 /// \param DKind Directive kind.
6859 /// \param Kind Kind of current clause.
6860 /// \param ParseOnly true to skip the clause's semantic actions and return
6861 /// nullptr.
6862 ///
6863 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
6864 OpenMPClauseKind Kind,
6865 bool ParseOnly);
6866
6867 /// Parses the 'looprange' clause of a '#pragma omp fuse' directive.
6868 OMPClause *ParseOpenMPLoopRangeClause();
6869
6870 /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
6871 OMPClause *ParseOpenMPSizesClause();
6872
6873 /// Parses the 'counts' clause of a '#pragma omp split' directive.
6874 OMPClause *ParseOpenMPCountsClause();
6875
6876 /// Parses the 'permutation' clause of a '#pragma omp interchange' directive.
6877 OMPClause *ParseOpenMPPermutationClause();
6878
6879 /// Parses clause without any additional arguments like 'ordered'.
6880 ///
6881 /// \verbatim
6882 /// ordered-clause:
6883 /// 'ordered'
6884 ///
6885 /// nowait-clause:
6886 /// 'nowait'
6887 ///
6888 /// untied-clause:
6889 /// 'untied'
6890 ///
6891 /// mergeable-clause:
6892 /// 'mergeable'
6893 ///
6894 /// read-clause:
6895 /// 'read'
6896 ///
6897 /// threads-clause:
6898 /// 'threads'
6899 ///
6900 /// simd-clause:
6901 /// 'simd'
6902 ///
6903 /// nogroup-clause:
6904 /// 'nogroup'
6905 /// \endverbatim
6906 ///
6907 /// \param Kind Kind of current clause.
6908 /// \param ParseOnly true to skip the clause's semantic actions and return
6909 /// nullptr.
6910 ///
6911 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
6912
6913 /// Parses clause with the list of variables of a kind \a Kind:
6914 /// 'private', 'firstprivate', 'lastprivate',
6915 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
6916 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
6917 ///
6918 /// \verbatim
6919 /// private-clause:
6920 /// 'private' '(' list ')'
6921 /// firstprivate-clause:
6922 /// 'firstprivate' '(' list ')'
6923 /// lastprivate-clause:
6924 /// 'lastprivate' '(' list ')'
6925 /// shared-clause:
6926 /// 'shared' '(' list ')'
6927 /// linear-clause:
6928 /// 'linear' '(' linear-list [ ':' linear-step ] ')'
6929 /// aligned-clause:
6930 /// 'aligned' '(' list [ ':' alignment ] ')'
6931 /// reduction-clause:
6932 /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
6933 /// task_reduction-clause:
6934 /// 'task_reduction' '(' reduction-identifier ':' list ')'
6935 /// in_reduction-clause:
6936 /// 'in_reduction' '(' reduction-identifier ':' list ')'
6937 /// copyprivate-clause:
6938 /// 'copyprivate' '(' list ')'
6939 /// flush-clause:
6940 /// 'flush' '(' list ')'
6941 /// depend-clause:
6942 /// 'depend' '(' in | out | inout : list | source ')'
6943 /// map-clause:
6944 /// 'map' '(' [ [ always [,] ] [ close [,] ]
6945 /// [ mapper '(' mapper-identifier ')' [,] ]
6946 /// to | from | tofrom | alloc | release | delete ':' ] list ')';
6947 /// to-clause:
6948 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6949 /// from-clause:
6950 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6951 /// use_device_ptr-clause:
6952 /// 'use_device_ptr' '(' list ')'
6953 /// use_device_addr-clause:
6954 /// 'use_device_addr' '(' list ')'
6955 /// is_device_ptr-clause:
6956 /// 'is_device_ptr' '(' list ')'
6957 /// has_device_addr-clause:
6958 /// 'has_device_addr' '(' list ')'
6959 /// allocate-clause:
6960 /// 'allocate' '(' [ allocator ':' ] list ')'
6961 /// As of OpenMP 5.1 there's also
6962 /// 'allocate' '(' allocate-modifier: list ')'
6963 /// where allocate-modifier is: 'allocator' '(' allocator ')'
6964 /// nontemporal-clause:
6965 /// 'nontemporal' '(' list ')'
6966 /// inclusive-clause:
6967 /// 'inclusive' '(' list ')'
6968 /// exclusive-clause:
6969 /// 'exclusive' '(' list ')'
6970 /// \endverbatim
6971 ///
6972 /// For 'linear' clause linear-list may have the following forms:
6973 /// list
6974 /// modifier(list)
6975 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
6976 ///
6977 /// \param Kind Kind of current clause.
6978 /// \param ParseOnly true to skip the clause's semantic actions and return
6979 /// nullptr.
6980 ///
6981 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
6982 OpenMPClauseKind Kind, bool ParseOnly);
6983
6984 /// Parses a clause consisting of a list of expressions.
6985 ///
6986 /// \param Kind The clause to parse.
6987 /// \param ClauseNameLoc [out] The location of the clause name.
6988 /// \param OpenLoc [out] The location of '('.
6989 /// \param CloseLoc [out] The location of ')'.
6990 /// \param Exprs [out] The parsed expressions.
6991 /// \param ReqIntConst If true, each expression must be an integer constant.
6992 ///
6993 /// \return Whether the clause was parsed successfully.
6994 bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
6995 SourceLocation &ClauseNameLoc,
6996 SourceLocation &OpenLoc,
6997 SourceLocation &CloseLoc,
6998 SmallVectorImpl<Expr *> &Exprs,
6999 bool ReqIntConst = false);
7000
7001 /// Parses simple expression in parens for single-expression clauses of OpenMP
7002 /// constructs.
7003 /// \verbatim
7004 /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
7005 /// <range-specification> }+ ')'
7006 /// \endverbatim
7007 ExprResult ParseOpenMPIteratorsExpr();
7008
7009 /// Parses allocators and traits in the context of the uses_allocator clause.
7010 /// Expected format:
7011 /// \verbatim
7012 /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
7013 /// \endverbatim
7014 OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
7015
7016 /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
7017 bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
7018
7019 /// Parses 'fr(<foreign-runtime-id>)'.
7020 ExprResult ParseOMPInteropFrSelector();
7021
7022 /// Parses 'attr(<string-literal>[, ...])', appending to \p Attrs.
7023 bool ParseOMPInteropAttrSelector(SmallVectorImpl<Expr *> &Attrs);
7024
7025 /// Parses clause with an interop variable of kind \a Kind.
7026 ///
7027 /// \verbatim
7028 /// init-clause:
7029 /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
7030 ///
7031 /// destroy-clause:
7032 /// destroy(interop-var)
7033 ///
7034 /// use-clause:
7035 /// use(interop-var)
7036 ///
7037 /// interop-modifier:
7038 /// prefer_type(preference-list)
7039 ///
7040 /// preference-list:
7041 /// foreign-runtime-id [, foreign-runtime-id]...
7042 ///
7043 /// foreign-runtime-id:
7044 /// <string-literal> | <constant-integral-expression>
7045 ///
7046 /// interop-type:
7047 /// target | targetsync
7048 /// \endverbatim
7049 ///
7050 /// \param Kind Kind of current clause.
7051 /// \param ParseOnly true to skip the clause's semantic actions and return
7052 /// nullptr.
7053 //
7054 OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
7055
7056 /// Parses a ompx_attribute clause
7057 ///
7058 /// \param ParseOnly true to skip the clause's semantic actions and return
7059 /// nullptr.
7060 //
7061 OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
7062
7063public:
7064 /// Parses simple expression in parens for single-expression clauses of OpenMP
7065 /// constructs.
7066 /// \param RLoc Returned location of right paren.
7067 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
7068 bool IsAddressOfOperand = false);
7069
7070 /// Parses a reserved locator like 'omp_all_memory'.
7072 SemaOpenMP::OpenMPVarListDataTy &Data,
7073 const LangOptions &LangOpts);
7074 /// Parses clauses with list.
7075 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
7076 SmallVectorImpl<Expr *> &Vars,
7077 SemaOpenMP::OpenMPVarListDataTy &Data);
7078
7079 /// Parses the mapper modifier in map, to, and from clauses.
7080 bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
7081
7082 /// Parse map-type-modifiers in map clause.
7083 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list)
7084 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
7085 /// present
7086 /// where, map-type ::= alloc | delete | from | release | to | tofrom
7087 bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
7088
7089 /// Parses 'omp begin declare variant' directive.
7090 /// The syntax is:
7091 /// \verbatim
7092 /// { #pragma omp begin declare variant clause }
7093 /// <function-declaration-or-definition-sequence>
7094 /// { #pragma omp end declare variant }
7095 /// \endverbatim
7096 ///
7097 bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc);
7098
7099 ///@}
7100
7101 //
7102 //
7103 // -------------------------------------------------------------------------
7104 //
7105 //
7106
7107 /// \name Pragmas
7108 /// Implementations are in ParsePragma.cpp
7109 ///@{
7110
7111private:
7112 std::unique_ptr<PragmaHandler> AlignHandler;
7113 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
7114 std::unique_ptr<PragmaHandler> OptionsHandler;
7115 std::unique_ptr<PragmaHandler> PackHandler;
7116 std::unique_ptr<PragmaHandler> MSStructHandler;
7117 std::unique_ptr<PragmaHandler> UnusedHandler;
7118 std::unique_ptr<PragmaHandler> WeakHandler;
7119 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
7120 std::unique_ptr<PragmaHandler> FPContractHandler;
7121 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
7122 std::unique_ptr<PragmaHandler> OpenMPHandler;
7123 std::unique_ptr<PragmaHandler> OpenACCHandler;
7124 std::unique_ptr<PragmaHandler> PCSectionHandler;
7125 std::unique_ptr<PragmaHandler> MSCommentHandler;
7126 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
7127 std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
7128 std::unique_ptr<PragmaHandler> FloatControlHandler;
7129 std::unique_ptr<PragmaHandler> MSPointersToMembers;
7130 std::unique_ptr<PragmaHandler> MSVtorDisp;
7131 std::unique_ptr<PragmaHandler> MSInitSeg;
7132 std::unique_ptr<PragmaHandler> MSDataSeg;
7133 std::unique_ptr<PragmaHandler> MSBSSSeg;
7134 std::unique_ptr<PragmaHandler> MSConstSeg;
7135 std::unique_ptr<PragmaHandler> MSCodeSeg;
7136 std::unique_ptr<PragmaHandler> MSSection;
7137 std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
7138 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
7139 std::unique_ptr<PragmaHandler> MSIntrinsic;
7140 std::unique_ptr<PragmaHandler> MSFunction;
7141 std::unique_ptr<PragmaHandler> MSOptimize;
7142 std::unique_ptr<PragmaHandler> MSFenvAccess;
7143 std::unique_ptr<PragmaHandler> MSAllocText;
7144 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
7145 std::unique_ptr<PragmaHandler> OptimizeHandler;
7146 std::unique_ptr<PragmaHandler> LoopHintHandler;
7147 std::unique_ptr<PragmaHandler> UnrollHintHandler;
7148 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
7149 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
7150 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
7151 std::unique_ptr<PragmaHandler> FPHandler;
7152 std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
7153 std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
7154 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
7155 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
7156 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
7157 std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
7158 std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
7159 std::unique_ptr<PragmaHandler> ExportHandler;
7160 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
7161
7162 /// Initialize all pragma handlers.
7163 void initializePragmaHandlers();
7164
7165 /// Destroy and reset all pragma handlers.
7166 void resetPragmaHandlers();
7167
7168 /// Handle the annotation token produced for #pragma unused(...)
7169 ///
7170 /// Each annot_pragma_unused is followed by the argument token so e.g.
7171 /// "#pragma unused(x,y)" becomes:
7172 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
7173 void HandlePragmaUnused();
7174
7175 /// Handle the annotation token produced for
7176 /// #pragma GCC visibility...
7177 void HandlePragmaVisibility();
7178
7179 /// Handle the annotation token produced for
7180 /// #pragma pack...
7181 void HandlePragmaPack();
7182
7183 /// Handle the annotation token produced for
7184 /// #pragma ms_struct...
7185 void HandlePragmaMSStruct();
7186
7187 void HandlePragmaMSPointersToMembers();
7188
7189 void HandlePragmaMSVtorDisp();
7190
7191 void HandlePragmaMSPragma();
7192 bool HandlePragmaMSSection(StringRef PragmaName,
7193 SourceLocation PragmaLocation);
7194 bool HandlePragmaMSSegment(StringRef PragmaName,
7195 SourceLocation PragmaLocation);
7196
7197 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
7198 bool HandlePragmaMSInitSeg(StringRef PragmaName,
7199 SourceLocation PragmaLocation);
7200
7201 // #pragma strict_gs_check(pop)
7202 // #pragma strict_gs_check(push, "on" | "off")
7203 // #pragma strict_gs_check("on" | "off")
7204 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
7205 SourceLocation PragmaLocation);
7206 bool HandlePragmaMSFunction(StringRef PragmaName,
7207 SourceLocation PragmaLocation);
7208 bool HandlePragmaMSAllocText(StringRef PragmaName,
7209 SourceLocation PragmaLocation);
7210
7211 // #pragma optimize("gsty", on|off)
7212 bool HandlePragmaMSOptimize(StringRef PragmaName,
7213 SourceLocation PragmaLocation);
7214
7215 // #pragma intrinsic("foo")
7216 bool HandlePragmaMSIntrinsic(StringRef PragmaName,
7217 SourceLocation PragmaLocation);
7218
7219 /// Handle the annotation token produced for
7220 /// #pragma align...
7221 void HandlePragmaAlign();
7222
7223 /// Handle the annotation token produced for
7224 /// #pragma clang __debug dump...
7225 void HandlePragmaDump();
7226
7227 /// Handle the annotation token produced for
7228 /// #pragma weak id...
7229 void HandlePragmaWeak();
7230
7231 /// Handle the annotation token produced for
7232 /// #pragma weak id = id...
7233 void HandlePragmaWeakAlias();
7234
7235 /// Handle the annotation token produced for
7236 /// #pragma redefine_extname...
7237 void HandlePragmaRedefineExtname();
7238
7239 /// Handle the annotation token produced for
7240 /// #pragma STDC FP_CONTRACT...
7241 void HandlePragmaFPContract();
7242
7243 /// Handle the annotation token produced for
7244 /// #pragma STDC FENV_ACCESS...
7245 void HandlePragmaFEnvAccess();
7246
7247 /// Handle the annotation token produced for
7248 /// #pragma STDC FENV_ROUND...
7249 void HandlePragmaFEnvRound();
7250
7251 /// Handle the annotation token produced for
7252 /// #pragma STDC CX_LIMITED_RANGE...
7253 void HandlePragmaCXLimitedRange();
7254
7255 /// Handle the annotation token produced for
7256 /// #pragma float_control
7257 void HandlePragmaFloatControl();
7258
7259 /// \brief Handle the annotation token produced for
7260 /// #pragma clang fp ...
7261 void HandlePragmaFP();
7262
7263 /// Handle the annotation token produced for
7264 /// #pragma OPENCL EXTENSION...
7265 void HandlePragmaOpenCLExtension();
7266
7267 /// Handle the annotation token produced for
7268 /// #pragma clang __debug captured
7269 StmtResult HandlePragmaCaptured();
7270
7271 /// Handle the annotation token produced for
7272 /// #pragma clang loop and #pragma unroll.
7273 bool HandlePragmaLoopHint(LoopHint &Hint);
7274
7275 bool ParsePragmaAttributeSubjectMatchRuleSet(
7276 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
7277 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
7278
7279 void HandlePragmaAttribute();
7280
7281 void zOSHandlePragmaHelper(tok::TokenKind);
7282
7283 /// Handle the annotation token produced for
7284 /// #pragma export ...
7285 void HandlePragmaExport();
7286
7287 ///@}
7288
7289 //
7290 //
7291 // -------------------------------------------------------------------------
7292 //
7293 //
7294
7295 /// \name Statements
7296 /// Implementations are in ParseStmt.cpp
7297 ///@{
7298
7299public:
7300 /// A SmallVector of statements.
7302
7303 /// The location of the first statement inside an else that might
7304 /// have a missleading indentation. If there is no
7305 /// MisleadingIndentationChecker on an else active, this location is invalid.
7307
7308 private:
7309
7310 /// Flags describing a context in which we're parsing a statement.
7311 enum class ParsedStmtContext {
7312 /// This context permits declarations in language modes where declarations
7313 /// are not statements.
7314 AllowDeclarationsInC = 0x1,
7315 /// This context permits standalone OpenMP directives.
7316 AllowStandaloneOpenMPDirectives = 0x2,
7317 /// This context is at the top level of a GNU statement expression.
7318 InStmtExpr = 0x4,
7319
7320 /// The context of a regular substatement.
7321 SubStmt = 0,
7322 /// The context of a compound-statement.
7323 Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
7324
7325 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
7326 };
7327
7328 /// Act on an expression statement that might be the last statement in a
7329 /// GNU statement expression. Checks whether we are actually at the end of
7330 /// a statement expression and builds a suitable expression statement.
7331 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
7332
7333 //===--------------------------------------------------------------------===//
7334 // C99 6.8: Statements and Blocks.
7335
7336 /// Parse a standalone statement (for instance, as the body of an 'if',
7337 /// 'while', or 'for').
7339 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
7340 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt,
7341 LabelDecl *PrecedingLabel = nullptr);
7342
7343 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
7344 /// \verbatim
7345 /// StatementOrDeclaration:
7346 /// statement
7347 /// declaration
7348 ///
7349 /// statement:
7350 /// labeled-statement
7351 /// compound-statement
7352 /// expression-statement
7353 /// selection-statement
7354 /// iteration-statement
7355 /// jump-statement
7356 /// [C++] declaration-statement
7357 /// [C++] try-block
7358 /// [MS] seh-try-block
7359 /// [OBC] objc-throw-statement
7360 /// [OBC] objc-try-catch-statement
7361 /// [OBC] objc-synchronized-statement
7362 /// [GNU] asm-statement
7363 /// [OMP] openmp-construct [TODO]
7364 ///
7365 /// labeled-statement:
7366 /// identifier ':' statement
7367 /// 'case' constant-expression ':' statement
7368 /// 'default' ':' statement
7369 ///
7370 /// selection-statement:
7371 /// if-statement
7372 /// switch-statement
7373 ///
7374 /// iteration-statement:
7375 /// while-statement
7376 /// do-statement
7377 /// for-statement
7378 ///
7379 /// expression-statement:
7380 /// expression[opt] ';'
7381 ///
7382 /// jump-statement:
7383 /// 'goto' identifier ';'
7384 /// 'continue' ';'
7385 /// 'break' ';'
7386 /// 'return' expression[opt] ';'
7387 /// [GNU] 'goto' '*' expression ';'
7388 ///
7389 /// [OBC] objc-throw-statement:
7390 /// [OBC] '@' 'throw' expression ';'
7391 /// [OBC] '@' 'throw' ';'
7392 /// \endverbatim
7393 ///
7395 ParseStatementOrDeclaration(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7396 SourceLocation *TrailingElseLoc = nullptr,
7397 LabelDecl *PrecedingLabel = nullptr);
7398
7399 StmtResult ParseStatementOrDeclarationAfterAttributes(
7400 StmtVector &Stmts, ParsedStmtContext StmtCtx,
7401 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
7402 ParsedAttributes &DeclSpecAttrs, LabelDecl *PrecedingLabel);
7403
7404 /// Parse an expression statement.
7405 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
7406
7407 /// ParseLabeledStatement - We have an identifier and a ':' after it.
7408 ///
7409 /// \verbatim
7410 /// label:
7411 /// identifier ':'
7412 /// [GNU] identifier ':' attributes[opt]
7413 ///
7414 /// labeled-statement:
7415 /// label statement
7416 /// \endverbatim
7417 ///
7418 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
7419 ParsedStmtContext StmtCtx);
7420
7421 /// ParseCaseStatement
7422 /// \verbatim
7423 /// labeled-statement:
7424 /// 'case' constant-expression ':' statement
7425 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
7426 /// \endverbatim
7427 ///
7428 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
7429 bool MissingCase = false,
7431
7432 /// ParseDefaultStatement
7433 /// \verbatim
7434 /// labeled-statement:
7435 /// 'default' ':' statement
7436 /// \endverbatim
7437 /// Note that this does not parse the 'statement' at the end.
7438 ///
7439 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
7440
7441 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
7442
7443 /// ParseCompoundStatement - Parse a "{}" block.
7444 ///
7445 /// \verbatim
7446 /// compound-statement: [C99 6.8.2]
7447 /// { block-item-list[opt] }
7448 /// [GNU] { label-declarations block-item-list } [TODO]
7449 ///
7450 /// block-item-list:
7451 /// block-item
7452 /// block-item-list block-item
7453 ///
7454 /// block-item:
7455 /// declaration
7456 /// [GNU] '__extension__' declaration
7457 /// statement
7458 ///
7459 /// [GNU] label-declarations:
7460 /// [GNU] label-declaration
7461 /// [GNU] label-declarations label-declaration
7462 ///
7463 /// [GNU] label-declaration:
7464 /// [GNU] '__label__' identifier-list ';'
7465 /// \endverbatim
7466 ///
7467 StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags);
7468
7469 /// Parse any pragmas at the start of the compound expression. We handle these
7470 /// separately since some pragmas (FP_CONTRACT) must appear before any C
7471 /// statement in the compound, but may be intermingled with other pragmas.
7472 void ParseCompoundStatementLeadingPragmas();
7473
7474 void DiagnoseLabelAtEndOfCompoundStatement();
7475
7476 /// Consume any extra semi-colons resulting in null statements,
7477 /// returning true if any tok::semi were consumed.
7478 bool ConsumeNullStmt(StmtVector &Stmts);
7479
7480 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
7481 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
7482 /// the '{' to be the current token, and consume the '}' at the end of the
7483 /// block. It does not manipulate the scope stack.
7484 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
7485
7486 /// ParseParenExprOrCondition:
7487 /// \verbatim
7488 /// [C ] '(' expression ')'
7489 /// [C++] '(' condition ')'
7490 /// [C++1z] '(' init-statement[opt] condition ')'
7491 /// \endverbatim
7492 ///
7493 /// This function parses and performs error recovery on the specified
7494 /// condition or expression (depending on whether we're in C++ or C mode).
7495 /// This function goes out of its way to recover well. It returns true if
7496 /// there was a parser error (the right paren couldn't be found), which
7497 /// indicates that the caller should try to recover harder. It returns false
7498 /// if the condition is successfully parsed. Note that a successful parse can
7499 /// still have semantic errors in the condition. Additionally, it will assign
7500 /// the location of the outer-most '(' and ')', to LParenLoc and RParenLoc,
7501 /// respectively.
7502 bool ParseParenExprOrCondition(StmtResult *InitStmt,
7503 Sema::ConditionResult &CondResult,
7505 SourceLocation &LParenLoc,
7506 SourceLocation &RParenLoc);
7507
7508 /// ParseIfStatement
7509 /// \verbatim
7510 /// if-statement: [C99 6.8.4.1]
7511 /// 'if' '(' expression ')' statement
7512 /// 'if' '(' expression ')' statement 'else' statement
7513 /// [C++] 'if' '(' condition ')' statement
7514 /// [C++] 'if' '(' condition ')' statement 'else' statement
7515 /// [C++23] 'if' '!' [opt] consteval compound-statement
7516 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
7517 /// \endverbatim
7518 ///
7519 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
7520
7521 /// ParseSwitchStatement
7522 /// \verbatim
7523 /// switch-statement:
7524 /// 'switch' '(' expression ')' statement
7525 /// [C++] 'switch' '(' condition ')' statement
7526 /// \endverbatim
7527 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc,
7528 LabelDecl *PrecedingLabel);
7529
7530 /// ParseWhileStatement
7531 /// \verbatim
7532 /// while-statement: [C99 6.8.5.1]
7533 /// 'while' '(' expression ')' statement
7534 /// [C++] 'while' '(' condition ')' statement
7535 /// \endverbatim
7536 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc,
7537 LabelDecl *PrecedingLabel);
7538
7539 /// ParseDoStatement
7540 /// \verbatim
7541 /// do-statement: [C99 6.8.5.2]
7542 /// 'do' statement 'while' '(' expression ')' ';'
7543 /// \endverbatim
7544 /// Note: this lets the caller parse the end ';'.
7545 StmtResult ParseDoStatement(LabelDecl *PrecedingLabel);
7546
7547 /// ParseForStatement
7548 /// \verbatim
7549 /// for-statement: [C99 6.8.5.3]
7550 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
7551 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
7552 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
7553 /// [C++] statement
7554 /// [C++0x] 'for'
7555 /// 'co_await'[opt] [Coroutines]
7556 /// '(' for-range-declaration ':' for-range-initializer ')'
7557 /// statement
7558 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
7559 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
7560 ///
7561 /// [C++] for-init-statement:
7562 /// [C++] expression-statement
7563 /// [C++] simple-declaration
7564 /// [C++23] alias-declaration
7565 ///
7566 /// [C++0x] for-range-declaration:
7567 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
7568 /// [C++0x] for-range-initializer:
7569 /// [C++0x] expression
7570 /// [C++0x] braced-init-list [TODO]
7571 /// \endverbatim
7572 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc,
7573 LabelDecl *PrecedingLabel,
7574 CXXExpansionStmtDecl *ESD = nullptr);
7575
7576 void ParseForRangeInitializerAfterColon(ForRangeInit &FRI,
7577 ParsingDeclSpec *VarDeclSpec);
7578
7579 /// ParseGotoStatement
7580 /// \verbatim
7581 /// jump-statement:
7582 /// 'goto' identifier ';'
7583 /// [GNU] 'goto' '*' expression ';'
7584 /// \endverbatim
7585 ///
7586 /// Note: this lets the caller parse the end ';'.
7587 ///
7588 StmtResult ParseGotoStatement();
7589
7590 /// ParseContinueStatement
7591 /// \verbatim
7592 /// jump-statement:
7593 /// 'continue' ';'
7594 /// [C2y] 'continue' identifier ';'
7595 /// \endverbatim
7596 ///
7597 /// Note: this lets the caller parse the end ';'.
7598 ///
7599 StmtResult ParseContinueStatement();
7600
7601 /// ParseBreakStatement
7602 /// \verbatim
7603 /// jump-statement:
7604 /// 'break' ';'
7605 /// [C2y] 'break' identifier ';'
7606 /// \endverbatim
7607 ///
7608 /// Note: this lets the caller parse the end ';'.
7609 ///
7610 StmtResult ParseBreakStatement();
7611
7612 /// ParseReturnStatement
7613 /// \verbatim
7614 /// jump-statement:
7615 /// 'return' expression[opt] ';'
7616 /// 'return' braced-init-list ';'
7617 /// 'co_return' expression[opt] ';'
7618 /// 'co_return' braced-init-list ';'
7619 /// \endverbatim
7620 StmtResult ParseReturnStatement();
7621
7622 StmtResult ParseBreakOrContinueStatement(bool IsContinue);
7623
7624 /// ParseDeferStatement
7625 /// \verbatim
7626 /// defer-statement:
7627 /// '_Defer' deferred-block
7628 ///
7629 /// deferred-block:
7630 /// unlabeled-statement
7631 /// \endverbatim
7632 StmtResult ParseDeferStatement(SourceLocation *TrailingElseLoc);
7633
7634 /// ParseExpansionStatement - Parse a C++26 expansion
7635 /// statement ('template for').
7636 ///
7637 /// \verbatim
7638 /// expansion-statement:
7639 /// 'template' 'for' '(' init-statement[opt]
7640 /// for-range-declaration ':' expansion-initializer ')'
7641 /// compound-statement
7642 ///
7643 /// expansion-initializer:
7644 /// expression
7645 /// expansion-init-list
7646 /// \endverbatim
7647 StmtResult ParseExpansionStatement(SourceLocation *TrailingElseLoc,
7648 LabelDecl *PrecedingLabel,
7649 SourceLocation TemplateLoc);
7650
7651 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7652 SourceLocation *TrailingElseLoc,
7653 ParsedAttributes &Attrs,
7654 LabelDecl *PrecedingLabel);
7655
7656 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
7657
7658 //===--------------------------------------------------------------------===//
7659 // C++ 6: Statements and Blocks
7660
7661 /// ParseCXXTryBlock - Parse a C++ try-block.
7662 ///
7663 /// \verbatim
7664 /// try-block:
7665 /// 'try' compound-statement handler-seq
7666 /// \endverbatim
7667 ///
7668 StmtResult ParseCXXTryBlock();
7669
7670 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
7671 /// function-try-block.
7672 ///
7673 /// \verbatim
7674 /// try-block:
7675 /// 'try' compound-statement handler-seq
7676 ///
7677 /// function-try-block:
7678 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7679 ///
7680 /// handler-seq:
7681 /// handler handler-seq[opt]
7682 ///
7683 /// [Borland] try-block:
7684 /// 'try' compound-statement seh-except-block
7685 /// 'try' compound-statement seh-finally-block
7686 /// \endverbatim
7687 ///
7688 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
7689
7690 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the
7691 /// standard
7692 ///
7693 /// \verbatim
7694 /// handler:
7695 /// 'catch' '(' exception-declaration ')' compound-statement
7696 ///
7697 /// exception-declaration:
7698 /// attribute-specifier-seq[opt] type-specifier-seq declarator
7699 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
7700 /// '...'
7701 /// \endverbatim
7702 ///
7703 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
7704
7705 //===--------------------------------------------------------------------===//
7706 // MS: SEH Statements and Blocks
7707
7708 /// ParseSEHTryBlockCommon
7709 ///
7710 /// \verbatim
7711 /// seh-try-block:
7712 /// '__try' compound-statement seh-handler
7713 ///
7714 /// seh-handler:
7715 /// seh-except-block
7716 /// seh-finally-block
7717 /// \endverbatim
7718 ///
7719 StmtResult ParseSEHTryBlock();
7720
7721 /// ParseSEHExceptBlock - Handle __except
7722 ///
7723 /// \verbatim
7724 /// seh-except-block:
7725 /// '__except' '(' seh-filter-expression ')' compound-statement
7726 /// \endverbatim
7727 ///
7728 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
7729
7730 /// ParseSEHFinallyBlock - Handle __finally
7731 ///
7732 /// \verbatim
7733 /// seh-finally-block:
7734 /// '__finally' compound-statement
7735 /// \endverbatim
7736 ///
7737 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
7738
7739 StmtResult ParseSEHLeaveStatement();
7740
7741 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
7742
7743 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
7744 ///
7745 /// \verbatim
7746 /// function-try-block:
7747 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7748 /// \endverbatim
7749 ///
7750 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
7751
7752 /// ParseFunctionBody - Parse the body of a function definition. The
7753 /// '= default' and '= delete' forms are handled by the caller.
7754 ///
7755 /// \verbatim
7756 /// function-body:
7757 /// ctor-initializer[opt] compound-statement
7758 /// function-try-block
7759 /// \endverbatim
7760 ///
7761 Decl *ParseFunctionBody(Decl *D, ParseScope &BodyScope);
7762
7763 /// When in code-completion, skip parsing of the function/method body
7764 /// unless the body contains the code-completion point.
7765 ///
7766 /// \returns true if the function body was skipped.
7767 bool trySkippingFunctionBody();
7768
7769 /// isDeclarationStatement - Disambiguates between a declaration or an
7770 /// expression statement, when parsing function bodies.
7771 ///
7772 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
7773 /// this check is to disambiguate between an expression and a declaration.
7774 /// Returns true for declaration, false for expression.
7775 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
7776 if (getLangOpts().CPlusPlus)
7777 return isCXXDeclarationStatement(DisambiguatingWithExpression);
7778 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7779 }
7780
7781 /// isForInitDeclaration - Disambiguates between a declaration or an
7782 /// expression in the context of the C 'clause-1' or the C++
7783 // 'for-init-statement' part of a 'for' statement.
7784 /// Returns true for declaration, false for expression.
7785 bool isForInitDeclaration() {
7786 if (getLangOpts().OpenMP)
7787 Actions.OpenMP().startOpenMPLoop();
7788 if (getLangOpts().CPlusPlus)
7789 return Tok.is(tok::kw_using) ||
7790 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
7791 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7792 }
7793
7794 /// Determine whether this is a C++1z for-range-identifier.
7795 bool isForRangeIdentifier();
7796
7797 ///@}
7798
7799 //
7800 //
7801 // -------------------------------------------------------------------------
7802 //
7803 //
7804
7805 /// \name `inline asm` Statement
7806 /// Implementations are in ParseStmtAsm.cpp
7807 ///@{
7808
7809public:
7810 /// Parse an identifier in an MS-style inline assembly block.
7811 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
7812 unsigned &NumLineToksConsumed,
7813 bool IsUnevaluated);
7814
7815private:
7816 /// ParseAsmStatement - Parse a GNU extended asm statement.
7817 /// \verbatim
7818 /// asm-statement:
7819 /// gnu-asm-statement
7820 /// ms-asm-statement
7821 ///
7822 /// [GNU] gnu-asm-statement:
7823 /// 'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'
7824 ///
7825 /// [GNU] asm-argument:
7826 /// asm-string-literal
7827 /// asm-string-literal ':' asm-operands[opt]
7828 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7829 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7830 /// ':' asm-clobbers
7831 ///
7832 /// [GNU] asm-clobbers:
7833 /// asm-string-literal
7834 /// asm-clobbers ',' asm-string-literal
7835 /// \endverbatim
7836 ///
7837 StmtResult ParseAsmStatement(bool &msAsm);
7838
7839 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
7840 /// this routine is called to collect the tokens for an MS asm statement.
7841 ///
7842 /// \verbatim
7843 /// [MS] ms-asm-statement:
7844 /// ms-asm-block
7845 /// ms-asm-block ms-asm-statement
7846 ///
7847 /// [MS] ms-asm-block:
7848 /// '__asm' ms-asm-line '\n'
7849 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
7850 ///
7851 /// [MS] ms-asm-instruction-block
7852 /// ms-asm-line
7853 /// ms-asm-line '\n' ms-asm-instruction-block
7854 /// \endverbatim
7855 ///
7856 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
7857
7858 /// ParseAsmOperands - Parse the asm-operands production as used by
7859 /// asm-statement, assuming the leading ':' token was eaten.
7860 ///
7861 /// \verbatim
7862 /// [GNU] asm-operands:
7863 /// asm-operand
7864 /// asm-operands ',' asm-operand
7865 ///
7866 /// [GNU] asm-operand:
7867 /// asm-string-literal '(' expression ')'
7868 /// '[' identifier ']' asm-string-literal '(' expression ')'
7869 /// \endverbatim
7870 ///
7871 // FIXME: Avoid unnecessary std::string trashing.
7872 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
7873 SmallVectorImpl<Expr *> &Constraints,
7874 SmallVectorImpl<Expr *> &Exprs);
7875
7876 class GNUAsmQualifiers {
7877 unsigned Qualifiers = AQ_unspecified;
7878
7879 public:
7880 enum AQ {
7881 AQ_unspecified = 0,
7882 AQ_volatile = 1,
7883 AQ_inline = 2,
7884 AQ_goto = 4,
7885 };
7886 static const char *getQualifierName(AQ Qualifier);
7887 bool setAsmQualifier(AQ Qualifier);
7888 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
7889 inline bool isInline() const { return Qualifiers & AQ_inline; };
7890 inline bool isGoto() const { return Qualifiers & AQ_goto; }
7891 };
7892
7893 // Determine if this is a GCC-style asm statement.
7894 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
7895
7896 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
7897 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
7898
7899 /// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.
7900 /// \verbatim
7901 /// asm-qualifier:
7902 /// volatile
7903 /// inline
7904 /// goto
7905 ///
7906 /// asm-qualifier-list:
7907 /// asm-qualifier
7908 /// asm-qualifier-list asm-qualifier
7909 /// \endverbatim
7910 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
7911
7912 ///@}
7913
7914 //
7915 //
7916 // -------------------------------------------------------------------------
7917 //
7918 //
7919
7920 /// \name C++ Templates
7921 /// Implementations are in ParseTemplate.cpp
7922 ///@{
7923
7924public:
7926
7927 /// Re-enter a possible template scope, creating as many template parameter
7928 /// scopes as necessary.
7929 /// \return The number of template parameter scopes entered.
7931
7932private:
7933 /// The "depth" of the template parameters currently being parsed.
7934 unsigned TemplateParameterDepth;
7935
7936 /// RAII class that manages the template parameter depth.
7937 class TemplateParameterDepthRAII {
7938 unsigned &Depth;
7939 unsigned AddedLevels;
7940
7941 public:
7942 explicit TemplateParameterDepthRAII(unsigned &Depth)
7943 : Depth(Depth), AddedLevels(0) {}
7944
7945 ~TemplateParameterDepthRAII() { Depth -= AddedLevels; }
7946
7947 void operator++() {
7948 ++Depth;
7949 ++AddedLevels;
7950 }
7951 void addDepth(unsigned D) {
7952 Depth += D;
7953 AddedLevels += D;
7954 }
7955 void setAddedDepth(unsigned D) {
7956 Depth = Depth - AddedLevels + D;
7957 AddedLevels = D;
7958 }
7959
7960 unsigned getDepth() const { return Depth; }
7961 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
7962 };
7963
7964 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
7965 /// top-level declaration is finished.
7966 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
7967
7968 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
7969 /// we're at the end of a declaration. Instead, we defer the destruction until
7970 /// after a top-level declaration.
7971 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
7972 bool DelayTemplateIdDestruction = false;
7973
7974 void MaybeDestroyTemplateIds() {
7975 if (DelayTemplateIdDestruction)
7976 return;
7977 if (!TemplateIds.empty() &&
7978 (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
7979 DestroyTemplateIds();
7980 }
7981 void DestroyTemplateIds();
7982
7983 /// RAII object to destroy TemplateIdAnnotations where possible, from a
7984 /// likely-good position during parsing.
7985 struct DestroyTemplateIdAnnotationsRAIIObj {
7986 Parser &Self;
7987
7988 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
7989 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
7990 };
7991
7992 struct DelayTemplateIdDestructionRAII {
7993 Parser &Self;
7994 bool PrevDelayTemplateIdDestruction;
7995
7996 DelayTemplateIdDestructionRAII(Parser &Self,
7997 bool DelayTemplateIdDestruction) noexcept
7998 : Self(Self),
7999 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
8000 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
8001 }
8002
8003 ~DelayTemplateIdDestructionRAII() noexcept {
8004 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
8005 }
8006 };
8007
8008 /// Identifiers which have been declared within a tentative parse.
8009 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
8010
8011 /// Tracker for '<' tokens that might have been intended to be treated as an
8012 /// angle bracket instead of a less-than comparison.
8013 ///
8014 /// This happens when the user intends to form a template-id, but typoes the
8015 /// template-name or forgets a 'template' keyword for a dependent template
8016 /// name.
8017 ///
8018 /// We track these locations from the point where we see a '<' with a
8019 /// name-like expression on its left until we see a '>' or '>>' that might
8020 /// match it.
8021 struct AngleBracketTracker {
8022 /// Flags used to rank candidate template names when there is more than one
8023 /// '<' in a scope.
8024 enum Priority : unsigned short {
8025 /// A non-dependent name that is a potential typo for a template name.
8026 PotentialTypo = 0x0,
8027 /// A dependent name that might instantiate to a template-name.
8028 DependentName = 0x2,
8029
8030 /// A space appears before the '<' token.
8031 SpaceBeforeLess = 0x0,
8032 /// No space before the '<' token
8033 NoSpaceBeforeLess = 0x1,
8034
8035 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
8036 };
8037
8038 struct Loc {
8041 AngleBracketTracker::Priority Priority;
8043
8044 bool isActive(Parser &P) const {
8045 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
8046 P.BraceCount == BraceCount;
8047 }
8048
8049 bool isActiveOrNested(Parser &P) const {
8050 return isActive(P) || P.ParenCount > ParenCount ||
8051 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
8052 }
8053 };
8054
8056
8057 /// Add an expression that might have been intended to be a template name.
8058 /// In the case of ambiguity, we arbitrarily select the innermost such
8059 /// expression, for example in 'foo < bar < baz', 'bar' is the current
8060 /// candidate. No attempt is made to track that 'foo' is also a candidate
8061 /// for the case where we see a second suspicious '>' token.
8062 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
8063 Priority Prio) {
8064 if (!Locs.empty() && Locs.back().isActive(P)) {
8065 if (Locs.back().Priority <= Prio) {
8066 Locs.back().TemplateName = TemplateName;
8067 Locs.back().LessLoc = LessLoc;
8068 Locs.back().Priority = Prio;
8069 }
8070 } else {
8071 Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount,
8072 P.BracketCount, P.BraceCount});
8073 }
8074 }
8075
8076 /// Mark the current potential missing template location as having been
8077 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
8078 /// or leave a bracket scope).
8079 void clear(Parser &P) {
8080 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
8081 Locs.pop_back();
8082 }
8083
8084 /// Get the current enclosing expression that might hve been intended to be
8085 /// a template name.
8086 Loc *getCurrent(Parser &P) {
8087 if (!Locs.empty() && Locs.back().isActive(P))
8088 return &Locs.back();
8089 return nullptr;
8090 }
8091 };
8092
8093 AngleBracketTracker AngleBrackets;
8094
8095 /// Contains information about any template-specific
8096 /// information that has been parsed prior to parsing declaration
8097 /// specifiers.
8098 struct ParsedTemplateInfo {
8099 ParsedTemplateInfo()
8100 : Kind(ParsedTemplateKind::NonTemplate), TemplateParams(nullptr) {}
8101
8102 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
8103 bool isSpecialization,
8104 bool lastParameterListWasEmpty = false)
8105 : Kind(isSpecialization ? ParsedTemplateKind::ExplicitSpecialization
8107 TemplateParams(TemplateParams),
8108 LastParameterListWasEmpty(lastParameterListWasEmpty) {}
8109
8110 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
8111 SourceLocation TemplateLoc)
8113 TemplateParams(nullptr), ExternLoc(ExternLoc),
8114 TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false) {}
8115
8116 ParsedTemplateKind Kind;
8117
8118 /// The template parameter lists, for template declarations
8119 /// and explicit specializations.
8120 TemplateParameterLists *TemplateParams;
8121
8122 /// The location of the 'extern' keyword, if any, for an explicit
8123 /// instantiation
8124 SourceLocation ExternLoc;
8125
8126 /// The location of the 'template' keyword, for an explicit
8127 /// instantiation.
8128 SourceLocation TemplateLoc;
8129
8130 /// Whether the last template parameter list was empty.
8131 bool LastParameterListWasEmpty;
8132
8133 SourceRange getSourceRange() const LLVM_READONLY;
8134 };
8135
8136 /// Lex a delayed template function for late parsing.
8137 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
8138
8139 /// Late parse a C++ function template in Microsoft mode.
8140 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
8141
8142 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
8143
8144 /// We've parsed something that could plausibly be intended to be a template
8145 /// name (\p LHS) followed by a '<' token, and the following code can't
8146 /// possibly be an expression. Determine if this is likely to be a template-id
8147 /// and if so, diagnose it.
8148 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
8149
8150 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
8151 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
8152 const Token &OpToken);
8153 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
8154 if (auto *Info = AngleBrackets.getCurrent(*this))
8155 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
8156 return false;
8157 }
8158
8159 //===--------------------------------------------------------------------===//
8160 // C++ 14: Templates [temp]
8161
8162 /// Parse a template declaration, explicit instantiation, or
8163 /// explicit specialization.
8165 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
8166 SourceLocation &DeclEnd,
8167 ParsedAttributes &AccessAttrs);
8168
8169 /// Parse a template declaration or an explicit specialization.
8170 ///
8171 /// Template declarations include one or more template parameter lists
8172 /// and either the function or class template declaration. Explicit
8173 /// specializations contain one or more 'template < >' prefixes
8174 /// followed by a (possibly templated) declaration. Since the
8175 /// syntactic form of both features is nearly identical, we parse all
8176 /// of the template headers together and let semantic analysis sort
8177 /// the declarations from the explicit specializations.
8178 ///
8179 /// \verbatim
8180 /// template-declaration: [C++ temp]
8181 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
8182 ///
8183 /// template-declaration: [C++2a]
8184 /// template-head declaration
8185 /// template-head concept-definition
8186 ///
8187 /// TODO: requires-clause
8188 /// template-head: [C++2a]
8189 /// 'template' '<' template-parameter-list '>'
8190 /// requires-clause[opt]
8191 ///
8192 /// explicit-specialization: [ C++ temp.expl.spec]
8193 /// 'template' '<' '>' declaration
8194 /// \endverbatim
8195 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8196 DeclaratorContext Context, SourceLocation &DeclEnd,
8197 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
8198
8199 clang::Parser::DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8200 DeclaratorContext Context, SourceLocation &DeclEnd, AccessSpecifier AS);
8201
8202 /// Parse a single declaration that declares a template,
8203 /// template specialization, or explicit instantiation of a template.
8204 ///
8205 /// \param DeclEnd will receive the source location of the last token
8206 /// within this declaration.
8207 ///
8208 /// \param AS the access specifier associated with this
8209 /// declaration. Will be AS_none for namespace-scope declarations.
8210 ///
8211 /// \returns the new declaration.
8212 DeclGroupPtrTy ParseDeclarationAfterTemplate(
8213 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
8214 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
8215 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
8216
8217 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
8218 /// angle brackets. Depth is the depth of this template-parameter-list, which
8219 /// is the number of template headers directly enclosing this template header.
8220 /// TemplateParams is the current list of template parameters we're building.
8221 /// The template parameter we parse will be added to this list. LAngleLoc and
8222 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
8223 /// that enclose this template parameter list.
8224 ///
8225 /// \returns true if an error occurred, false otherwise.
8226 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
8227 SmallVectorImpl<NamedDecl *> &TemplateParams,
8228 SourceLocation &LAngleLoc,
8229 SourceLocation &RAngleLoc);
8230
8231 /// ParseTemplateParameterList - Parse a template parameter list. If
8232 /// the parsing fails badly (i.e., closing bracket was left out), this
8233 /// will try to put the token stream in a reasonable position (closing
8234 /// a statement, etc.) and return false.
8235 ///
8236 /// \verbatim
8237 /// template-parameter-list: [C++ temp]
8238 /// template-parameter
8239 /// template-parameter-list ',' template-parameter
8240 /// \endverbatim
8241 bool ParseTemplateParameterList(unsigned Depth,
8242 SmallVectorImpl<NamedDecl *> &TemplateParams);
8243
8244 enum class TPResult;
8245
8246 /// Determine whether the parser is at the start of a template
8247 /// type parameter.
8248 TPResult isStartOfTemplateTypeParameter();
8249
8250 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
8251 ///
8252 /// \verbatim
8253 /// template-parameter: [C++ temp.param]
8254 /// type-parameter
8255 /// parameter-declaration
8256 ///
8257 /// type-parameter: (See below)
8258 /// type-parameter-key ...[opt] identifier[opt]
8259 /// type-parameter-key identifier[opt] = type-id
8260 /// (C++2a) type-constraint ...[opt] identifier[opt]
8261 /// (C++2a) type-constraint identifier[opt] = type-id
8262 /// 'template' '<' template-parameter-list '>' type-parameter-key
8263 /// ...[opt] identifier[opt]
8264 /// 'template' '<' template-parameter-list '>' type-parameter-key
8265 /// identifier[opt] '=' id-expression
8266 ///
8267 /// type-parameter-key:
8268 /// class
8269 /// typename
8270 /// \endverbatim
8271 ///
8272 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
8273
8274 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
8275 /// Other kinds of template parameters are parsed in
8276 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
8277 ///
8278 /// \verbatim
8279 /// type-parameter: [C++ temp.param]
8280 /// 'class' ...[opt][C++0x] identifier[opt]
8281 /// 'class' identifier[opt] '=' type-id
8282 /// 'typename' ...[opt][C++0x] identifier[opt]
8283 /// 'typename' identifier[opt] '=' type-id
8284 /// \endverbatim
8285 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
8286
8287 /// ParseTemplateTemplateParameter - Handle the parsing of template
8288 /// template parameters.
8289 ///
8290 /// \verbatim
8291 /// type-parameter: [C++ temp.param]
8292 /// template-head type-parameter-key ...[opt] identifier[opt]
8293 /// template-head type-parameter-key identifier[opt] = id-expression
8294 /// type-parameter-key:
8295 /// 'class'
8296 /// 'typename' [C++1z]
8297 /// template-head: [C++2a]
8298 /// 'template' '<' template-parameter-list '>'
8299 /// requires-clause[opt]
8300 /// \endverbatim
8301 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
8302
8303 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
8304 /// template parameters (e.g., in "template<int Size> class array;").
8305 ///
8306 /// \verbatim
8307 /// template-parameter:
8308 /// ...
8309 /// parameter-declaration
8310 /// \endverbatim
8311 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
8312
8313 /// Check whether the current token is a template-id annotation denoting a
8314 /// type-constraint.
8315 bool isTypeConstraintAnnotation();
8316
8317 /// Try parsing a type-constraint at the current location.
8318 ///
8319 /// \verbatim
8320 /// type-constraint:
8321 /// nested-name-specifier[opt] concept-name
8322 /// nested-name-specifier[opt] concept-name
8323 /// '<' template-argument-list[opt] '>'[opt]
8324 /// \endverbatim
8325 ///
8326 /// \returns true if an error occurred, and false otherwise.
8327 bool TryAnnotateTypeConstraint();
8328
8329 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
8330 SourceLocation CorrectLoc,
8331 bool AlreadyHasEllipsis,
8332 bool IdentifierHasName);
8333 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
8334 Declarator &D);
8335 // C++ 14.3: Template arguments [temp.arg]
8336 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
8337
8338 /// Parses a '>' at the end of a template list.
8339 ///
8340 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
8341 /// to determine if these tokens were supposed to be a '>' followed by
8342 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
8343 ///
8344 /// \param RAngleLoc the location of the consumed '>'.
8345 ///
8346 /// \param ConsumeLastToken if true, the '>' is consumed.
8347 ///
8348 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
8349 /// type parameter or type argument list, rather than a C++ template parameter
8350 /// or argument list.
8351 ///
8352 /// \returns true, if current token does not start with '>', false otherwise.
8353 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
8354 SourceLocation &RAngleLoc,
8355 bool ConsumeLastToken,
8356 bool ObjCGenericList);
8357
8358 /// Parses a template-id that after the template name has
8359 /// already been parsed.
8360 ///
8361 /// This routine takes care of parsing the enclosed template argument
8362 /// list ('<' template-parameter-list [opt] '>') and placing the
8363 /// results into a form that can be transferred to semantic analysis.
8364 ///
8365 /// \param ConsumeLastToken if true, then we will consume the last
8366 /// token that forms the template-id. Otherwise, we will leave the
8367 /// last token in the stream (e.g., so that it can be replaced with an
8368 /// annotation token).
8369 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
8370 SourceLocation &LAngleLoc,
8371 TemplateArgList &TemplateArgs,
8372 SourceLocation &RAngleLoc,
8373 TemplateTy NameHint = nullptr);
8374
8375 /// Replace the tokens that form a simple-template-id with an
8376 /// annotation token containing the complete template-id.
8377 ///
8378 /// The first token in the stream must be the name of a template that
8379 /// is followed by a '<'. This routine will parse the complete
8380 /// simple-template-id and replace the tokens with a single annotation
8381 /// token with one of two different kinds: if the template-id names a
8382 /// type (and \p AllowTypeAnnotation is true), the annotation token is
8383 /// a type annotation that includes the optional nested-name-specifier
8384 /// (\p SS). Otherwise, the annotation token is a template-id
8385 /// annotation that does not include the optional
8386 /// nested-name-specifier.
8387 ///
8388 /// \param Template the declaration of the template named by the first
8389 /// token (an identifier), as returned from \c Action::isTemplateName().
8390 ///
8391 /// \param TNK the kind of template that \p Template
8392 /// refers to, as returned from \c Action::isTemplateName().
8393 ///
8394 /// \param SS if non-NULL, the nested-name-specifier that precedes
8395 /// this template name.
8396 ///
8397 /// \param TemplateKWLoc if valid, specifies that this template-id
8398 /// annotation was preceded by the 'template' keyword and gives the
8399 /// location of that keyword. If invalid (the default), then this
8400 /// template-id was not preceded by a 'template' keyword.
8401 ///
8402 /// \param AllowTypeAnnotation if true (the default), then a
8403 /// simple-template-id that refers to a class template, template
8404 /// template parameter, or other template that produces a type will be
8405 /// replaced with a type annotation token. Otherwise, the
8406 /// simple-template-id is always replaced with a template-id
8407 /// annotation token.
8408 ///
8409 /// \param TypeConstraint if true, then this is actually a type-constraint,
8410 /// meaning that the template argument list can be omitted (and the template
8411 /// in question must be a concept).
8412 ///
8413 /// If an unrecoverable parse error occurs and no annotation token can be
8414 /// formed, this function returns true.
8415 ///
8416 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
8417 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8418 UnqualifiedId &TemplateName,
8419 bool AllowTypeAnnotation = true,
8420 bool TypeConstraint = false);
8421
8422 /// Replaces a template-id annotation token with a type
8423 /// annotation token.
8424 ///
8425 /// If there was a failure when forming the type from the template-id,
8426 /// a type annotation token will still be created, but will have a
8427 /// NULL type pointer to signify an error.
8428 ///
8429 /// \param SS The scope specifier appearing before the template-id, if any.
8430 ///
8431 /// \param AllowImplicitTypename whether this is a context where T::type
8432 /// denotes a dependent type.
8433 /// \param IsClassName Is this template-id appearing in a context where we
8434 /// know it names a class, such as in an elaborated-type-specifier or
8435 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
8436 /// in those contexts.)
8437 void
8438 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
8439 ImplicitTypenameContext AllowImplicitTypename,
8440 bool IsClassName = false);
8441
8442 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
8443 /// (C++ [temp.names]). Returns true if there was an error.
8444 ///
8445 /// \verbatim
8446 /// template-argument-list: [C++ 14.2]
8447 /// template-argument
8448 /// template-argument-list ',' template-argument
8449 /// \endverbatim
8450 ///
8451 /// \param Template is only used for code completion, and may be null.
8452 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
8453 TemplateTy Template, SourceLocation OpenLoc);
8454
8455 /// Parse a C++ template template argument.
8456 ParsedTemplateArgument ParseTemplateTemplateArgument();
8457
8458 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
8459 ///
8460 /// \verbatim
8461 /// template-argument: [C++ 14.2]
8462 /// constant-expression
8463 /// type-id
8464 /// id-expression
8465 /// braced-init-list [C++26, DR]
8466 /// \endverbatim
8467 ///
8468 ParsedTemplateArgument ParseTemplateArgument();
8469
8470 /// Parse a C++ explicit template instantiation
8471 /// (C++ [temp.explicit]).
8472 ///
8473 /// \verbatim
8474 /// explicit-instantiation:
8475 /// 'extern' [opt] 'template' declaration
8476 /// \endverbatim
8477 ///
8478 /// Note that the 'extern' is a GNU extension and C++11 feature.
8479 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
8480 SourceLocation ExternLoc,
8481 SourceLocation TemplateLoc,
8482 SourceLocation &DeclEnd,
8483 ParsedAttributes &AccessAttrs,
8485
8486 /// \brief Parse a single declaration that declares a concept.
8487 ///
8488 /// \param DeclEnd will receive the source location of the last token
8489 /// within this declaration.
8490 ///
8491 /// \returns the new declaration.
8492 Decl *ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
8493 SourceLocation &DeclEnd);
8494
8495 ///@}
8496
8497 //
8498 //
8499 // -------------------------------------------------------------------------
8500 //
8501 //
8502
8503 /// \name Tentative Parsing
8504 /// Implementations are in ParseTentative.cpp
8505 ///@{
8506
8507private:
8508 /// TentativeParsingAction - An object that is used as a kind of "tentative
8509 /// parsing transaction". It gets instantiated to mark the token position and
8510 /// after the token consumption is done, Commit() or Revert() is called to
8511 /// either "commit the consumed tokens" or revert to the previously marked
8512 /// token position. Example:
8513 ///
8514 /// TentativeParsingAction TPA(*this);
8515 /// ConsumeToken();
8516 /// ....
8517 /// TPA.Revert();
8518 ///
8519 /// If the Unannotated parameter is true, any token annotations created
8520 /// during the tentative parse are reverted.
8521 class TentativeParsingAction {
8522 Parser &P;
8523 PreferredTypeBuilder PrevPreferredType;
8524 Token PrevTok;
8525 size_t PrevTentativelyDeclaredIdentifierCount;
8526 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
8527 bool isActive;
8528
8529 public:
8530 explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
8531 : P(p), PrevPreferredType(P.PreferredType) {
8532 PrevTok = P.Tok;
8533 PrevTentativelyDeclaredIdentifierCount =
8534 P.TentativelyDeclaredIdentifiers.size();
8535 PrevParenCount = P.ParenCount;
8536 PrevBracketCount = P.BracketCount;
8537 PrevBraceCount = P.BraceCount;
8538 P.PP.EnableBacktrackAtThisPos(Unannotated);
8539 isActive = true;
8540 }
8541 void Commit() {
8542 assert(isActive && "Parsing action was finished!");
8543 P.TentativelyDeclaredIdentifiers.resize(
8544 PrevTentativelyDeclaredIdentifierCount);
8545 P.PP.CommitBacktrackedTokens();
8546 isActive = false;
8547 }
8548 void Revert() {
8549 assert(isActive && "Parsing action was finished!");
8550 P.PP.Backtrack();
8551 P.PreferredType = PrevPreferredType;
8552 P.Tok = PrevTok;
8553 P.TentativelyDeclaredIdentifiers.resize(
8554 PrevTentativelyDeclaredIdentifierCount);
8555 P.ParenCount = PrevParenCount;
8556 P.BracketCount = PrevBracketCount;
8557 P.BraceCount = PrevBraceCount;
8558 isActive = false;
8559 }
8560 ~TentativeParsingAction() {
8561 assert(!isActive && "Forgot to call Commit or Revert!");
8562 }
8563 };
8564
8565 /// A TentativeParsingAction that automatically reverts in its destructor.
8566 /// Useful for disambiguation parses that will always be reverted.
8567 class RevertingTentativeParsingAction
8568 : private Parser::TentativeParsingAction {
8569 public:
8570 using TentativeParsingAction::TentativeParsingAction;
8571
8572 ~RevertingTentativeParsingAction() { Revert(); }
8573 };
8574
8575 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
8576 /// between a declaration or an expression statement, when parsing function
8577 /// bodies. Returns true for declaration, false for expression.
8578 ///
8579 /// \verbatim
8580 /// declaration-statement:
8581 /// block-declaration
8582 ///
8583 /// block-declaration:
8584 /// simple-declaration
8585 /// asm-definition
8586 /// namespace-alias-definition
8587 /// using-declaration
8588 /// using-directive
8589 /// [C++0x] static_assert-declaration
8590 ///
8591 /// asm-definition:
8592 /// 'asm' '(' string-literal ')' ';'
8593 ///
8594 /// namespace-alias-definition:
8595 /// 'namespace' identifier = qualified-namespace-specifier ';'
8596 ///
8597 /// using-declaration:
8598 /// 'using' typename[opt] '::'[opt] nested-name-specifier
8599 /// unqualified-id ';'
8600 /// 'using' '::' unqualified-id ;
8601 ///
8602 /// using-directive:
8603 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
8604 /// namespace-name ';'
8605 /// \endverbatim
8606 ///
8607 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
8608
8609 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
8610 /// between a simple-declaration or an expression-statement.
8611 /// If during the disambiguation process a parsing error is encountered,
8612 /// the function returns true to let the declaration parsing code handle it.
8613 /// Returns false if the statement is disambiguated as expression.
8614 ///
8615 /// \verbatim
8616 /// simple-declaration:
8617 /// decl-specifier-seq init-declarator-list[opt] ';'
8618 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8619 /// brace-or-equal-initializer ';' [C++17]
8620 /// \endverbatim
8621 ///
8622 /// (if AllowForRangeDecl specified)
8623 /// for ( for-range-declaration : for-range-initializer ) statement
8624 ///
8625 /// \verbatim
8626 /// for-range-declaration:
8627 /// decl-specifier-seq declarator
8628 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8629 /// \endverbatim
8630 ///
8631 /// In any of the above cases there can be a preceding
8632 /// attribute-specifier-seq, but the caller is expected to handle that.
8633 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
8634
8635 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
8636 /// a constructor-style initializer, when parsing declaration statements.
8637 /// Returns true for function declarator and false for constructor-style
8638 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
8639 /// might be a constructor-style initializer.
8640 /// If during the disambiguation process a parsing error is encountered,
8641 /// the function returns true to let the declaration parsing code handle it.
8642 ///
8643 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8644 /// exception-specification[opt]
8645 ///
8646 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
8647 ImplicitTypenameContext AllowImplicitTypename =
8649
8650 struct ConditionDeclarationOrInitStatementState;
8651 enum class ConditionOrInitStatement {
8652 Expression, ///< Disambiguated as an expression (either kind).
8653 ConditionDecl, ///< Disambiguated as the declaration form of condition.
8654 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
8655 ForRangeDecl, ///< Disambiguated as a for-range declaration.
8656 Error ///< Can't be any of the above!
8657 };
8658
8659 /// Disambiguates between a declaration in a condition, a
8660 /// simple-declaration in an init-statement, and an expression for
8661 /// a condition of a if/switch statement.
8662 ///
8663 /// \verbatim
8664 /// condition:
8665 /// expression
8666 /// type-specifier-seq declarator '=' assignment-expression
8667 /// [C++11] type-specifier-seq declarator '=' initializer-clause
8668 /// [C++11] type-specifier-seq declarator braced-init-list
8669 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
8670 /// '=' assignment-expression
8671 /// simple-declaration:
8672 /// decl-specifier-seq init-declarator-list[opt] ';'
8673 /// \endverbatim
8674 ///
8675 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
8676 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
8677 /// 'int(x);' (a simple-declaration in an init-statement).
8678 ConditionOrInitStatement
8679 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
8680 bool CanBeForRangeDecl);
8681
8682 /// Determine whether the next set of tokens contains a type-id.
8683 ///
8684 /// The context parameter states what context we're parsing right
8685 /// now, which affects how this routine copes with the token
8686 /// following the type-id. If the context is
8687 /// TentativeCXXTypeIdContext::InParens, we have already parsed the '(' and we
8688 /// will cease lookahead when we hit the corresponding ')'. If the context is
8689 /// TentativeCXXTypeIdContext::AsTemplateArgument, we've already parsed the
8690 /// '<' or ',' before this template argument, and will cease lookahead when we
8691 /// hit a
8692 /// '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
8693 /// preceding such. Returns true for a type-id and false for an expression.
8694 /// If during the disambiguation process a parsing error is encountered,
8695 /// the function returns true to let the declaration parsing code handle it.
8696 ///
8697 /// \verbatim
8698 /// type-id:
8699 /// type-specifier-seq abstract-declarator[opt]
8700 /// \endverbatim
8701 ///
8702 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
8703
8704 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
8705 bool isAmbiguous;
8706 return isCXXTypeId(Context, isAmbiguous);
8707 }
8708
8709 /// TPResult - Used as the result value for functions whose purpose is to
8710 /// disambiguate C++ constructs by "tentatively parsing" them.
8711 enum class TPResult { True, False, Ambiguous, Error };
8712
8713 /// Determine whether we could have an enum-base.
8714 ///
8715 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
8716 /// only consider this to be an enum-base if the next token is a '{'.
8717 ///
8718 /// \return \c false if this cannot possibly be an enum base; \c true
8719 /// otherwise.
8720 bool isEnumBase(bool AllowSemi);
8721
8722 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
8723 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
8724 /// be either a decl-specifier or a function-style cast, and TPResult::Error
8725 /// if a parsing error was found and reported.
8726 ///
8727 /// Does not consume tokens.
8728 ///
8729 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
8730 /// declaration specifiers but possibly valid as some other kind of construct
8731 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
8732 /// the intent is to keep trying to disambiguate, on the basis that we might
8733 /// find a better reason to treat this construct as a declaration later on.
8734 /// When this happens and the name could possibly be valid in some other
8735 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
8736 /// that trigger this are:
8737 ///
8738 /// * When parsing X::Y (with no 'typename') where X is dependent
8739 /// * When parsing X<Y> where X is undeclared
8740 ///
8741 /// \verbatim
8742 /// decl-specifier:
8743 /// storage-class-specifier
8744 /// type-specifier
8745 /// function-specifier
8746 /// 'friend'
8747 /// 'typedef'
8748 /// [C++11] 'constexpr'
8749 /// [C++20] 'consteval'
8750 /// [GNU] attributes declaration-specifiers[opt]
8751 ///
8752 /// storage-class-specifier:
8753 /// 'register'
8754 /// 'static'
8755 /// 'extern'
8756 /// 'mutable'
8757 /// 'auto'
8758 /// [GNU] '__thread'
8759 /// [C++11] 'thread_local'
8760 /// [C11] '_Thread_local'
8761 ///
8762 /// function-specifier:
8763 /// 'inline'
8764 /// 'virtual'
8765 /// 'explicit'
8766 ///
8767 /// typedef-name:
8768 /// identifier
8769 ///
8770 /// type-specifier:
8771 /// simple-type-specifier
8772 /// class-specifier
8773 /// enum-specifier
8774 /// elaborated-type-specifier
8775 /// typename-specifier
8776 /// cv-qualifier
8777 ///
8778 /// simple-type-specifier:
8779 /// '::'[opt] nested-name-specifier[opt] type-name
8780 /// '::'[opt] nested-name-specifier 'template'
8781 /// simple-template-id [TODO]
8782 /// 'char'
8783 /// 'wchar_t'
8784 /// 'bool'
8785 /// 'short'
8786 /// 'int'
8787 /// 'long'
8788 /// 'signed'
8789 /// 'unsigned'
8790 /// 'float'
8791 /// 'double'
8792 /// 'void'
8793 /// [GNU] typeof-specifier
8794 /// [GNU] '_Complex'
8795 /// [C++11] 'auto'
8796 /// [GNU] '__auto_type'
8797 /// [C++11] 'decltype' ( expression )
8798 /// [C++1y] 'decltype' ( 'auto' )
8799 ///
8800 /// type-name:
8801 /// class-name
8802 /// enum-name
8803 /// typedef-name
8804 ///
8805 /// elaborated-type-specifier:
8806 /// class-key '::'[opt] nested-name-specifier[opt] identifier
8807 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
8808 /// simple-template-id
8809 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
8810 ///
8811 /// enum-name:
8812 /// identifier
8813 ///
8814 /// enum-specifier:
8815 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
8816 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
8817 ///
8818 /// class-specifier:
8819 /// class-head '{' member-specification[opt] '}'
8820 ///
8821 /// class-head:
8822 /// class-key identifier[opt] base-clause[opt]
8823 /// class-key nested-name-specifier identifier base-clause[opt]
8824 /// class-key nested-name-specifier[opt] simple-template-id
8825 /// base-clause[opt]
8826 ///
8827 /// class-key:
8828 /// 'class'
8829 /// 'struct'
8830 /// 'union'
8831 ///
8832 /// cv-qualifier:
8833 /// 'const'
8834 /// 'volatile'
8835 /// [GNU] restrict
8836 /// \endverbatim
8837 ///
8838 TPResult
8839 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
8840 TPResult BracedCastResult = TPResult::False,
8841 bool *InvalidAsDeclSpec = nullptr);
8842
8843 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
8844 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
8845 /// a type-specifier other than a cv-qualifier.
8846 bool isCXXDeclarationSpecifierAType();
8847
8848 /// Determine whether we might be looking at the '<' template-argument-list
8849 /// '>' of a template-id or simple-template-id, rather than a less-than
8850 /// comparison. This will often fail and produce an ambiguity, but should
8851 /// never be wrong if it returns True or False.
8852 TPResult isTemplateArgumentList(unsigned TokensToSkip);
8853
8854 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
8855 /// 'explicit(bool)' declaration, in earlier language modes where that is an
8856 /// extension.
8857 TPResult isExplicitBool();
8858
8859 /// Determine whether an identifier has been tentatively declared as a
8860 /// non-type. Such tentative declarations should not be found to name a type
8861 /// during a tentative parse, but also should not be annotated as a non-type.
8862 bool isTentativelyDeclared(IdentifierInfo *II);
8863
8864 // "Tentative parsing" functions, used for disambiguation. If a parsing error
8865 // is encountered they will return TPResult::Error.
8866 // Returning TPResult::True/False indicates that the ambiguity was
8867 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
8868 // that more tentative parsing is necessary for disambiguation.
8869 // They all consume tokens, so backtracking should be used after calling them.
8870
8871 /// \verbatim
8872 /// simple-declaration:
8873 /// decl-specifier-seq init-declarator-list[opt] ';'
8874 ///
8875 /// (if AllowForRangeDecl specified)
8876 /// for ( for-range-declaration : for-range-initializer ) statement
8877 /// for-range-declaration:
8878 /// attribute-specifier-seqopt type-specifier-seq declarator
8879 /// \endverbatim
8880 ///
8881 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
8882
8883 /// \verbatim
8884 /// [GNU] typeof-specifier:
8885 /// 'typeof' '(' expressions ')'
8886 /// 'typeof' '(' type-name ')'
8887 /// \endverbatim
8888 ///
8889 TPResult TryParseTypeofSpecifier();
8890
8891 /// [ObjC] protocol-qualifiers:
8892 /// '<' identifier-list '>'
8893 TPResult TryParseProtocolQualifiers();
8894
8895 TPResult TryParsePtrOperatorSeq();
8896
8897 /// \verbatim
8898 /// operator-function-id:
8899 /// 'operator' operator
8900 ///
8901 /// operator: one of
8902 /// new delete new[] delete[] + - * / % ^ [...]
8903 ///
8904 /// conversion-function-id:
8905 /// 'operator' conversion-type-id
8906 ///
8907 /// conversion-type-id:
8908 /// type-specifier-seq conversion-declarator[opt]
8909 ///
8910 /// conversion-declarator:
8911 /// ptr-operator conversion-declarator[opt]
8912 ///
8913 /// literal-operator-id:
8914 /// 'operator' string-literal identifier
8915 /// 'operator' user-defined-string-literal
8916 /// \endverbatim
8917 TPResult TryParseOperatorId();
8918
8919 /// Tentatively parse an init-declarator-list in order to disambiguate it from
8920 /// an expression.
8921 ///
8922 /// \verbatim
8923 /// init-declarator-list:
8924 /// init-declarator
8925 /// init-declarator-list ',' init-declarator
8926 ///
8927 /// init-declarator:
8928 /// declarator initializer[opt]
8929 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
8930 ///
8931 /// initializer:
8932 /// brace-or-equal-initializer
8933 /// '(' expression-list ')'
8934 ///
8935 /// brace-or-equal-initializer:
8936 /// '=' initializer-clause
8937 /// [C++11] braced-init-list
8938 ///
8939 /// initializer-clause:
8940 /// assignment-expression
8941 /// braced-init-list
8942 ///
8943 /// braced-init-list:
8944 /// '{' initializer-list ','[opt] '}'
8945 /// '{' '}'
8946 /// \endverbatim
8947 ///
8948 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
8949
8950 /// \verbatim
8951 /// declarator:
8952 /// direct-declarator
8953 /// ptr-operator declarator
8954 ///
8955 /// direct-declarator:
8956 /// declarator-id
8957 /// direct-declarator '(' parameter-declaration-clause ')'
8958 /// cv-qualifier-seq[opt] exception-specification[opt]
8959 /// direct-declarator '[' constant-expression[opt] ']'
8960 /// '(' declarator ')'
8961 /// [GNU] '(' attributes declarator ')'
8962 ///
8963 /// abstract-declarator:
8964 /// ptr-operator abstract-declarator[opt]
8965 /// direct-abstract-declarator
8966 ///
8967 /// direct-abstract-declarator:
8968 /// direct-abstract-declarator[opt]
8969 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8970 /// exception-specification[opt]
8971 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
8972 /// '(' abstract-declarator ')'
8973 /// [C++0x] ...
8974 ///
8975 /// ptr-operator:
8976 /// '*' cv-qualifier-seq[opt]
8977 /// '&'
8978 /// [C++0x] '&&' [TODO]
8979 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
8980 ///
8981 /// cv-qualifier-seq:
8982 /// cv-qualifier cv-qualifier-seq[opt]
8983 ///
8984 /// cv-qualifier:
8985 /// 'const'
8986 /// 'volatile'
8987 ///
8988 /// declarator-id:
8989 /// '...'[opt] id-expression
8990 ///
8991 /// id-expression:
8992 /// unqualified-id
8993 /// qualified-id [TODO]
8994 ///
8995 /// unqualified-id:
8996 /// identifier
8997 /// operator-function-id
8998 /// conversion-function-id
8999 /// literal-operator-id
9000 /// '~' class-name [TODO]
9001 /// '~' decltype-specifier [TODO]
9002 /// template-id [TODO]
9003 /// \endverbatim
9004 ///
9005 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
9006 bool mayHaveDirectInit = false,
9007 bool mayHaveTrailingReturnType = false);
9008
9009 /// \verbatim
9010 /// parameter-declaration-clause:
9011 /// parameter-declaration-list[opt] '...'[opt]
9012 /// parameter-declaration-list ',' '...'
9013 ///
9014 /// parameter-declaration-list:
9015 /// parameter-declaration
9016 /// parameter-declaration-list ',' parameter-declaration
9017 ///
9018 /// parameter-declaration:
9019 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
9020 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
9021 /// '=' assignment-expression
9022 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
9023 /// attributes[opt]
9024 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
9025 /// attributes[opt] '=' assignment-expression
9026 /// \endverbatim
9027 ///
9028 TPResult TryParseParameterDeclarationClause(
9029 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
9030 ImplicitTypenameContext AllowImplicitTypename =
9032
9033 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to
9034 /// continue parsing as a function declarator. If TryParseFunctionDeclarator
9035 /// fully parsed the function declarator, it will return TPResult::Ambiguous,
9036 /// otherwise it will return either False() or Error().
9037 ///
9038 /// \verbatim
9039 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
9040 /// exception-specification[opt]
9041 ///
9042 /// exception-specification:
9043 /// 'throw' '(' type-id-list[opt] ')'
9044 /// \endverbatim
9045 ///
9046 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
9047
9048 // When parsing an identifier after an arrow it may be a member expression,
9049 // in which case we should not annotate it as an independant expression
9050 // so we just lookup that name, if it's not a type the construct is not
9051 // a function declaration.
9052 bool NameAfterArrowIsNonType();
9053
9054 /// \verbatim
9055 /// '[' constant-expression[opt] ']'
9056 /// \endverbatim
9057 ///
9058 TPResult TryParseBracketDeclarator();
9059
9060 /// Try to consume a token sequence that we've already identified as
9061 /// (potentially) starting a decl-specifier.
9062 TPResult TryConsumeDeclarationSpecifier();
9063
9064 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
9065 /// full validation of the syntactic structure of attributes.
9066 bool TrySkipAttributes();
9067
9068 /// Whether tentative lookahead from the current '[' finds a lambda-like
9069 /// continuation. This does not parse or validate a lambda.
9070 bool hasLambdaLikeContinuation();
9071
9072 //===--------------------------------------------------------------------===//
9073 // C++ 7: Declarations [dcl.dcl]
9074
9075 /// Returns true if this is a C++11 attribute-specifier. Per
9076 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
9077 /// always introduce an attribute. In Objective-C++11, this rule does not
9078 /// apply if either '[' begins a message-send.
9079 ///
9080 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
9081 /// an attribute-specifier, and return
9082 /// CXX11AttributeKind::InvalidAttributeSpecifier if not.
9083 ///
9084 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
9085 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
9086 /// is not an Obj-C message send.
9087 ///
9088 /// C++11 [dcl.attr.grammar]:
9089 ///
9090 /// \verbatim
9091 /// attribute-specifier:
9092 /// '[' '[' attribute-list ']' ']'
9093 /// alignment-specifier
9094 ///
9095 /// attribute-list:
9096 /// attribute[opt]
9097 /// attribute-list ',' attribute[opt]
9098 /// attribute '...'
9099 /// attribute-list ',' attribute '...'
9100 ///
9101 /// attribute:
9102 /// attribute-token attribute-argument-clause[opt]
9103 ///
9104 /// attribute-token:
9105 /// identifier
9106 /// identifier '::' identifier
9107 ///
9108 /// attribute-argument-clause:
9109 /// '(' balanced-token-seq ')'
9110 /// \endverbatim
9112 isCXX11AttributeSpecifier(bool Disambiguate = false,
9113 bool OuterMightBeMessageSend = false);
9114
9115 ///@}
9116};
9117
9118} // end namespace clang
9119
9120#endif
bool is(tok::TokenKind Kind) const
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Token Tok
The Token.
bool isNot(T Kind) const
FormatToken * Next
The next token in the unwrapped line.
Defines some OpenACC-specific enums and functions.
Defines and computes precedence levels for binary/ternary operators.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
bool isInvalid() const
Definition Ownership.h:167
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:635
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Represents a C++26 expansion statement declaration.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
Callback handler that receives notifications when performing code completion within the preprocessor.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
virtual void CodeCompleteInConditionalExclusion()
Callback invoked when performing code completion within a block of code that was excluded due to prep...
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
TypeSpecifierType TST
Definition DeclSpec.h:250
static const TST TST_unspecified
Definition DeclSpec.h:251
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
This represents one expression.
Definition Expr.h:113
One of these records is kept for each identifier that is lexed.
Represents the declaration of a label.
Definition Decl.h:525
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
[class.mem]p1: "... the class is regarded as complete within
Definition Parser.h:175
This is a basic class for representing single OpenMP clause.
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:665
Wrapper for void* pointer.
Definition Ownership.h:51
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
This is the base type for all OpenACC Clauses.
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:950
Introduces zero or more scopes for parsing.
Definition Parser.h:528
MultiParseScope(Parser &Self)
Definition Parser.h:535
void Enter(unsigned ScopeFlags)
Definition Parser.h:536
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope=true, bool BeforeCompoundStmt=false)
Definition Parser.h:501
Parser - This implements a parser for the C family of languages.
Definition Parser.h:256
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl< Expr * > &Vars, SemaOpenMP::OpenMPVarListDataTy &Data)
Parses clauses with list.
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName.
Definition ParseDecl.cpp:45
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, bool IsAddressOfOperand=false)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition Parser.cpp:1885
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:101
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1860
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
Definition Parser.cpp:2013
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Definition Parser.cpp:109
Preprocessor & getPreprocessor() const
Definition Parser.h:291
bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data)
Parse map-type-modifiers in map clause.
Sema::FullExprArg FullExprArg
Definition Parser.h:3683
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ParseStringLiteralExpression - This handles the various token types that form string literals,...
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:347
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:72
AttributeFactory & getAttrFactory()
Definition Parser.h:293
void incrementMSManglingNumber() const
Definition Parser.h:298
Sema & getActions() const
Definition Parser.h:292
DiagnosticBuilder DiagCompat(unsigned CompatDiagId)
Definition Parser.h:564
bool ParseTopLevelDecl()
Definition Parser.h:336
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition Parser.h:412
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:440
bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data)
Parses the mapper modifier in map, to, and from clauses.
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
friend class ParsingOpenMPDirectiveRAII
Definition Parser.h:6408
ExprResult ParseConstantExpressionInExprEvalContext(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
SmallVector< Stmt *, 24 > StmtVector
A SmallVector of statements.
Definition Parser.h:7301
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext=false)
Definition Parser.h:479
friend class ColonProtectionRAIIObject
Definition Parser.h:281
DeclGroupPtrTy ParseOpenACCDirectiveDecl(AccessSpecifier &AS, ParsedAttributes &Attrs, DeclSpec::TST TagType, Decl *TagDecl)
Parse OpenACC directive on a declaration.
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition Parser.h:595
~Parser() override
Definition Parser.cpp:485
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:375
friend struct LateParsedTypeAttribute
Definition Parser.h:1211
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:401
ExprResult ParseConstantExpression()
StmtResult ParseOpenACCDirectiveStmt()
ExprResult ParseConditionalExpression()
Definition ParseExpr.cpp:95
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:355
friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R)
Definition Parser.h:576
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:304
Scope * getCurScope() const
Definition Parser.h:296
ExprResult ParseArrayBoundExpression()
friend class InMessageExpressionRAIIObject
Definition Parser.h:5419
friend class ParsingOpenACCDirectiveRAII
Definition Parser.h:6140
friend struct LateParsedAttribute
Definition Parser.h:1210
ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-and-expression.
bool TryAnnotateTypeOrScopeToken(bool IsAddressOfOperand)
Definition Parser.h:450
const TargetInfo & getTargetInfo() const
Definition Parser.h:290
OpaquePtr< TemplateName > TemplateTy
Definition Parser.h:305
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition Parser.h:591
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
friend class OffsetOfStateRAIIObject
Definition Parser.h:3681
const Token & getCurToken() const
Definition Parser.h:295
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds to the given nullability kind...
Definition Parser.h:5428
friend class ObjCDeclContextSwitch
Definition Parser.h:5420
friend class PoisonSEHIdentifiersRAIIObject
Definition Parser.h:282
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
Definition Parser.h:600
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition Parser.cpp:450
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand=false)
Parses simple expression in parens for single-expression clauses of OpenMP constructs.
SourceLocation MisleadingIndentationElseLoc
The location of the first statement inside an else that might have a missleading indentation.
Definition Parser.h:7306
const LangOptions & getLangOpts() const
Definition Parser.h:289
friend class ParenBraceBracketBalancer
Definition Parser.h:283
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
Definition Parser.cpp:606
DiagnosticBuilder Diag(unsigned DiagID)
Definition Parser.h:560
ExprResult ParseExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Simple precedence-based parser for binary/ternary operators.
Definition ParseExpr.cpp:47
SkipUntilFlags
Control flags for SkipUntil functions.
Definition Parser.h:569
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:572
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:573
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:570
bool MightBeCXXScopeToken()
Definition Parser.h:472
ExprResult ParseUnevaluatedStringLiteralExpression()
bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind, SemaOpenMP::OpenMPVarListDataTy &Data, const LangOptions &LangOpts)
Parses a reserved locator like 'omp_all_memory'.
ObjCContainerDecl * getObjCDeclContext() const
Definition Parser.h:5422
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:409
ExprResult ParseAssignmentExpression(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
Parse an expr that doesn't include (top-level) commas.
Definition ParseExpr.cpp:75
friend class BalancedDelimiterTracker
Definition Parser.h:284
bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc)
Definition Parser.h:365
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7925
void Initialize()
Initialize - Warm up the parser.
Definition Parser.cpp:503
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D)
Re-enter a possible template scope, creating as many template parameter scopes as necessary.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition Parser.cpp:2130
bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc)
Parses 'omp begin declare variant' directive.
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
A class for parsing a declarator.
A class for parsing a field declarator.
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition Pragma.h:65
Tracks expected type during expression parsing, for use in code completion.
Definition Sema.h:297
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void startOpenMPLoop()
If the current region is a loop-based region, mark the start of the loop construct.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
SemaOpenMP & OpenMP()
Definition Sema.h:1531
ProcessingContextState ParsingClassState
Definition Sema.h:6592
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9950
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9959
Encodes a location in the source.
A trivial tuple used to represent a source range.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
Exposes information about the current target.
Definition TargetInfo.h:226
Represents a C++ template name within the type system.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
llvm::DenseMap< int, SourceRange > ParsedSubjectMatchRuleSet
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
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:101
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition TokenKinds.h:49
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
@ TST_unspecified
Definition Specifiers.h:57
ImplicitTypenameContext
Definition DeclSpec.h:1935
OpenACCDirectiveKind
CXX11AttributeKind
The kind of attribute specifier we have found.
Definition Parser.h:157
@ NotAttributeSpecifier
This is not an attribute specifier.
Definition Parser.h:159
@ AttributeSpecifier
This should be treated as an attribute-specifier.
Definition Parser.h:161
@ InvalidAttributeSpecifier
The next tokens are '[[', but this is not an attribute-specifier.
Definition Parser.h:164
@ CPlusPlus
OpenACCAtomicKind
TypoCorrectionTypeBehavior
If a typo should be encountered, should typo correction suggest type names, non type names,...
Definition Parser.h:106
OpenACCModifierKind
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
AnnotatedNameKind
Definition Parser.h:55
@ Success
Annotation was successful.
Definition Parser.h:65
@ TentativeDecl
The identifier is a tentatively-declared name.
Definition Parser.h:59
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OpenACCClauseKind
Represents the kind of an OpenACC clause.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
TypeResult TypeError()
Definition Ownership.h:267
IfExistsBehavior
Describes the behavior that should be taken for an __if_exists block.
Definition Parser.h:135
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
DeclaratorContext
Definition DeclSpec.h:1902
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:610
TentativeCXXTypeIdContext
Specifies the context in which type-id/expression disambiguation will occur.
Definition Parser.h:147
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
const FunctionProtoType * T
ParsedTemplateKind
The kind of template we are parsing.
Definition Parser.h:77
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ ExplicitSpecialization
We are parsing an explicit specialization.
Definition Parser.h:83
@ ExplicitInstantiation
We are parsing an explicit instantiation.
Definition Parser.h:85
@ NonTemplate
We are not parsing a template at all.
Definition Parser.h:79
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
CachedInitKind
Definition Parser.h:88
ObjCTypeQual
Definition Parser.h:91
TagUseKind
Definition Sema.h:445
ExtraSemiKind
The kind of extra semi diagnostic to emit.
Definition Parser.h:69
@ AfterMemberFunctionDefinition
Definition Parser.h:73
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
ParenExprKind
In a call to ParseParenExpression, are the initial parentheses part of an operator that requires the ...
Definition Parser.h:128
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1256
CastParseKind
Control what ParseCastExpression will parse.
Definition Parser.h:113
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6007
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ParenParseOption
ParenParseOption - Control what ParseParenExpression will parse.
Definition Parser.h:116
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
#define false
Definition stdbool.h:26
LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc, Kind K)
Definition Parser.h:210
IdentifierInfo & AttrName
Definition Parser.h:201
LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc)
Definition Parser.h:215
IdentifierInfo * MacroII
Definition Parser.h:202
void addDecl(Decl *D)
Definition Parser.h:221
SourceLocation AttrNameLoc
Definition Parser.h:203
static bool classof(const LateParsedAttribute *LA)
Definition Parser.h:225
SmallVector< Decl *, 2 > Decls
Definition Parser.h:204
LateParsedTypeAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc)
Definition Parser.h:235
void ParseInto(ParsedAttributes &OutAttrs)
Parse this late-parsed type attribute and store results in OutAttrs.
static bool classof(const LateParsedAttribute *LA)
Definition Parser.h:246
Loop optimization hint for loop and unroll pragmas.
Definition LoopHint.h:20
AngleBracketTracker::Priority Priority
Definition Parser.h:8041
bool isActiveOrNested(Parser &P) const
Definition Parser.h:8049