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