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
3898 ParseStringLiteralExpression(bool AllowUserDefinedLiteral, bool Unevaluated,
3900
3901 /// This routine is called when the '@' is seen and consumed.
3902 /// Current token is an Identifier and is not a 'try'. This
3903 /// routine is necessary to disambiguate \@try-statement from,
3904 /// for example, \@encode-expression.
3905 ///
3906 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
3907
3908 /// This routine is called when a leading '__extension__' is seen and
3909 /// consumed. This is necessary because the token gets consumed in the
3910 /// process of disambiguating between an expression and a declaration.
3911 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
3912
3913 /// Parse a binary expression that starts with \p LHS and has a
3914 /// precedence of at least \p MinPrec.
3915 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec);
3916
3917 bool isRevertibleTypeTrait(const IdentifierInfo *Id,
3918 clang::tok::TokenKind *Kind = nullptr);
3919
3920 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
3921 /// a unary-expression.
3922 ///
3923 /// \p isAddressOfOperand exists because an id-expression that is the operand
3924 /// of address-of gets special treatment due to member pointers. NotCastExpr
3925 /// is set to true if the token is not the start of a cast-expression, and no
3926 /// diagnostic is emitted in this case and no tokens are consumed.
3927 /// In addition, isAddressOfOperand is propagated to SemaCodeCompletion
3928 /// as a heuristic for function completions (to provide different behavior
3929 /// when the user is likely taking the address of a function vs. calling it).
3930 ///
3931 /// \verbatim
3932 /// cast-expression: [C99 6.5.4]
3933 /// unary-expression
3934 /// '(' type-name ')' cast-expression
3935 ///
3936 /// unary-expression: [C99 6.5.3]
3937 /// postfix-expression
3938 /// '++' unary-expression
3939 /// '--' unary-expression
3940 /// [Coro] 'co_await' cast-expression
3941 /// unary-operator cast-expression
3942 /// 'sizeof' unary-expression
3943 /// 'sizeof' '(' type-name ')'
3944 /// [C++11] 'sizeof' '...' '(' identifier ')'
3945 /// [GNU] '__alignof' unary-expression
3946 /// [GNU] '__alignof' '(' type-name ')'
3947 /// [C11] '_Alignof' '(' type-name ')'
3948 /// [C++11] 'alignof' '(' type-id ')'
3949 /// [C2y] '_Countof' unary-expression
3950 /// [C2y] '_Countof' '(' type-name ')'
3951 /// [GNU] '&&' identifier
3952 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
3953 /// [C++] new-expression
3954 /// [C++] delete-expression
3955 ///
3956 /// unary-operator: one of
3957 /// '&' '*' '+' '-' '~' '!'
3958 /// [GNU] '__extension__' '__real' '__imag'
3959 ///
3960 /// primary-expression: [C99 6.5.1]
3961 /// [C99] identifier
3962 /// [C++] id-expression
3963 /// constant
3964 /// string-literal
3965 /// [C++] boolean-literal [C++ 2.13.5]
3966 /// [C++11] 'nullptr' [C++11 2.14.7]
3967 /// [C++11] user-defined-literal
3968 /// '(' expression ')'
3969 /// [C11] generic-selection
3970 /// [C++2a] requires-expression
3971 /// '__func__' [C99 6.4.2.2]
3972 /// [GNU] '__FUNCTION__'
3973 /// [MS] '__FUNCDNAME__'
3974 /// [MS] 'L__FUNCTION__'
3975 /// [MS] '__FUNCSIG__'
3976 /// [MS] 'L__FUNCSIG__'
3977 /// [GNU] '__PRETTY_FUNCTION__'
3978 /// [GNU] '(' compound-statement ')'
3979 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
3980 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
3981 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
3982 /// assign-expr ')'
3983 /// [GNU] '__builtin_FILE' '(' ')'
3984 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
3985 /// [GNU] '__builtin_FUNCTION' '(' ')'
3986 /// [MS] '__builtin_FUNCSIG' '(' ')'
3987 /// [GNU] '__builtin_LINE' '(' ')'
3988 /// [CLANG] '__builtin_COLUMN' '(' ')'
3989 /// [GNU] '__builtin_source_location' '(' ')'
3990 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
3991 /// [GNU] '__null'
3992 /// [OBJC] '[' objc-message-expr ']'
3993 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
3994 /// [OBJC] '\@protocol' '(' identifier ')'
3995 /// [OBJC] '\@encode' '(' type-name ')'
3996 /// [OBJC] objc-string-literal
3997 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
3998 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
3999 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
4000 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
4001 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
4002 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
4003 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
4004 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
4005 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
4006 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
4007 /// [C++] 'this' [C++ 9.3.2]
4008 /// [G++] unary-type-trait '(' type-id ')'
4009 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
4010 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
4011 /// [clang] '^' block-literal
4012 ///
4013 /// constant: [C99 6.4.4]
4014 /// integer-constant
4015 /// floating-constant
4016 /// enumeration-constant -> identifier
4017 /// character-constant
4018 ///
4019 /// id-expression: [C++ 5.1]
4020 /// unqualified-id
4021 /// qualified-id
4022 ///
4023 /// unqualified-id: [C++ 5.1]
4024 /// identifier
4025 /// operator-function-id
4026 /// conversion-function-id
4027 /// '~' class-name
4028 /// template-id
4029 ///
4030 /// new-expression: [C++ 5.3.4]
4031 /// '::'[opt] 'new' new-placement[opt] new-type-id
4032 /// new-initializer[opt]
4033 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4034 /// new-initializer[opt]
4035 ///
4036 /// delete-expression: [C++ 5.3.5]
4037 /// '::'[opt] 'delete' cast-expression
4038 /// '::'[opt] 'delete' '[' ']' cast-expression
4039 ///
4040 /// [GNU/Embarcadero] unary-type-trait:
4041 /// '__is_arithmetic'
4042 /// '__is_floating_point'
4043 /// '__is_integral'
4044 /// '__is_lvalue_expr'
4045 /// '__is_rvalue_expr'
4046 /// '__is_complete_type'
4047 /// '__is_void'
4048 /// '__is_array'
4049 /// '__is_function'
4050 /// '__is_reference'
4051 /// '__is_lvalue_reference'
4052 /// '__is_rvalue_reference'
4053 /// '__is_fundamental'
4054 /// '__is_object'
4055 /// '__is_scalar'
4056 /// '__is_compound'
4057 /// '__is_pointer'
4058 /// '__is_member_object_pointer'
4059 /// '__is_member_function_pointer'
4060 /// '__is_member_pointer'
4061 /// '__is_const'
4062 /// '__is_volatile'
4063 /// '__is_trivial'
4064 /// '__is_standard_layout'
4065 /// '__is_signed'
4066 /// '__is_unsigned'
4067 ///
4068 /// [GNU] unary-type-trait:
4069 /// '__has_nothrow_assign'
4070 /// '__has_nothrow_copy'
4071 /// '__has_nothrow_constructor'
4072 /// '__has_trivial_assign' [TODO]
4073 /// '__has_trivial_copy' [TODO]
4074 /// '__has_trivial_constructor'
4075 /// '__has_trivial_destructor'
4076 /// '__has_virtual_destructor'
4077 /// '__is_abstract' [TODO]
4078 /// '__is_class'
4079 /// '__is_empty' [TODO]
4080 /// '__is_enum'
4081 /// '__is_final'
4082 /// '__is_pod'
4083 /// '__is_polymorphic'
4084 /// '__is_sealed' [MS]
4085 /// '__is_trivial'
4086 /// '__is_union'
4087 /// '__has_unique_object_representations'
4088 ///
4089 /// [Clang] unary-type-trait:
4090 /// '__is_aggregate'
4091 /// '__trivially_copyable'
4092 ///
4093 /// binary-type-trait:
4094 /// [GNU] '__is_base_of'
4095 /// [MS] '__is_convertible_to'
4096 /// '__is_convertible'
4097 /// '__is_same'
4098 ///
4099 /// [Embarcadero] array-type-trait:
4100 /// '__array_rank'
4101 /// '__array_extent'
4102 ///
4103 /// [Embarcadero] expression-trait:
4104 /// '__is_lvalue_expr'
4105 /// '__is_rvalue_expr'
4106 /// \endverbatim
4107 ///
4108 ExprResult ParseCastExpression(CastParseKind ParseKind,
4109 bool isAddressOfOperand, bool &NotCastExpr,
4110 TypoCorrectionTypeBehavior CorrectionBehavior,
4111 bool isVectorLiteral = false,
4112 bool *NotPrimaryExpression = nullptr);
4113 ExprResult ParseCastExpression(CastParseKind ParseKind,
4114 bool isAddressOfOperand = false,
4115 TypoCorrectionTypeBehavior CorrectionBehavior =
4117 bool isVectorLiteral = false,
4118 bool *NotPrimaryExpression = nullptr);
4119
4120 /// Returns true if the next token cannot start an expression.
4121 bool isNotExpressionStart();
4122
4123 /// Returns true if the next token would start a postfix-expression
4124 /// suffix.
4125 bool isPostfixExpressionSuffixStart() {
4126 tok::TokenKind K = Tok.getKind();
4127 return (K == tok::l_square || K == tok::l_paren || K == tok::period ||
4128 K == tok::arrow || K == tok::plusplus || K == tok::minusminus);
4129 }
4130
4131 /// Once the leading part of a postfix-expression is parsed, this
4132 /// method parses any suffixes that apply.
4133 ///
4134 /// \verbatim
4135 /// postfix-expression: [C99 6.5.2]
4136 /// primary-expression
4137 /// postfix-expression '[' expression ']'
4138 /// postfix-expression '[' braced-init-list ']'
4139 /// postfix-expression '[' expression-list [opt] ']' [C++23 12.4.5]
4140 /// postfix-expression '(' argument-expression-list[opt] ')'
4141 /// postfix-expression '.' identifier
4142 /// postfix-expression '->' identifier
4143 /// postfix-expression '++'
4144 /// postfix-expression '--'
4145 /// '(' type-name ')' '{' initializer-list '}'
4146 /// '(' type-name ')' '{' initializer-list ',' '}'
4147 ///
4148 /// argument-expression-list: [C99 6.5.2]
4149 /// argument-expression ...[opt]
4150 /// argument-expression-list ',' assignment-expression ...[opt]
4151 /// \endverbatim
4152 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
4153
4154 /// Parse a sizeof or alignof expression.
4155 ///
4156 /// \verbatim
4157 /// unary-expression: [C99 6.5.3]
4158 /// 'sizeof' unary-expression
4159 /// 'sizeof' '(' type-name ')'
4160 /// [C++11] 'sizeof' '...' '(' identifier ')'
4161 /// [Clang] '__datasizeof' unary-expression
4162 /// [Clang] '__datasizeof' '(' type-name ')'
4163 /// [GNU] '__alignof' unary-expression
4164 /// [GNU] '__alignof' '(' type-name ')'
4165 /// [C11] '_Alignof' '(' type-name ')'
4166 /// [C++11] 'alignof' '(' type-id ')'
4167 /// [C2y] '_Countof' unary-expression
4168 /// [C2y] '_Countof' '(' type-name ')'
4169 /// \endverbatim
4170 ExprResult ParseUnaryExprOrTypeTraitExpression();
4171
4172 /// ParseBuiltinPrimaryExpression
4173 ///
4174 /// \verbatim
4175 /// primary-expression: [C99 6.5.1]
4176 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
4177 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
4178 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
4179 /// assign-expr ')'
4180 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
4181 /// [GNU] '__builtin_FILE' '(' ')'
4182 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
4183 /// [GNU] '__builtin_FUNCTION' '(' ')'
4184 /// [MS] '__builtin_FUNCSIG' '(' ')'
4185 /// [GNU] '__builtin_LINE' '(' ')'
4186 /// [CLANG] '__builtin_COLUMN' '(' ')'
4187 /// [GNU] '__builtin_source_location' '(' ')'
4188 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
4189 ///
4190 /// [GNU] offsetof-member-designator:
4191 /// [GNU] identifier
4192 /// [GNU] offsetof-member-designator '.' identifier
4193 /// [GNU] offsetof-member-designator '[' expression ']'
4194 /// \endverbatim
4195 ExprResult ParseBuiltinPrimaryExpression();
4196
4197 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id
4198 /// as a parameter.
4199 ExprResult ParseSYCLUniqueStableNameExpression();
4200
4201 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
4202 /// vec_step and we are at the start of an expression or a parenthesized
4203 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
4204 /// expression (isCastExpr == false) or the type (isCastExpr == true).
4205 ///
4206 /// \verbatim
4207 /// unary-expression: [C99 6.5.3]
4208 /// 'sizeof' unary-expression
4209 /// 'sizeof' '(' type-name ')'
4210 /// [Clang] '__datasizeof' unary-expression
4211 /// [Clang] '__datasizeof' '(' type-name ')'
4212 /// [GNU] '__alignof' unary-expression
4213 /// [GNU] '__alignof' '(' type-name ')'
4214 /// [C11] '_Alignof' '(' type-name ')'
4215 /// [C++0x] 'alignof' '(' type-id ')'
4216 ///
4217 /// [GNU] typeof-specifier:
4218 /// typeof ( expressions )
4219 /// typeof ( type-name )
4220 /// [GNU/C++] typeof unary-expression
4221 /// [C23] typeof-specifier:
4222 /// typeof '(' typeof-specifier-argument ')'
4223 /// typeof_unqual '(' typeof-specifier-argument ')'
4224 ///
4225 /// typeof-specifier-argument:
4226 /// expression
4227 /// type-name
4228 ///
4229 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
4230 /// vec_step ( expressions )
4231 /// vec_step ( type-name )
4232 /// \endverbatim
4233 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
4234 bool &isCastExpr,
4235 ParsedType &CastTy,
4236 SourceRange &CastRange);
4237
4238 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
4239 ///
4240 /// \verbatim
4241 /// argument-expression-list:
4242 /// assignment-expression
4243 /// argument-expression-list , assignment-expression
4244 ///
4245 /// [C++] expression-list:
4246 /// [C++] assignment-expression
4247 /// [C++] expression-list , assignment-expression
4248 ///
4249 /// [C++0x] expression-list:
4250 /// [C++0x] initializer-list
4251 ///
4252 /// [C++0x] initializer-list
4253 /// [C++0x] initializer-clause ...[opt]
4254 /// [C++0x] initializer-list , initializer-clause ...[opt]
4255 ///
4256 /// [C++0x] initializer-clause:
4257 /// [C++0x] assignment-expression
4258 /// [C++0x] braced-init-list
4259 /// \endverbatim
4260 bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
4261 llvm::function_ref<void()> ExpressionStarts =
4262 llvm::function_ref<void()>(),
4263 bool FailImmediatelyOnInvalidExpr = false,
4264 bool ParsingExpansionStmtInitList = false);
4265
4266 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
4267 /// used for misc language extensions.
4268 ///
4269 /// \verbatim
4270 /// simple-expression-list:
4271 /// assignment-expression
4272 /// simple-expression-list , assignment-expression
4273 /// \endverbatim
4274 bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
4275
4276 /// This parses the unit that starts with a '(' token, based on what is
4277 /// allowed by ExprType. The actual thing parsed is returned in ExprType. If
4278 /// StopIfCastExpr is true, it will only return the parsed type, not the
4279 /// parsed cast-expression. If ParenBehavior is ParenExprKind::PartOfOperator,
4280 /// the initial open paren and its matching close paren are known to be part
4281 /// of another grammar production and not part of the operand. e.g., the
4282 /// typeof and typeof_unqual operators in C. Otherwise, the function has to
4283 /// parse the parens to determine whether they're part of a cast or compound
4284 /// literal expression rather than a parenthesized type.
4285 ///
4286 /// \verbatim
4287 /// primary-expression: [C99 6.5.1]
4288 /// '(' expression ')'
4289 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
4290 /// postfix-expression: [C99 6.5.2]
4291 /// '(' type-name ')' '{' initializer-list '}'
4292 /// '(' type-name ')' '{' initializer-list ',' '}'
4293 /// cast-expression: [C99 6.5.4]
4294 /// '(' type-name ')' cast-expression
4295 /// [ARC] bridged-cast-expression
4296 /// [ARC] bridged-cast-expression:
4297 /// (__bridge type-name) cast-expression
4298 /// (__bridge_transfer type-name) cast-expression
4299 /// (__bridge_retained type-name) cast-expression
4300 /// fold-expression: [C++1z]
4301 /// '(' cast-expression fold-operator '...' ')'
4302 /// '(' '...' fold-operator cast-expression ')'
4303 /// '(' cast-expression fold-operator '...'
4304 /// fold-operator cast-expression ')'
4305 /// [OPENMP] Array shaping operation
4306 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
4307 /// \endverbatim
4308 ExprResult ParseParenExpression(ParenParseOption &ExprType,
4309 bool StopIfCastExpr,
4310 ParenExprKind ParenBehavior,
4311 TypoCorrectionTypeBehavior CorrectionBehavior,
4312 ParsedType &CastTy,
4313 SourceLocation &RParenLoc);
4314
4315 /// ParseCompoundLiteralExpression - We have parsed the parenthesized
4316 /// type-name and we are at the left brace.
4317 ///
4318 /// \verbatim
4319 /// postfix-expression: [C99 6.5.2]
4320 /// '(' type-name ')' '{' initializer-list '}'
4321 /// '(' type-name ')' '{' initializer-list ',' '}'
4322 /// \endverbatim
4323 ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
4324 SourceLocation LParenLoc,
4325 SourceLocation RParenLoc);
4326
4327 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
4328 /// [C11 6.5.1.1].
4329 ///
4330 /// \verbatim
4331 /// generic-selection:
4332 /// _Generic ( assignment-expression , generic-assoc-list )
4333 /// generic-assoc-list:
4334 /// generic-association
4335 /// generic-assoc-list , generic-association
4336 /// generic-association:
4337 /// type-name : assignment-expression
4338 /// default : assignment-expression
4339 /// \endverbatim
4340 ///
4341 /// As an extension, Clang also accepts:
4342 /// \verbatim
4343 /// generic-selection:
4344 /// _Generic ( type-name, generic-assoc-list )
4345 /// \endverbatim
4346 ExprResult ParseGenericSelectionExpression();
4347
4348 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
4349 ///
4350 /// '__objc_yes'
4351 /// '__objc_no'
4352 ExprResult ParseObjCBoolLiteral();
4353
4354 /// Parse A C++1z fold-expression after the opening paren and optional
4355 /// left-hand-side expression.
4356 ///
4357 /// \verbatim
4358 /// fold-expression:
4359 /// ( cast-expression fold-operator ... )
4360 /// ( ... fold-operator cast-expression )
4361 /// ( cast-expression fold-operator ... fold-operator cast-expression )
4362 /// \endverbatim
4363 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
4364
4365 void injectEmbedTokens();
4366
4367 //===--------------------------------------------------------------------===//
4368 // clang Expressions
4369
4370 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
4371 /// like ^(int x){ return x+1; }
4372 ///
4373 /// \verbatim
4374 /// block-literal:
4375 /// [clang] '^' block-args[opt] compound-statement
4376 /// [clang] '^' block-id compound-statement
4377 /// [clang] block-args:
4378 /// [clang] '(' parameter-list ')'
4379 /// \endverbatim
4380 ExprResult ParseBlockLiteralExpression(); // ^{...}
4381
4382 /// Parse an assignment expression where part of an Objective-C message
4383 /// send has already been parsed.
4384 ///
4385 /// In this case \p LBracLoc indicates the location of the '[' of the message
4386 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
4387 /// the receiver of the message.
4388 ///
4389 /// Since this handles full assignment-expression's, it handles postfix
4390 /// expressions and other binary operators for these expressions as well.
4391 ExprResult ParseAssignmentExprWithObjCMessageExprStart(
4392 SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType,
4393 Expr *ReceiverExpr);
4394
4395 /// Return true if we know that we are definitely looking at a
4396 /// decl-specifier, and isn't part of an expression such as a function-style
4397 /// cast. Return false if it's no a decl-specifier, or we're not sure.
4398 bool isKnownToBeDeclarationSpecifier() {
4399 if (getLangOpts().CPlusPlus)
4400 return isCXXDeclarationSpecifier(ImplicitTypenameContext::No) ==
4401 TPResult::True;
4402 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
4403 }
4404
4405 /// Checks whether the current tokens form a type-id or an expression for the
4406 /// purposes of use as the initial operand to a generic selection expression.
4407 /// This requires special handling in C++ because it accepts either a type or
4408 /// an expression, and we need to disambiguate which is which. However, we
4409 /// cannot use the same logic as we've used for sizeof expressions, because
4410 /// that logic relies on the operator only accepting a single argument,
4411 /// whereas _Generic accepts a list of arguments.
4412 bool isTypeIdForGenericSelection() {
4413 if (getLangOpts().CPlusPlus) {
4414 bool isAmbiguous;
4416 isAmbiguous);
4417 }
4418 return isTypeSpecifierQualifier(Tok);
4419 }
4420
4421 /// Checks if the current tokens form type-id or expression.
4422 /// It is similar to isTypeIdInParens but does not suppose that type-id
4423 /// is in parenthesis.
4424 bool isTypeIdUnambiguously() {
4425 if (getLangOpts().CPlusPlus) {
4426 bool isAmbiguous;
4427 return isCXXTypeId(TentativeCXXTypeIdContext::Unambiguous, isAmbiguous);
4428 }
4429 return isTypeSpecifierQualifier(Tok);
4430 }
4431
4432 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
4433 ///
4434 /// \verbatim
4435 /// [clang] block-id:
4436 /// [clang] specifier-qualifier-list block-declarator
4437 /// \endverbatim
4438 void ParseBlockId(SourceLocation CaretLoc);
4439
4440 /// Parse availability query specification.
4441 ///
4442 /// \verbatim
4443 /// availability-spec:
4444 /// '*'
4445 /// identifier version-tuple
4446 /// \endverbatim
4447 std::optional<AvailabilitySpec> ParseAvailabilitySpec();
4448 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
4449
4450 /// Tries to parse cast part of OpenMP array shaping operation:
4451 /// \verbatim
4452 /// '[' expression ']' { '[' expression ']' } ')'
4453 /// \endverbatim
4454 bool tryParseOpenMPArrayShapingCastPart();
4455
4456 ExprResult ParseBuiltinPtrauthTypeDiscriminator();
4457
4458 ///@}
4459
4460 //
4461 //
4462 // -------------------------------------------------------------------------
4463 //
4464 //
4465
4466 /// \name C++ Expressions
4467 /// Implementations are in ParseExprCXX.cpp
4468 ///@{
4469
4470public:
4471 /// Parse a C++ unqualified-id (or a C identifier), which describes the
4472 /// name of an entity.
4473 ///
4474 /// \verbatim
4475 /// unqualified-id: [C++ expr.prim.general]
4476 /// identifier
4477 /// operator-function-id
4478 /// conversion-function-id
4479 /// [C++0x] literal-operator-id [TODO]
4480 /// ~ class-name
4481 /// template-id
4482 /// \endverbatim
4483 ///
4484 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
4485 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
4486 ///
4487 /// \param ObjectType if this unqualified-id occurs within a member access
4488 /// expression, the type of the base object whose member is being accessed.
4489 ///
4490 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4491 /// access expression, indicates whether the original subexpressions had any
4492 /// errors. When true, diagnostics for missing 'template' keyword will be
4493 /// supressed.
4494 ///
4495 /// \param EnteringContext whether we are entering the scope of the
4496 /// nested-name-specifier.
4497 ///
4498 /// \param AllowDestructorName whether we allow parsing of a destructor name.
4499 ///
4500 /// \param AllowConstructorName whether we allow parsing a constructor name.
4501 ///
4502 /// \param AllowDeductionGuide whether we allow parsing a deduction guide
4503 /// name.
4504 ///
4505 /// \param Result on a successful parse, contains the parsed unqualified-id.
4506 ///
4507 /// \returns true if parsing fails, false otherwise.
4508 bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
4509 bool ObjectHadErrors, bool EnteringContext,
4510 bool AllowDestructorName, bool AllowConstructorName,
4511 bool AllowDeductionGuide,
4512 SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
4513
4514private:
4515 /// ColonIsSacred - When this is false, we aggressively try to recover from
4516 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not
4517 /// safe in case statements and a few other things. This is managed by the
4518 /// ColonProtectionRAIIObject RAII object.
4519 bool ColonIsSacred;
4520
4521 // ParsingGenericAssociationType - Currently parsing the typename in
4522 // _Generic association. This is to consume the colon if what comes after it
4523 // is a type.
4524 bool ParsingGenericAssociationType;
4525
4526 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
4527 /// parenthesized ambiguous type-id. This uses tentative parsing to
4528 /// disambiguate based on the context past the parens.
4529 ExprResult ParseCXXAmbiguousParenExpression(
4530 ParenParseOption &ExprType, ParsedType &CastTy,
4532
4533 //===--------------------------------------------------------------------===//
4534 // C++ Expressions
4535 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand);
4536
4537 ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4538 ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
4539
4540 /// ParseCXXIdExpression - Handle id-expression.
4541 ///
4542 /// \verbatim
4543 /// id-expression:
4544 /// unqualified-id
4545 /// qualified-id
4546 ///
4547 /// qualified-id:
4548 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4549 /// '::' identifier
4550 /// '::' operator-function-id
4551 /// '::' template-id
4552 ///
4553 /// NOTE: The standard specifies that, for qualified-id, the parser does not
4554 /// expect:
4555 ///
4556 /// '::' conversion-function-id
4557 /// '::' '~' class-name
4558 /// \endverbatim
4559 ///
4560 /// This may cause a slight inconsistency on diagnostics:
4561 ///
4562 /// class C {};
4563 /// namespace A {}
4564 /// void f() {
4565 /// :: A :: ~ C(); // Some Sema error about using destructor with a
4566 /// // namespace.
4567 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
4568 /// }
4569 ///
4570 /// We simplify the parser a bit and make it work like:
4571 ///
4572 /// \verbatim
4573 /// qualified-id:
4574 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
4575 /// '::' unqualified-id
4576 /// \endverbatim
4577 ///
4578 /// That way Sema can handle and report similar errors for namespaces and the
4579 /// global scope.
4580 ///
4581 /// The isAddressOfOperand parameter indicates that this id-expression is a
4582 /// direct operand of the address-of operator. This is, besides member
4583 /// contexts, the only place where a qualified-id naming a non-static class
4584 /// member may appear.
4585 ///
4586 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
4587
4588 // Are the two tokens adjacent in the same source file?
4589 bool areTokensAdjacent(const Token &A, const Token &B);
4590
4591 // Check for '<::' which should be '< ::' instead of '[:' when following
4592 // a template name.
4593 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
4594 bool EnteringContext, IdentifierInfo &II,
4595 CXXScopeSpec &SS);
4596
4597 /// Parse global scope or nested-name-specifier if present.
4598 ///
4599 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
4600 /// may be preceded by '::'). Note that this routine will not parse ::new or
4601 /// ::delete; it will just leave them in the token stream.
4602 ///
4603 /// \verbatim
4604 /// '::'[opt] nested-name-specifier
4605 /// '::'
4606 ///
4607 /// nested-name-specifier:
4608 /// type-name '::'
4609 /// namespace-name '::'
4610 /// nested-name-specifier identifier '::'
4611 /// nested-name-specifier 'template'[opt] simple-template-id '::'
4612 /// \endverbatim
4613 ///
4614 ///
4615 /// \param SS the scope specifier that will be set to the parsed
4616 /// nested-name-specifier (or empty)
4617 ///
4618 /// \param ObjectType if this nested-name-specifier is being parsed following
4619 /// the "." or "->" of a member access expression, this parameter provides the
4620 /// type of the object whose members are being accessed.
4621 ///
4622 /// \param ObjectHadErrors if this unqualified-id occurs within a member
4623 /// access expression, indicates whether the original subexpressions had any
4624 /// errors. When true, diagnostics for missing 'template' keyword will be
4625 /// supressed.
4626 ///
4627 /// \param EnteringContext whether we will be entering into the context of
4628 /// the nested-name-specifier after parsing it.
4629 ///
4630 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
4631 /// indicates whether this nested-name-specifier may be part of a
4632 /// pseudo-destructor name. In this case, the flag will be set false
4633 /// if we don't actually end up parsing a destructor name. Moreover,
4634 /// if we do end up determining that we are parsing a destructor name,
4635 /// the last component of the nested-name-specifier is not parsed as
4636 /// part of the scope specifier.
4637 ///
4638 /// \param IsTypename If \c true, this nested-name-specifier is known to be
4639 /// part of a type name. This is used to improve error recovery.
4640 ///
4641 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
4642 /// filled in with the leading identifier in the last component of the
4643 /// nested-name-specifier, if any.
4644 ///
4645 /// \param OnlyNamespace If true, only considers namespaces in lookup.
4646 ///
4647 /// \param IsAddressOfOperand A hint indicating the expression is part of
4648 /// an address-of operation (e.g. '&'). Used by code completion to filter
4649 /// results; may not be set by all callers.
4650 ///
4651 /// \param IsInDeclarationContext A hint indicating whether the current
4652 /// context is likely a declaration. Used by code completion to filter
4653 /// results; may not be set by all callers.
4654 ///
4655 ///
4656 /// \returns true if there was an error parsing a scope specifier
4657 bool ParseOptionalCXXScopeSpecifier(
4658 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
4659 bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
4660 bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
4661 bool OnlyNamespace = false, bool InUsingDeclaration = false,
4662 bool Disambiguation = false, bool IsAddressOfOperand = false,
4663 bool IsInDeclarationContext = false);
4664
4665 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType,
4666 bool ObjectHasErrors,
4667 bool EnteringContext,
4668 bool IsAddressOfOperand) {
4669 return ParseOptionalCXXScopeSpecifier(
4670 SS, ObjectType, ObjectHasErrors, EnteringContext,
4671 /*MayBePseudoDestructor=*/nullptr,
4672 /*IsTypename=*/false,
4673 /*LastII=*/nullptr,
4674 /*OnlyNamespace=*/false,
4675 /*InUsingDeclaration=*/false,
4676 /*Disambiguation=*/false,
4677 /*IsAddressOfOperand=*/IsAddressOfOperand);
4678 }
4679
4680 //===--------------------------------------------------------------------===//
4681 // C++11 5.1.2: Lambda expressions
4682
4683 /// Result of tentatively parsing a lambda-introducer.
4684 enum class LambdaIntroducerTentativeParse {
4685 /// This appears to be a lambda-introducer, which has been fully parsed.
4686 Success,
4687 /// This is a lambda-introducer, but has not been fully parsed, and this
4688 /// function needs to be called again to parse it.
4689 Incomplete,
4690 /// This is definitely an Objective-C message send expression, rather than
4691 /// a lambda-introducer, attribute-specifier, or array designator.
4692 MessageSend,
4693 /// This is not a lambda-introducer.
4694 Invalid,
4695 };
4696
4697 /// ParseLambdaExpression - Parse a C++11 lambda expression.
4698 ///
4699 /// \verbatim
4700 /// lambda-expression:
4701 /// lambda-introducer lambda-declarator compound-statement
4702 /// lambda-introducer '<' template-parameter-list '>'
4703 /// requires-clause[opt] lambda-declarator compound-statement
4704 ///
4705 /// lambda-introducer:
4706 /// '[' lambda-capture[opt] ']'
4707 ///
4708 /// lambda-capture:
4709 /// capture-default
4710 /// capture-list
4711 /// capture-default ',' capture-list
4712 ///
4713 /// capture-default:
4714 /// '&'
4715 /// '='
4716 ///
4717 /// capture-list:
4718 /// capture
4719 /// capture-list ',' capture
4720 ///
4721 /// capture:
4722 /// simple-capture
4723 /// init-capture [C++1y]
4724 ///
4725 /// simple-capture:
4726 /// identifier
4727 /// '&' identifier
4728 /// 'this'
4729 ///
4730 /// init-capture: [C++1y]
4731 /// identifier initializer
4732 /// '&' identifier initializer
4733 ///
4734 /// lambda-declarator:
4735 /// lambda-specifiers [C++23]
4736 /// '(' parameter-declaration-clause ')' lambda-specifiers
4737 /// requires-clause[opt]
4738 ///
4739 /// lambda-specifiers:
4740 /// decl-specifier-seq[opt] noexcept-specifier[opt]
4741 /// attribute-specifier-seq[opt] trailing-return-type[opt]
4742 /// \endverbatim
4743 ///
4744 ExprResult ParseLambdaExpression();
4745
4746 /// Use lookahead and potentially tentative parsing to determine if we are
4747 /// looking at a C++11 lambda expression, and parse it if we are.
4748 ///
4749 /// If we are not looking at a lambda expression, returns ExprError().
4750 ExprResult TryParseLambdaExpression();
4751
4752 /// Parse a lambda introducer.
4753 /// \param Intro A LambdaIntroducer filled in with information about the
4754 /// contents of the lambda-introducer.
4755 /// \param Tentative If non-null, we are disambiguating between a
4756 /// lambda-introducer and some other construct. In this mode, we do not
4757 /// produce any diagnostics or take any other irreversible action
4758 /// unless we're sure that this is a lambda-expression.
4759 /// \return \c true if parsing (or disambiguation) failed with a diagnostic
4760 /// and the caller should bail out / recover.
4761 bool
4762 ParseLambdaIntroducer(LambdaIntroducer &Intro,
4763 LambdaIntroducerTentativeParse *Tentative = nullptr);
4764
4765 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
4766 /// expression.
4767 ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
4768
4769 /// Whether the current token can begin a lambda specifier sequence.
4770 bool isLambdaSpecifier();
4771
4772 //===--------------------------------------------------------------------===//
4773 // C++ 5.2p1: C++ Casts
4774
4775 /// ParseCXXCasts - This handles the various ways to cast expressions to
4776 /// another type.
4777 ///
4778 /// \verbatim
4779 /// postfix-expression: [C++ 5.2p1]
4780 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
4781 /// 'static_cast' '<' type-name '>' '(' expression ')'
4782 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
4783 /// 'const_cast' '<' type-name '>' '(' expression ')'
4784 /// \endverbatim
4785 ///
4786 /// C++ for OpenCL s2.3.1 adds:
4787 /// 'addrspace_cast' '<' type-name '>' '(' expression ')'
4788 ExprResult ParseCXXCasts();
4789
4790 /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
4791 ExprResult ParseBuiltinBitCast();
4792
4793 //===--------------------------------------------------------------------===//
4794 // C++ 5.2p1: C++ Type Identification
4795
4796 /// ParseCXXTypeid - This handles the C++ typeid expression.
4797 ///
4798 /// \verbatim
4799 /// postfix-expression: [C++ 5.2p1]
4800 /// 'typeid' '(' expression ')'
4801 /// 'typeid' '(' type-id ')'
4802 /// \endverbatim
4803 ///
4804 ExprResult ParseCXXTypeid();
4805
4806 //===--------------------------------------------------------------------===//
4807 // C++ : Microsoft __uuidof Expression
4808
4809 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
4810 ///
4811 /// \verbatim
4812 /// '__uuidof' '(' expression ')'
4813 /// '__uuidof' '(' type-id ')'
4814 /// \endverbatim
4815 ///
4816 ExprResult ParseCXXUuidof();
4817
4818 //===--------------------------------------------------------------------===//
4819 // C++ 5.2.4: C++ Pseudo-Destructor Expressions
4820
4821 /// Parse a C++ pseudo-destructor expression after the base,
4822 /// . or -> operator, and nested-name-specifier have already been
4823 /// parsed. We're handling this fragment of the grammar:
4824 ///
4825 /// \verbatim
4826 /// postfix-expression: [C++2a expr.post]
4827 /// postfix-expression . template[opt] id-expression
4828 /// postfix-expression -> template[opt] id-expression
4829 ///
4830 /// id-expression:
4831 /// qualified-id
4832 /// unqualified-id
4833 ///
4834 /// qualified-id:
4835 /// nested-name-specifier template[opt] unqualified-id
4836 ///
4837 /// nested-name-specifier:
4838 /// type-name ::
4839 /// decltype-specifier :: FIXME: not implemented, but probably only
4840 /// allowed in C++ grammar by accident
4841 /// nested-name-specifier identifier ::
4842 /// nested-name-specifier template[opt] simple-template-id ::
4843 /// [...]
4844 ///
4845 /// unqualified-id:
4846 /// ~ type-name
4847 /// ~ decltype-specifier
4848 /// [...]
4849 /// \endverbatim
4850 ///
4851 /// ... where the all but the last component of the nested-name-specifier
4852 /// has already been parsed, and the base expression is not of a non-dependent
4853 /// class type.
4854 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
4855 tok::TokenKind OpKind, CXXScopeSpec &SS,
4856 ParsedType ObjectType);
4857
4858 //===--------------------------------------------------------------------===//
4859 // C++ 9.3.2: C++ 'this' pointer
4860
4861 /// ParseCXXThis - This handles the C++ 'this' pointer.
4862 ///
4863 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
4864 /// is a non-lvalue expression whose value is the address of the object for
4865 /// which the function is called.
4866 ExprResult ParseCXXThis();
4867
4868 //===--------------------------------------------------------------------===//
4869 // C++ 15: C++ Throw Expression
4870
4871 /// ParseThrowExpression - This handles the C++ throw expression.
4872 ///
4873 /// \verbatim
4874 /// throw-expression: [C++ 15]
4875 /// 'throw' assignment-expression[opt]
4876 /// \endverbatim
4877 ExprResult ParseThrowExpression();
4878
4879 //===--------------------------------------------------------------------===//
4880 // C++ 2.13.5: C++ Boolean Literals
4881
4882 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
4883 ///
4884 /// \verbatim
4885 /// boolean-literal: [C++ 2.13.5]
4886 /// 'true'
4887 /// 'false'
4888 /// \endverbatim
4889 ExprResult ParseCXXBoolLiteral();
4890
4891 //===--------------------------------------------------------------------===//
4892 // C++ 5.2.3: Explicit type conversion (functional notation)
4893
4894 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
4895 /// Can be interpreted either as function-style casting ("int(x)")
4896 /// or class type construction ("ClassType(x,y,z)")
4897 /// or creation of a value-initialized type ("int()").
4898 /// See [C++ 5.2.3].
4899 ///
4900 /// \verbatim
4901 /// postfix-expression: [C++ 5.2p1]
4902 /// simple-type-specifier '(' expression-list[opt] ')'
4903 /// [C++0x] simple-type-specifier braced-init-list
4904 /// typename-specifier '(' expression-list[opt] ')'
4905 /// [C++0x] typename-specifier braced-init-list
4906 /// \endverbatim
4907 ///
4908 /// In C++1z onwards, the type specifier can also be a template-name.
4909 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
4910
4911 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
4912 /// This should only be called when the current token is known to be part of
4913 /// simple-type-specifier.
4914 ///
4915 /// \verbatim
4916 /// simple-type-specifier:
4917 /// '::'[opt] nested-name-specifier[opt] type-name
4918 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
4919 /// char
4920 /// wchar_t
4921 /// bool
4922 /// short
4923 /// int
4924 /// long
4925 /// signed
4926 /// unsigned
4927 /// float
4928 /// double
4929 /// void
4930 /// [GNU] typeof-specifier
4931 /// [C++0x] auto [TODO]
4932 ///
4933 /// type-name:
4934 /// class-name
4935 /// enum-name
4936 /// typedef-name
4937 /// \endverbatim
4938 ///
4939 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
4940
4941 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
4942 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
4943 /// e.g., "const short int". Note that the DeclSpec is *not* finished
4944 /// by parsing the type-specifier-seq, because these sequences are
4945 /// typically followed by some form of declarator. Returns true and
4946 /// emits diagnostics if this is not a type-specifier-seq, false
4947 /// otherwise.
4948 ///
4949 /// \verbatim
4950 /// type-specifier-seq: [C++ 8.1]
4951 /// type-specifier type-specifier-seq[opt]
4952 /// \endverbatim
4953 ///
4954 bool ParseCXXTypeSpecifierSeq(
4955 DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
4956
4957 //===--------------------------------------------------------------------===//
4958 // C++ 5.3.4 and 5.3.5: C++ new and delete
4959
4960 /// ParseExpressionListOrTypeId - Parse either an expression-list or a
4961 /// type-id. This ambiguity appears in the syntax of the C++ new operator.
4962 ///
4963 /// \verbatim
4964 /// new-expression:
4965 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4966 /// new-initializer[opt]
4967 ///
4968 /// new-placement:
4969 /// '(' expression-list ')'
4970 /// \endverbatim
4971 ///
4972 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr *> &Exprs,
4973 Declarator &D);
4974
4975 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
4976 /// passed to ParseDeclaratorInternal.
4977 ///
4978 /// \verbatim
4979 /// direct-new-declarator:
4980 /// '[' expression[opt] ']'
4981 /// direct-new-declarator '[' constant-expression ']'
4982 /// \endverbatim
4983 ///
4984 void ParseDirectNewDeclarator(Declarator &D);
4985
4986 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to
4987 /// allocate memory in a typesafe manner and call constructors.
4988 ///
4989 /// This method is called to parse the new expression after the optional ::
4990 /// has been already parsed. If the :: was present, "UseGlobal" is true and
4991 /// "Start" is its location. Otherwise, "Start" is the location of the 'new'
4992 /// token.
4993 ///
4994 /// \verbatim
4995 /// new-expression:
4996 /// '::'[opt] 'new' new-placement[opt] new-type-id
4997 /// new-initializer[opt]
4998 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
4999 /// new-initializer[opt]
5000 ///
5001 /// new-placement:
5002 /// '(' expression-list ')'
5003 ///
5004 /// new-type-id:
5005 /// type-specifier-seq new-declarator[opt]
5006 /// [GNU] attributes type-specifier-seq new-declarator[opt]
5007 ///
5008 /// new-declarator:
5009 /// ptr-operator new-declarator[opt]
5010 /// direct-new-declarator
5011 ///
5012 /// new-initializer:
5013 /// '(' expression-list[opt] ')'
5014 /// [C++0x] braced-init-list
5015 /// \endverbatim
5016 ///
5017 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
5018
5019 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
5020 /// to free memory allocated by new.
5021 ///
5022 /// This method is called to parse the 'delete' expression after the optional
5023 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is
5024 /// true and "Start" is its location. Otherwise, "Start" is the location of
5025 /// the 'delete' token.
5026 ///
5027 /// \verbatim
5028 /// delete-expression:
5029 /// '::'[opt] 'delete' cast-expression
5030 /// '::'[opt] 'delete' '[' ']' cast-expression
5031 /// \endverbatim
5032 ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start);
5033
5034 //===--------------------------------------------------------------------===//
5035 // C++ if/switch/while/for condition expression.
5036
5037 /// ParseCondition - if/switch/while condition expression.
5038 ///
5039 /// \verbatim
5040 /// condition:
5041 /// expression
5042 /// type-specifier-seq declarator '=' assignment-expression
5043 /// [C++11] type-specifier-seq declarator '=' initializer-clause
5044 /// [C++11] type-specifier-seq declarator braced-init-list
5045 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
5046 /// brace-or-equal-initializer
5047 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
5048 /// '=' assignment-expression
5049 /// \endverbatim
5050 ///
5051 /// In C++1z, a condition may in some contexts be preceded by an
5052 /// optional init-statement. This function will parse that too.
5053 ///
5054 /// \param InitStmt If non-null, an init-statement is permitted, and if
5055 /// present will be parsed and stored here.
5056 ///
5057 /// \param Loc The location of the start of the statement that requires this
5058 /// condition, e.g., the "for" in a for loop.
5059 ///
5060 /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
5061 /// it is considered an error to be recovered from.
5062 ///
5063 /// \param FRI If non-null, a for range declaration is permitted, and if
5064 /// present will be parsed and stored here, and a null result will be
5065 /// returned.
5066 ///
5067 /// \param AfterInitStmt Whether an init-statement has already been parsed
5068 /// for this condition, so a null \p InitStmt means "the init-statement slot
5069 /// is used up" rather than "no init-statement is permitted here".
5070 ///
5071 /// \returns The parsed condition.
5072 Sema::ConditionResult ParseCondition(StmtResult *InitStmt, SourceLocation Loc,
5073 Sema::ConditionKind CK, bool MissingOK,
5074 ForRangeInfo *FRI = nullptr,
5075 bool AfterInitStmt = false);
5076 DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
5077 ParsedAttributes &Attrs);
5078
5079 //===--------------------------------------------------------------------===//
5080 // C++ Coroutines
5081
5082 /// Parse the C++ Coroutines co_yield expression.
5083 ///
5084 /// \verbatim
5085 /// co_yield-expression:
5086 /// 'co_yield' assignment-expression[opt]
5087 /// \endverbatim
5088 ExprResult ParseCoyieldExpression();
5089
5090 //===--------------------------------------------------------------------===//
5091 // C++ Concepts
5092
5093 /// ParseRequiresExpression - Parse a C++2a requires-expression.
5094 /// C++2a [expr.prim.req]p1
5095 /// A requires-expression provides a concise way to express requirements
5096 /// on template arguments. A requirement is one that can be checked by
5097 /// name lookup (6.4) or by checking properties of types and expressions.
5098 ///
5099 /// \verbatim
5100 /// requires-expression:
5101 /// 'requires' requirement-parameter-list[opt] requirement-body
5102 ///
5103 /// requirement-parameter-list:
5104 /// '(' parameter-declaration-clause[opt] ')'
5105 ///
5106 /// requirement-body:
5107 /// '{' requirement-seq '}'
5108 ///
5109 /// requirement-seq:
5110 /// requirement
5111 /// requirement-seq requirement
5112 ///
5113 /// requirement:
5114 /// simple-requirement
5115 /// type-requirement
5116 /// compound-requirement
5117 /// nested-requirement
5118 /// \endverbatim
5119 ExprResult ParseRequiresExpression();
5120
5121 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
5122 /// whether the parens contain an expression or a type-id.
5123 /// Returns true for a type-id and false for an expression.
5124 bool isTypeIdInParens(bool &isAmbiguous) {
5125 if (getLangOpts().CPlusPlus)
5126 return isCXXTypeId(TentativeCXXTypeIdContext::InParens, isAmbiguous);
5127 isAmbiguous = false;
5128 return isTypeSpecifierQualifier(Tok);
5129 }
5130 bool isTypeIdInParens() {
5131 bool isAmbiguous;
5132 return isTypeIdInParens(isAmbiguous);
5133 }
5134
5135 /// Finish parsing a C++ unqualified-id that is a template-id of
5136 /// some form.
5137 ///
5138 /// This routine is invoked when a '<' is encountered after an identifier or
5139 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
5140 /// whether the unqualified-id is actually a template-id. This routine will
5141 /// then parse the template arguments and form the appropriate template-id to
5142 /// return to the caller.
5143 ///
5144 /// \param SS the nested-name-specifier that precedes this template-id, if
5145 /// we're actually parsing a qualified-id.
5146 ///
5147 /// \param ObjectType if this unqualified-id occurs within a member access
5148 /// expression, the type of the base object whose member is being accessed.
5149 ///
5150 /// \param ObjectHadErrors this unqualified-id occurs within a member access
5151 /// expression, indicates whether the original subexpressions had any errors.
5152 ///
5153 /// \param Name for constructor and destructor names, this is the actual
5154 /// identifier that may be a template-name.
5155 ///
5156 /// \param NameLoc the location of the class-name in a constructor or
5157 /// destructor.
5158 ///
5159 /// \param EnteringContext whether we're entering the scope of the
5160 /// nested-name-specifier.
5161 ///
5162 /// \param Id as input, describes the template-name or operator-function-id
5163 /// that precedes the '<'. If template arguments were parsed successfully,
5164 /// will be updated with the template-id.
5165 ///
5166 /// \param AssumeTemplateId When true, this routine will assume that the name
5167 /// refers to a template without performing name lookup to verify.
5168 ///
5169 /// \returns true if a parse error occurred, false otherwise.
5170 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType,
5171 bool ObjectHadErrors,
5172 SourceLocation TemplateKWLoc,
5173 IdentifierInfo *Name,
5174 SourceLocation NameLoc,
5175 bool EnteringContext, UnqualifiedId &Id,
5176 bool AssumeTemplateId);
5177
5178 /// Parse an operator-function-id or conversion-function-id as part
5179 /// of a C++ unqualified-id.
5180 ///
5181 /// This routine is responsible only for parsing the operator-function-id or
5182 /// conversion-function-id; it does not handle template arguments in any way.
5183 ///
5184 /// \verbatim
5185 /// operator-function-id: [C++ 13.5]
5186 /// 'operator' operator
5187 ///
5188 /// operator: one of
5189 /// new delete new[] delete[]
5190 /// + - * / % ^ & | ~
5191 /// ! = < > += -= *= /= %=
5192 /// ^= &= |= << >> >>= <<= == !=
5193 /// <= >= && || ++ -- , ->* ->
5194 /// () [] <=>
5195 ///
5196 /// conversion-function-id: [C++ 12.3.2]
5197 /// operator conversion-type-id
5198 ///
5199 /// conversion-type-id:
5200 /// type-specifier-seq conversion-declarator[opt]
5201 ///
5202 /// conversion-declarator:
5203 /// ptr-operator conversion-declarator[opt]
5204 /// \endverbatim
5205 ///
5206 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
5207 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
5208 ///
5209 /// \param EnteringContext whether we are entering the scope of the
5210 /// nested-name-specifier.
5211 ///
5212 /// \param ObjectType if this unqualified-id occurs within a member access
5213 /// expression, the type of the base object whose member is being accessed.
5214 ///
5215 /// \param Result on a successful parse, contains the parsed unqualified-id.
5216 ///
5217 /// \returns true if parsing fails, false otherwise.
5218 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
5219 ParsedType ObjectType, UnqualifiedId &Result);
5220
5221 //===--------------------------------------------------------------------===//
5222 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
5223
5224 /// Parse the built-in type-trait pseudo-functions that allow
5225 /// implementation of the TR1/C++11 type traits templates.
5226 ///
5227 /// \verbatim
5228 /// primary-expression:
5229 /// unary-type-trait '(' type-id ')'
5230 /// binary-type-trait '(' type-id ',' type-id ')'
5231 /// type-trait '(' type-id-seq ')'
5232 ///
5233 /// type-id-seq:
5234 /// type-id ...[opt] type-id-seq[opt]
5235 /// \endverbatim
5236 ///
5237 ExprResult ParseTypeTrait();
5238
5239 //===--------------------------------------------------------------------===//
5240 // Embarcadero: Arary and Expression Traits
5241
5242 /// ParseArrayTypeTrait - Parse the built-in array type-trait
5243 /// pseudo-functions.
5244 ///
5245 /// \verbatim
5246 /// primary-expression:
5247 /// [Embarcadero] '__array_rank' '(' type-id ')'
5248 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
5249 /// \endverbatim
5250 ///
5251 ExprResult ParseArrayTypeTrait();
5252
5253 /// ParseExpressionTrait - Parse built-in expression-trait
5254 /// pseudo-functions like __is_lvalue_expr( xxx ).
5255 ///
5256 /// \verbatim
5257 /// primary-expression:
5258 /// [Embarcadero] expression-trait '(' expression ')'
5259 /// \endverbatim
5260 ///
5261 ExprResult ParseExpressionTrait();
5262
5263 ///@}
5264
5265 //===--------------------------------------------------------------------===//
5266 // Reflection parsing
5267
5268 /// ParseCXXReflectExpression - parses the operand of reflection operator.
5269 ///
5270 /// \returns on success, an expression holding the constructed CXXReflectExpr;
5271 /// on failure, an ExprError.
5272 ExprResult ParseCXXReflectExpression();
5273
5274 //
5275 //
5276 // -------------------------------------------------------------------------
5277 //
5278 //
5279
5280 /// \name HLSL Constructs
5281 /// Implementations are in ParseHLSL.cpp
5282 ///@{
5283
5284private:
5285 bool MaybeParseHLSLAnnotations(Declarator &D,
5286 SourceLocation *EndLoc = nullptr,
5287 bool CouldBeBitField = false) {
5288 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5289 if (Tok.is(tok::colon)) {
5290 ParsedAttributes Attrs(AttrFactory);
5291 ParseHLSLAnnotations(Attrs, EndLoc, CouldBeBitField);
5292 D.takeAttributesAppending(Attrs);
5293 return true;
5294 }
5295 return false;
5296 }
5297
5298 void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
5299 SourceLocation *EndLoc = nullptr) {
5300 assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
5301 if (Tok.is(tok::colon))
5302 ParseHLSLAnnotations(Attrs, EndLoc);
5303 }
5304
5305 struct ParsedSemantic {
5306 StringRef Name = "";
5307 unsigned Index = 0;
5308 bool Explicit = false;
5309 };
5310
5311 ParsedSemantic ParseHLSLSemantic();
5312
5313 void ParseHLSLAnnotations(ParsedAttributes &Attrs,
5314 SourceLocation *EndLoc = nullptr,
5315 bool CouldBeBitField = false);
5316 Decl *ParseHLSLBuffer(SourceLocation &DeclEnd, ParsedAttributes &Attrs);
5317
5318 ///@}
5319
5320 //
5321 //
5322 // -------------------------------------------------------------------------
5323 //
5324 //
5325
5326 /// \name Initializers
5327 /// Implementations are in ParseInit.cpp
5328 ///@{
5329
5330private:
5331 //===--------------------------------------------------------------------===//
5332 // C99 6.7.8: Initialization.
5333
5334 /// ParseInitializer
5335 /// \verbatim
5336 /// initializer: [C99 6.7.8]
5337 /// assignment-expression
5338 /// '{' ...
5339 /// \endverbatim
5340 ExprResult ParseInitializer(Decl *DeclForInitializer = nullptr);
5341
5342 /// MayBeDesignationStart - Return true if the current token might be the
5343 /// start of a designator. If we can tell it is impossible that it is a
5344 /// designator, return false.
5345 bool MayBeDesignationStart();
5346
5347 /// ParseBraceInitializer - Called when parsing an initializer that has a
5348 /// leading open brace.
5349 ///
5350 /// \verbatim
5351 /// initializer: [C99 6.7.8]
5352 /// '{' initializer-list '}'
5353 /// '{' initializer-list ',' '}'
5354 /// [C23] '{' '}'
5355 ///
5356 /// initializer-list:
5357 /// designation[opt] initializer ...[opt]
5358 /// initializer-list ',' designation[opt] initializer ...[opt]
5359 /// \endverbatim
5360 ///
5361 ExprResult ParseBraceInitializer();
5362
5363 /// ParseExpansionInitList - Called when the initializer of an expansion
5364 /// statement starts with an open brace.
5365 ///
5366 /// \verbatim
5367 /// expansion-init-list: [C++26 [stmt.expand]]
5368 /// '{' expression-list ','[opt] '}'
5369 /// '{' '}'
5370 /// \endverbatim
5371 ExprResult ParseExpansionInitList();
5372
5373 struct DesignatorCompletionInfo {
5374 SmallVectorImpl<Expr *> &InitExprs;
5375 QualType PreferredBaseType;
5376 };
5377
5378 /// ParseInitializerWithPotentialDesignator - Parse the 'initializer'
5379 /// production checking to see if the token stream starts with a designator.
5380 ///
5381 /// C99:
5382 ///
5383 /// \verbatim
5384 /// designation:
5385 /// designator-list '='
5386 /// [GNU] array-designator
5387 /// [GNU] identifier ':'
5388 ///
5389 /// designator-list:
5390 /// designator
5391 /// designator-list designator
5392 ///
5393 /// designator:
5394 /// array-designator
5395 /// '.' identifier
5396 ///
5397 /// array-designator:
5398 /// '[' constant-expression ']'
5399 /// [GNU] '[' constant-expression '...' constant-expression ']'
5400 /// \endverbatim
5401 ///
5402 /// C++20:
5403 ///
5404 /// \verbatim
5405 /// designated-initializer-list:
5406 /// designated-initializer-clause
5407 /// designated-initializer-list ',' designated-initializer-clause
5408 ///
5409 /// designated-initializer-clause:
5410 /// designator brace-or-equal-initializer
5411 ///
5412 /// designator:
5413 /// '.' identifier
5414 /// \endverbatim
5415 ///
5416 /// We allow the C99 syntax extensions in C++20, but do not allow the C++20
5417 /// extension (a braced-init-list after the designator with no '=') in C99.
5418 ///
5419 /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an
5420 /// initializer (because it is an expression). We need to consider this case
5421 /// when parsing array designators.
5422 ///
5423 /// \p CodeCompleteCB is called with Designation parsed so far.
5424 ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
5425
5426 ExprResult createEmbedExpr();
5427
5428 /// A SmallVector of expressions.
5429 typedef SmallVector<Expr *, 12> ExprVector;
5430
5431 // Return true if a comma (or closing brace) is necessary after the
5432 // __if_exists/if_not_exists statement.
5433 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
5434 bool &InitExprsOk);
5435
5436 ///@}
5437
5438 //
5439 //
5440 // -------------------------------------------------------------------------
5441 //
5442 //
5443
5444 /// \name Objective-C Constructs
5445 /// Implementations are in ParseObjc.cpp
5446 ///@{
5447
5448public:
5450 friend class ObjCDeclContextSwitch;
5451
5453 return Actions.ObjC().getObjCDeclContext();
5454 }
5455
5456 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
5457 /// to the given nullability kind.
5459 return Actions.getNullabilityKeyword(nullability);
5460 }
5461
5462private:
5463 /// Objective-C contextual keywords.
5464 IdentifierInfo *Ident_instancetype;
5465
5466 /// Ident_super - IdentifierInfo for "super", to support fast
5467 /// comparison.
5468 IdentifierInfo *Ident_super;
5469
5470 /// When true, we are directly inside an Objective-C message
5471 /// send expression.
5472 ///
5473 /// This is managed by the \c InMessageExpressionRAIIObject class, and
5474 /// should not be set directly.
5475 bool InMessageExpression;
5476
5477 /// True if we are within an Objective-C container while parsing C-like decls.
5478 ///
5479 /// This is necessary because Sema thinks we have left the container
5480 /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
5481 /// will be NULL.
5482 bool ParsingInObjCContainer;
5483
5484 /// Returns true if the current token is the identifier 'instancetype'.
5485 ///
5486 /// Should only be used in Objective-C language modes.
5487 bool isObjCInstancetype() {
5488 assert(getLangOpts().ObjC);
5489 if (Tok.isAnnotation())
5490 return false;
5491 if (!Ident_instancetype)
5492 Ident_instancetype = PP.getIdentifierInfo("instancetype");
5493 return Tok.getIdentifierInfo() == Ident_instancetype;
5494 }
5495
5496 /// ObjCDeclContextSwitch - An object used to switch context from
5497 /// an objective-c decl context to its enclosing decl context and
5498 /// back.
5499 class ObjCDeclContextSwitch {
5500 Parser &P;
5501 ObjCContainerDecl *DC;
5502 SaveAndRestore<bool> WithinObjCContainer;
5503
5504 public:
5505 explicit ObjCDeclContextSwitch(Parser &p)
5506 : P(p), DC(p.getObjCDeclContext()),
5507 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
5508 if (DC)
5509 P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(DC);
5510 }
5511 ~ObjCDeclContextSwitch() {
5512 if (DC)
5513 P.Actions.ObjC().ActOnObjCReenterContainerContext(DC);
5514 }
5515 };
5516
5517 void CheckNestedObjCContexts(SourceLocation AtLoc);
5518
5519 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
5520
5521 // Objective-C External Declarations
5522
5523 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
5524 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
5525
5526 /// ParseObjCAtDirectives - Handle parts of the external-declaration
5527 /// production:
5528 /// \verbatim
5529 /// external-declaration: [C99 6.9]
5530 /// [OBJC] objc-class-definition
5531 /// [OBJC] objc-class-declaration
5532 /// [OBJC] objc-alias-declaration
5533 /// [OBJC] objc-protocol-definition
5534 /// [OBJC] objc-method-definition
5535 /// [OBJC] '@' 'end'
5536 /// \endverbatim
5537 DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
5538 ParsedAttributes &DeclSpecAttrs);
5539
5540 ///
5541 /// \verbatim
5542 /// objc-class-declaration:
5543 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
5544 ///
5545 /// objc-class-forward-decl:
5546 /// identifier objc-type-parameter-list[opt]
5547 /// \endverbatim
5548 ///
5549 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
5550
5551 ///
5552 /// \verbatim
5553 /// objc-interface:
5554 /// objc-class-interface-attributes[opt] objc-class-interface
5555 /// objc-category-interface
5556 ///
5557 /// objc-class-interface:
5558 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5559 /// objc-superclass[opt] objc-protocol-refs[opt]
5560 /// objc-class-instance-variables[opt]
5561 /// objc-interface-decl-list
5562 /// @end
5563 ///
5564 /// objc-category-interface:
5565 /// '@' 'interface' identifier objc-type-parameter-list[opt]
5566 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
5567 /// objc-interface-decl-list
5568 /// @end
5569 ///
5570 /// objc-superclass:
5571 /// ':' identifier objc-type-arguments[opt]
5572 ///
5573 /// objc-class-interface-attributes:
5574 /// __attribute__((visibility("default")))
5575 /// __attribute__((visibility("hidden")))
5576 /// __attribute__((deprecated))
5577 /// __attribute__((unavailable))
5578 /// __attribute__((objc_exception)) - used by NSException on 64-bit
5579 /// __attribute__((objc_root_class))
5580 /// \endverbatim
5581 ///
5582 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
5583 ParsedAttributes &prefixAttrs);
5584
5585 /// Class to handle popping type parameters when leaving the scope.
5587
5588 /// Parse an objc-type-parameter-list.
5589 ObjCTypeParamList *parseObjCTypeParamList();
5590
5591 /// Parse an Objective-C type parameter list, if present, or capture
5592 /// the locations of the protocol identifiers for a list of protocol
5593 /// references.
5594 ///
5595 /// \verbatim
5596 /// objc-type-parameter-list:
5597 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
5598 ///
5599 /// objc-type-parameter:
5600 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
5601 ///
5602 /// objc-type-parameter-bound:
5603 /// ':' type-name
5604 ///
5605 /// objc-type-parameter-variance:
5606 /// '__covariant'
5607 /// '__contravariant'
5608 /// \endverbatim
5609 ///
5610 /// \param lAngleLoc The location of the starting '<'.
5611 ///
5612 /// \param protocolIdents Will capture the list of identifiers, if the
5613 /// angle brackets contain a list of protocol references rather than a
5614 /// type parameter list.
5615 ///
5616 /// \param rAngleLoc The location of the ending '>'.
5617 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
5618 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
5619 SmallVectorImpl<IdentifierLoc> &protocolIdents, SourceLocation &rAngleLoc,
5620 bool mayBeProtocolList = true);
5621
5622 void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
5623 SourceLocation atLoc,
5625 SmallVectorImpl<Decl *> &AllIvarDecls,
5626 bool RBraceMissing);
5627
5628 /// \verbatim
5629 /// objc-class-instance-variables:
5630 /// '{' objc-instance-variable-decl-list[opt] '}'
5631 ///
5632 /// objc-instance-variable-decl-list:
5633 /// objc-visibility-spec
5634 /// objc-instance-variable-decl ';'
5635 /// ';'
5636 /// objc-instance-variable-decl-list objc-visibility-spec
5637 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
5638 /// objc-instance-variable-decl-list static_assert-declaration
5639 /// objc-instance-variable-decl-list ';'
5640 ///
5641 /// objc-visibility-spec:
5642 /// @private
5643 /// @protected
5644 /// @public
5645 /// @package [OBJC2]
5646 ///
5647 /// objc-instance-variable-decl:
5648 /// struct-declaration
5649 /// \endverbatim
5650 ///
5651 void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
5652 tok::ObjCKeywordKind visibility,
5653 SourceLocation atLoc);
5654
5655 /// \verbatim
5656 /// objc-protocol-refs:
5657 /// '<' identifier-list '>'
5658 /// \endverbatim
5659 ///
5660 bool ParseObjCProtocolReferences(
5661 SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs,
5662 bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc,
5663 SourceLocation &EndProtoLoc, bool consumeLastToken);
5664
5665 /// Parse the first angle-bracket-delimited clause for an
5666 /// Objective-C object or object pointer type, which may be either
5667 /// type arguments or protocol qualifiers.
5668 ///
5669 /// \verbatim
5670 /// objc-type-arguments:
5671 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
5672 /// \endverbatim
5673 ///
5674 void parseObjCTypeArgsOrProtocolQualifiers(
5675 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5676 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5677 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5678 SmallVectorImpl<SourceLocation> &protocolLocs,
5679 SourceLocation &protocolRAngleLoc, bool consumeLastToken,
5680 bool warnOnIncompleteProtocols);
5681
5682 /// Parse either Objective-C type arguments or protocol qualifiers; if the
5683 /// former, also parse protocol qualifiers afterward.
5684 void parseObjCTypeArgsAndProtocolQualifiers(
5685 ParsedType baseType, SourceLocation &typeArgsLAngleLoc,
5686 SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc,
5687 SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols,
5688 SmallVectorImpl<SourceLocation> &protocolLocs,
5689 SourceLocation &protocolRAngleLoc, bool consumeLastToken);
5690
5691 /// Parse a protocol qualifier type such as '<NSCopying>', which is
5692 /// an anachronistic way of writing 'id<NSCopying>'.
5693 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
5694
5695 /// Parse Objective-C type arguments and protocol qualifiers, extending the
5696 /// current type with the parsed result.
5697 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
5699 bool consumeLastToken,
5700 SourceLocation &endLoc);
5701
5702 /// \verbatim
5703 /// objc-interface-decl-list:
5704 /// empty
5705 /// objc-interface-decl-list objc-property-decl [OBJC2]
5706 /// objc-interface-decl-list objc-method-requirement [OBJC2]
5707 /// objc-interface-decl-list objc-method-proto ';'
5708 /// objc-interface-decl-list declaration
5709 /// objc-interface-decl-list ';'
5710 ///
5711 /// objc-method-requirement: [OBJC2]
5712 /// @required
5713 /// @optional
5714 /// \endverbatim
5715 ///
5716 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl);
5717
5718 /// \verbatim
5719 /// objc-protocol-declaration:
5720 /// objc-protocol-definition
5721 /// objc-protocol-forward-reference
5722 ///
5723 /// objc-protocol-definition:
5724 /// \@protocol identifier
5725 /// objc-protocol-refs[opt]
5726 /// objc-interface-decl-list
5727 /// \@end
5728 ///
5729 /// objc-protocol-forward-reference:
5730 /// \@protocol identifier-list ';'
5731 /// \endverbatim
5732 ///
5733 /// "\@protocol identifier ;" should be resolved as "\@protocol
5734 /// identifier-list ;": objc-interface-decl-list may not start with a
5735 /// semicolon in the first alternative if objc-protocol-refs are omitted.
5736 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
5737 ParsedAttributes &prefixAttrs);
5738
5739 struct ObjCImplParsingDataRAII {
5740 Parser &P;
5741 Decl *Dcl;
5742 bool HasCFunction;
5743 typedef SmallVector<LexedMethod *, 8> LateParsedObjCMethodContainer;
5744 LateParsedObjCMethodContainer LateParsedObjCMethods;
5745
5746 ObjCImplParsingDataRAII(Parser &parser, Decl *D)
5747 : P(parser), Dcl(D), HasCFunction(false),
5748 PrevParsedObjCImpl(parser.CurParsedObjCImpl) {
5749 P.CurParsedObjCImpl = this;
5750 Finished = false;
5751 }
5752 ~ObjCImplParsingDataRAII();
5753
5754 void finish(SourceRange AtEnd);
5755 bool isFinished() const { return Finished; }
5756
5757 private:
5758 /// The \@implementation that was still open when this one started; made
5759 /// current again once this one finishes. Only invalid code has one: an
5760 /// \@implementation that starts while a previous \@implementation is
5761 /// still open (e.g. through an intervening namespace). For valid code
5762 /// this is always null.
5763 ObjCImplParsingDataRAII *PrevParsedObjCImpl;
5764 bool Finished;
5765 };
5766 ObjCImplParsingDataRAII *CurParsedObjCImpl;
5767
5768 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
5769 /// for later parsing.
5770 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
5771
5772 /// \verbatim
5773 /// objc-implementation:
5774 /// objc-class-implementation-prologue
5775 /// objc-category-implementation-prologue
5776 ///
5777 /// objc-class-implementation-prologue:
5778 /// @implementation identifier objc-superclass[opt]
5779 /// objc-class-instance-variables[opt]
5780 ///
5781 /// objc-category-implementation-prologue:
5782 /// @implementation identifier ( identifier )
5783 /// \endverbatim
5784 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
5785 ParsedAttributes &Attrs);
5786 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
5787
5788 /// \verbatim
5789 /// compatibility-alias-decl:
5790 /// @compatibility_alias alias-name class-name ';'
5791 /// \endverbatim
5792 ///
5793 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
5794
5795 /// \verbatim
5796 /// property-synthesis:
5797 /// @synthesize property-ivar-list ';'
5798 ///
5799 /// property-ivar-list:
5800 /// property-ivar
5801 /// property-ivar-list ',' property-ivar
5802 ///
5803 /// property-ivar:
5804 /// identifier
5805 /// identifier '=' identifier
5806 /// \endverbatim
5807 ///
5808 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
5809
5810 /// \verbatim
5811 /// property-dynamic:
5812 /// @dynamic property-list
5813 ///
5814 /// property-list:
5815 /// identifier
5816 /// property-list ',' identifier
5817 /// \endverbatim
5818 ///
5819 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
5820
5821 /// \verbatim
5822 /// objc-selector:
5823 /// identifier
5824 /// one of
5825 /// enum struct union if else while do for switch case default
5826 /// break continue return goto asm sizeof typeof __alignof
5827 /// unsigned long const short volatile signed restrict _Complex
5828 /// in out inout bycopy byref oneway int char float double void _Bool
5829 /// \endverbatim
5830 ///
5831 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
5832
5833 IdentifierInfo *ObjCTypeQuals[llvm::to_underlying(ObjCTypeQual::NumQuals)];
5834
5835 /// \verbatim
5836 /// objc-for-collection-in: 'in'
5837 /// \endverbatim
5838 ///
5839 bool isTokIdentifier_in() const;
5840
5841 /// \verbatim
5842 /// objc-type-name:
5843 /// '(' objc-type-qualifiers[opt] type-name ')'
5844 /// '(' objc-type-qualifiers[opt] ')'
5845 /// \endverbatim
5846 ///
5847 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
5848 ParsedAttributes *ParamAttrs);
5849
5850 /// \verbatim
5851 /// objc-method-proto:
5852 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
5853 /// objc-class-method objc-method-decl objc-method-attributes[opt]
5854 ///
5855 /// objc-instance-method: '-'
5856 /// objc-class-method: '+'
5857 ///
5858 /// objc-method-attributes: [OBJC2]
5859 /// __attribute__((deprecated))
5860 /// \endverbatim
5861 ///
5862 Decl *ParseObjCMethodPrototype(
5863 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5864 bool MethodDefinition = true);
5865
5866 /// \verbatim
5867 /// objc-method-decl:
5868 /// objc-selector
5869 /// objc-keyword-selector objc-parmlist[opt]
5870 /// objc-type-name objc-selector
5871 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
5872 ///
5873 /// objc-keyword-selector:
5874 /// objc-keyword-decl
5875 /// objc-keyword-selector objc-keyword-decl
5876 ///
5877 /// objc-keyword-decl:
5878 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
5879 /// objc-selector ':' objc-keyword-attributes[opt] identifier
5880 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
5881 /// ':' objc-keyword-attributes[opt] identifier
5882 ///
5883 /// objc-parmlist:
5884 /// objc-parms objc-ellipsis[opt]
5885 ///
5886 /// objc-parms:
5887 /// objc-parms , parameter-declaration
5888 ///
5889 /// objc-ellipsis:
5890 /// , ...
5891 ///
5892 /// objc-keyword-attributes: [OBJC2]
5893 /// __attribute__((unused))
5894 /// \endverbatim
5895 ///
5896 Decl *ParseObjCMethodDecl(
5897 SourceLocation mLoc, tok::TokenKind mType,
5898 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
5899 bool MethodDefinition = true);
5900
5901 /// Parse property attribute declarations.
5902 ///
5903 /// \verbatim
5904 /// property-attr-decl: '(' property-attrlist ')'
5905 /// property-attrlist:
5906 /// property-attribute
5907 /// property-attrlist ',' property-attribute
5908 /// property-attribute:
5909 /// getter '=' identifier
5910 /// setter '=' identifier ':'
5911 /// direct
5912 /// readonly
5913 /// readwrite
5914 /// assign
5915 /// retain
5916 /// copy
5917 /// nonatomic
5918 /// atomic
5919 /// strong
5920 /// weak
5921 /// unsafe_unretained
5922 /// nonnull
5923 /// nullable
5924 /// null_unspecified
5925 /// null_resettable
5926 /// class
5927 /// \endverbatim
5928 ///
5929 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
5930
5931 /// \verbatim
5932 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
5933 /// \endverbatim
5934 ///
5935 Decl *ParseObjCMethodDefinition();
5936
5937 //===--------------------------------------------------------------------===//
5938 // Objective-C Expressions
5939 ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
5940 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
5941
5942 /// ParseObjCCharacterLiteral -
5943 /// \verbatim
5944 /// objc-scalar-literal : '@' character-literal
5945 /// ;
5946 /// \endverbatim
5947 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
5948
5949 /// ParseObjCNumericLiteral -
5950 /// \verbatim
5951 /// objc-scalar-literal : '@' scalar-literal
5952 /// ;
5953 /// scalar-literal : | numeric-constant /* any numeric constant. */
5954 /// ;
5955 /// \endverbatim
5956 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
5957
5958 /// ParseObjCBooleanLiteral -
5959 /// \verbatim
5960 /// objc-scalar-literal : '@' boolean-keyword
5961 /// ;
5962 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
5963 /// ;
5964 /// \endverbatim
5965 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
5966
5967 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
5968 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
5969
5970 /// ParseObjCBoxedExpr -
5971 /// \verbatim
5972 /// objc-box-expression:
5973 /// @( assignment-expression )
5974 /// \endverbatim
5975 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
5976
5977 /// \verbatim
5978 /// objc-encode-expression:
5979 /// \@encode ( type-name )
5980 /// \endverbatim
5981 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
5982
5983 /// \verbatim
5984 /// objc-selector-expression
5985 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
5986 /// \endverbatim
5987 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
5988
5989 /// \verbatim
5990 /// objc-protocol-expression
5991 /// \@protocol ( protocol-name )
5992 /// \endverbatim
5993 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
5994
5995 /// Determine whether the parser is currently referring to a an
5996 /// Objective-C message send, using a simplified heuristic to avoid overhead.
5997 ///
5998 /// This routine will only return true for a subset of valid message-send
5999 /// expressions.
6000 bool isSimpleObjCMessageExpression();
6001
6002 /// \verbatim
6003 /// objc-message-expr:
6004 /// '[' objc-receiver objc-message-args ']'
6005 ///
6006 /// objc-receiver: [C]
6007 /// 'super'
6008 /// expression
6009 /// class-name
6010 /// type-name
6011 /// \endverbatim
6012 ///
6013 ExprResult ParseObjCMessageExpression();
6014
6015 /// Parse the remainder of an Objective-C message following the
6016 /// '[' objc-receiver.
6017 ///
6018 /// This routine handles sends to super, class messages (sent to a
6019 /// class name), and instance messages (sent to an object), and the
6020 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
6021 /// ReceiverExpr, respectively. Only one of these parameters may have
6022 /// a valid value.
6023 ///
6024 /// \param LBracLoc The location of the opening '['.
6025 ///
6026 /// \param SuperLoc If this is a send to 'super', the location of the
6027 /// 'super' keyword that indicates a send to the superclass.
6028 ///
6029 /// \param ReceiverType If this is a class message, the type of the
6030 /// class we are sending a message to.
6031 ///
6032 /// \param ReceiverExpr If this is an instance message, the expression
6033 /// used to compute the receiver object.
6034 ///
6035 /// \verbatim
6036 /// objc-message-args:
6037 /// objc-selector
6038 /// objc-keywordarg-list
6039 ///
6040 /// objc-keywordarg-list:
6041 /// objc-keywordarg
6042 /// objc-keywordarg-list objc-keywordarg
6043 ///
6044 /// objc-keywordarg:
6045 /// selector-name[opt] ':' objc-keywordexpr
6046 ///
6047 /// objc-keywordexpr:
6048 /// nonempty-expr-list
6049 ///
6050 /// nonempty-expr-list:
6051 /// assignment-expression
6052 /// nonempty-expr-list , assignment-expression
6053 /// \endverbatim
6054 ///
6055 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
6056 SourceLocation SuperLoc,
6057 ParsedType ReceiverType,
6058 Expr *ReceiverExpr);
6059
6060 /// Parse the receiver of an Objective-C++ message send.
6061 ///
6062 /// This routine parses the receiver of a message send in
6063 /// Objective-C++ either as a type or as an expression. Note that this
6064 /// routine must not be called to parse a send to 'super', since it
6065 /// has no way to return such a result.
6066 ///
6067 /// \param IsExpr Whether the receiver was parsed as an expression.
6068 ///
6069 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
6070 /// IsExpr is true), the parsed expression. If the receiver was parsed
6071 /// as a type (\c IsExpr is false), the parsed type.
6072 ///
6073 /// \returns True if an error occurred during parsing or semantic
6074 /// analysis, in which case the arguments do not have valid
6075 /// values. Otherwise, returns false for a successful parse.
6076 ///
6077 /// \verbatim
6078 /// objc-receiver: [C++]
6079 /// 'super' [not parsed here]
6080 /// expression
6081 /// simple-type-specifier
6082 /// typename-specifier
6083 /// \endverbatim
6084 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
6085
6086 //===--------------------------------------------------------------------===//
6087 // Objective-C Statements
6088
6089 enum class ParsedStmtContext;
6090
6091 StmtResult ParseObjCAtStatement(SourceLocation atLoc,
6092 ParsedStmtContext StmtCtx);
6093
6094 /// \verbatim
6095 /// objc-try-catch-statement:
6096 /// @try compound-statement objc-catch-list[opt]
6097 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
6098 ///
6099 /// objc-catch-list:
6100 /// @catch ( parameter-declaration ) compound-statement
6101 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
6102 /// catch-parameter-declaration:
6103 /// parameter-declaration
6104 /// '...' [OBJC2]
6105 /// \endverbatim
6106 ///
6107 StmtResult ParseObjCTryStmt(SourceLocation atLoc);
6108
6109 /// \verbatim
6110 /// objc-throw-statement:
6111 /// throw expression[opt];
6112 /// \endverbatim
6113 ///
6114 StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
6115
6116 /// \verbatim
6117 /// objc-synchronized-statement:
6118 /// @synchronized '(' expression ')' compound-statement
6119 /// \endverbatim
6120 ///
6121 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
6122
6123 /// \verbatim
6124 /// objc-autoreleasepool-statement:
6125 /// @autoreleasepool compound-statement
6126 /// \endverbatim
6127 ///
6128 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
6129
6130 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
6131 /// qualifier list and builds their bitmask representation in the input
6132 /// argument.
6133 ///
6134 /// \verbatim
6135 /// objc-type-qualifiers:
6136 /// objc-type-qualifier
6137 /// objc-type-qualifiers objc-type-qualifier
6138 ///
6139 /// objc-type-qualifier:
6140 /// 'in'
6141 /// 'out'
6142 /// 'inout'
6143 /// 'oneway'
6144 /// 'bycopy's
6145 /// 'byref'
6146 /// 'nonnull'
6147 /// 'nullable'
6148 /// 'null_unspecified'
6149 /// \endverbatim
6150 ///
6151 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context);
6152
6153 /// Determine whether we are currently at the start of an Objective-C
6154 /// class message that appears to be missing the open bracket '['.
6155 bool isStartOfObjCClassMessageMissingOpenBracket();
6156
6157 ///@}
6158
6159 //
6160 //
6161 // -------------------------------------------------------------------------
6162 //
6163 //
6164
6165 /// \name OpenACC Constructs
6166 /// Implementations are in ParseOpenACC.cpp
6167 ///@{
6168
6169public:
6171
6172 /// Parse OpenACC directive on a declaration.
6173 ///
6174 /// Placeholder for now, should just ignore the directives after emitting a
6175 /// diagnostic. Eventually will be split into a few functions to parse
6176 /// different situations.
6178 ParsedAttributes &Attrs,
6179 DeclSpec::TST TagType,
6180 Decl *TagDecl);
6181
6182 // Parse OpenACC Directive on a Statement.
6184
6185private:
6186 /// Parsing OpenACC directive mode.
6187 bool OpenACCDirectiveParsing = false;
6188
6189 /// Currently parsing a situation where an OpenACC array section could be
6190 /// legal, such as a 'var-list'.
6191 bool AllowOpenACCArraySections = false;
6192
6193 /// RAII object to set reset OpenACC parsing a context where Array Sections
6194 /// are allowed.
6195 class OpenACCArraySectionRAII {
6196 Parser &P;
6197
6198 public:
6199 OpenACCArraySectionRAII(Parser &P) : P(P) {
6200 assert(!P.AllowOpenACCArraySections);
6201 P.AllowOpenACCArraySections = true;
6202 }
6203 ~OpenACCArraySectionRAII() {
6204 assert(P.AllowOpenACCArraySections);
6205 P.AllowOpenACCArraySections = false;
6206 }
6207 };
6208
6209 /// A struct to hold the information that got parsed by ParseOpenACCDirective,
6210 /// so that the callers of it can use that to construct the appropriate AST
6211 /// nodes.
6212 struct OpenACCDirectiveParseInfo {
6213 OpenACCDirectiveKind DirKind;
6214 SourceLocation StartLoc;
6215 SourceLocation DirLoc;
6216 SourceLocation LParenLoc;
6217 SourceLocation RParenLoc;
6218 SourceLocation EndLoc;
6219 SourceLocation MiscLoc;
6220 OpenACCAtomicKind AtomicKind;
6221 SmallVector<Expr *> Exprs;
6222 SmallVector<OpenACCClause *> Clauses;
6223 // TODO OpenACC: As we implement support for the Atomic, Routine, and Cache
6224 // constructs, we likely want to put that information in here as well.
6225 };
6226
6227 struct OpenACCWaitParseInfo {
6228 bool Failed = false;
6229 Expr *DevNumExpr = nullptr;
6230 SourceLocation QueuesLoc;
6231 SmallVector<Expr *> QueueIdExprs;
6232
6233 SmallVector<Expr *> getAllExprs() {
6234 SmallVector<Expr *> Out;
6235 Out.push_back(DevNumExpr);
6236 llvm::append_range(Out, QueueIdExprs);
6237 return Out;
6238 }
6239 };
6240 struct OpenACCCacheParseInfo {
6241 bool Failed = false;
6242 SourceLocation ReadOnlyLoc;
6243 SmallVector<Expr *> Vars;
6244 };
6245
6246 /// Represents the 'error' state of parsing an OpenACC Clause, and stores
6247 /// whether we can continue parsing, or should give up on the directive.
6248 enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
6249
6250 /// A type to represent the state of parsing an OpenACC Clause. Situations
6251 /// that result in an OpenACCClause pointer are a success and can continue
6252 /// parsing, however some other situations can also continue.
6253 /// FIXME: This is better represented as a std::expected when we get C++23.
6254 using OpenACCClauseParseResult =
6255 llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
6256
6257 OpenACCClauseParseResult OpenACCCanContinue();
6258 OpenACCClauseParseResult OpenACCCannotContinue();
6259 OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
6260
6261 /// Parses the OpenACC directive (the entire pragma) including the clause
6262 /// list, but does not produce the main AST node.
6263 OpenACCDirectiveParseInfo ParseOpenACCDirective();
6264 /// Helper that parses an ID Expression based on the language options.
6265 ExprResult ParseOpenACCIDExpression();
6266
6267 /// Parses the variable list for the `cache` construct.
6268 ///
6269 /// OpenACC 3.3, section 2.10:
6270 /// In C and C++, the syntax of the cache directive is:
6271 ///
6272 /// #pragma acc cache ([readonly:]var-list) new-line
6273 OpenACCCacheParseInfo ParseOpenACCCacheVarList();
6274
6275 /// Tries to parse the 'modifier-list' for a 'copy', 'copyin', 'copyout', or
6276 /// 'create' clause.
6277 OpenACCModifierKind tryParseModifierList(OpenACCClauseKind CK);
6278
6279 using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
6280
6281 /// Parses a single variable in a variable list for OpenACC.
6282 ///
6283 /// OpenACC 3.3, section 1.6:
6284 /// In this spec, a 'var' (in italics) is one of the following:
6285 /// - a variable name (a scalar, array, or composite variable name)
6286 /// - a subarray specification with subscript ranges
6287 /// - an array element
6288 /// - a member of a composite variable
6289 /// - a common block name between slashes (fortran only)
6290 OpenACCVarParseResult ParseOpenACCVar(OpenACCDirectiveKind DK,
6292
6293 /// Parses the variable list for the variety of places that take a var-list.
6294 llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCDirectiveKind DK,
6296
6297 /// Parses any parameters for an OpenACC Clause, including required/optional
6298 /// parens.
6299 ///
6300 /// The OpenACC Clause List is a comma or space-delimited list of clauses (see
6301 /// the comment on ParseOpenACCClauseList). The concept of a 'clause' doesn't
6302 /// really have its owner grammar and each individual one has its own
6303 /// definition. However, they all are named with a single-identifier (or
6304 /// auto/default!) token, followed in some cases by either braces or parens.
6305 OpenACCClauseParseResult
6306 ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
6308 SourceLocation ClauseLoc);
6309
6310 /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
6311 /// error.
6312 OpenACCClauseParseResult
6313 ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
6314 OpenACCDirectiveKind DirKind);
6315
6316 /// Parses the clause-list for an OpenACC directive.
6317 ///
6318 /// OpenACC 3.3, section 1.7:
6319 /// To simplify the specification and convey appropriate constraint
6320 /// information, a pqr-list is a comma-separated list of pdr items. The one
6321 /// exception is a clause-list, which is a list of one or more clauses
6322 /// optionally separated by commas.
6323 SmallVector<OpenACCClause *>
6324 ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
6325
6326 /// OpenACC 3.3, section 2.16:
6327 /// In this section and throughout the specification, the term wait-argument
6328 /// means:
6329 /// \verbatim
6330 /// [ devnum : int-expr : ] [ queues : ] async-argument-list
6331 /// \endverbatim
6332 OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
6333 bool IsDirective);
6334
6335 /// Parses the clause of the 'bind' argument, which can be a string literal or
6336 /// an identifier.
6337 std::variant<std::monostate, StringLiteral *, IdentifierInfo *>
6338 ParseOpenACCBindClauseArgument();
6339
6340 /// A type to represent the state of parsing after an attempt to parse an
6341 /// OpenACC int-expr. This is useful to determine whether an int-expr list can
6342 /// continue parsing after a failed int-expr.
6343 using OpenACCIntExprParseResult =
6344 std::pair<ExprResult, OpenACCParseCanContinue>;
6345 /// Parses the clause kind of 'int-expr', which can be any integral
6346 /// expression.
6347 OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
6349 SourceLocation Loc);
6350 /// Parses the argument list for 'num_gangs', which allows up to 3
6351 /// 'int-expr's.
6352 bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
6353 SourceLocation Loc,
6354 llvm::SmallVectorImpl<Expr *> &IntExprs);
6355
6356 /// Parses the 'device-type-list', which is a list of identifiers.
6357 ///
6358 /// OpenACC 3.3 Section 2.4:
6359 /// The argument to the device_type clause is a comma-separated list of one or
6360 /// more device architecture name identifiers, or an asterisk.
6361 ///
6362 /// The syntax of the device_type clause is
6363 /// device_type( * )
6364 /// device_type( device-type-list )
6365 ///
6366 /// The device_type clause may be abbreviated to dtype.
6367 bool ParseOpenACCDeviceTypeList(llvm::SmallVector<IdentifierLoc> &Archs);
6368
6369 /// Parses the 'async-argument', which is an integral value with two
6370 /// 'special' values that are likely negative (but come from Macros).
6371 ///
6372 /// OpenACC 3.3 section 2.16:
6373 /// In this section and throughout the specification, the term async-argument
6374 /// means a nonnegative scalar integer expression (int for C or C++, integer
6375 /// for Fortran), or one of the special values acc_async_noval or
6376 /// acc_async_sync, as defined in the C header file and the Fortran openacc
6377 /// module. The special values are negative values, so as not to conflict with
6378 /// a user-specified nonnegative async-argument.
6379 OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
6381 SourceLocation Loc);
6382
6383 /// Parses the 'size-expr', which is an integral value, or an asterisk.
6384 /// Asterisk is represented by a OpenACCAsteriskSizeExpr
6385 ///
6386 /// OpenACC 3.3 Section 2.9:
6387 /// size-expr is one of:
6388 /// *
6389 /// int-expr
6390 /// Note that this is specified under 'gang-arg-list', but also applies to
6391 /// 'tile' via reference.
6392 ExprResult ParseOpenACCSizeExpr(OpenACCClauseKind CK);
6393
6394 /// Parses a comma delimited list of 'size-expr's.
6395 bool ParseOpenACCSizeExprList(OpenACCClauseKind CK,
6396 llvm::SmallVectorImpl<Expr *> &SizeExprs);
6397
6398 /// Parses a 'gang-arg-list', used for the 'gang' clause.
6399 ///
6400 /// OpenACC 3.3 Section 2.9:
6401 ///
6402 /// where gang-arg is one of:
6403 /// \verbatim
6404 /// [num:]int-expr
6405 /// dim:int-expr
6406 /// static:size-expr
6407 /// \endverbatim
6408 bool ParseOpenACCGangArgList(SourceLocation GangLoc,
6409 llvm::SmallVectorImpl<OpenACCGangKind> &GKs,
6410 llvm::SmallVectorImpl<Expr *> &IntExprs);
6411
6412 using OpenACCGangArgRes = std::pair<OpenACCGangKind, ExprResult>;
6413 /// Parses a 'gang-arg', used for the 'gang' clause. Returns a pair of the
6414 /// ExprResult (which contains the validity of the expression), plus the gang
6415 /// kind for the current argument.
6416 OpenACCGangArgRes ParseOpenACCGangArg(SourceLocation GangLoc);
6417 /// Parses a 'condition' expr, ensuring it results in a
6418 ExprResult ParseOpenACCConditionExpr();
6420 ParseOpenACCAfterRoutineDecl(AccessSpecifier &AS, ParsedAttributes &Attrs,
6421 DeclSpec::TST TagType, Decl *TagDecl,
6422 OpenACCDirectiveParseInfo &DirInfo);
6423 StmtResult ParseOpenACCAfterRoutineStmt(OpenACCDirectiveParseInfo &DirInfo);
6424
6425 ///@}
6426
6427 //
6428 //
6429 // -------------------------------------------------------------------------
6430 //
6431 //
6432
6433 /// \name OpenMP Constructs
6434 /// Implementations are in ParseOpenMP.cpp
6435 ///@{
6436
6437private:
6439
6440 /// Parsing OpenMP directive mode.
6441 bool OpenMPDirectiveParsing = false;
6442
6443 /// Current kind of OpenMP clause
6444 OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
6445
6446 void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
6447 // If parsing the attributes found an OpenMP directive, emit those tokens
6448 // to the parse stream now.
6449 if (!OpenMPTokens.empty()) {
6450 PP.EnterToken(Tok, /*IsReinject*/ true);
6451 PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
6452 /*IsReinject*/ true);
6453 ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
6454 }
6455 }
6456
6457 //===--------------------------------------------------------------------===//
6458 // OpenMP: Directives and clauses.
6459
6460 /// Parse clauses for '#pragma omp declare simd'.
6461 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
6462 CachedTokens &Toks,
6463 SourceLocation Loc);
6464
6465 /// Parse a property kind into \p TIProperty for the selector set \p Set and
6466 /// selector \p Selector.
6467 void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
6468 llvm::omp::TraitSet Set,
6469 llvm::omp::TraitSelector Selector,
6470 llvm::StringMap<SourceLocation> &Seen);
6471
6472 /// Parse a selector kind into \p TISelector for the selector set \p Set.
6473 void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
6474 llvm::omp::TraitSet Set,
6475 llvm::StringMap<SourceLocation> &Seen);
6476
6477 /// Parse a selector set kind into \p TISet.
6478 void parseOMPTraitSetKind(OMPTraitSet &TISet,
6479 llvm::StringMap<SourceLocation> &Seen);
6480
6481 /// Parses an OpenMP context property.
6482 void parseOMPContextProperty(OMPTraitSelector &TISelector,
6483 llvm::omp::TraitSet Set,
6484 llvm::StringMap<SourceLocation> &Seen);
6485
6486 /// Parses an OpenMP context selector.
6487 ///
6488 /// \verbatim
6489 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
6490 /// \endverbatim
6491 void parseOMPContextSelector(OMPTraitSelector &TISelector,
6492 llvm::omp::TraitSet Set,
6493 llvm::StringMap<SourceLocation> &SeenSelectors);
6494
6495 /// Parses an OpenMP context selector set.
6496 ///
6497 /// \verbatim
6498 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
6499 /// \endverbatim
6500 void parseOMPContextSelectorSet(OMPTraitSet &TISet,
6501 llvm::StringMap<SourceLocation> &SeenSets);
6502
6503 /// Parse OpenMP context selectors:
6504 ///
6505 /// \verbatim
6506 /// <trait-set-selector> [, <trait-set-selector>]*
6507 /// \endverbatim
6508 bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
6509
6510 /// Parse an 'append_args' clause for '#pragma omp declare variant'.
6511 bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
6512
6513 /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
6514 /// if there was an error.
6515 bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
6516 OMPTraitInfo *ParentTI);
6517
6518 /// Parse clauses for '#pragma omp declare variant ( variant-func-id )
6519 /// clause'.
6520 void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
6521 SourceLocation Loc);
6522
6523 /// Parse 'omp [begin] assume[s]' directive.
6524 ///
6525 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
6526 /// where
6527 ///
6528 /// \verbatim
6529 /// clause:
6530 /// 'ext_IMPL_DEFINED'
6531 /// 'absent' '(' directive-name [, directive-name]* ')'
6532 /// 'contains' '(' directive-name [, directive-name]* ')'
6533 /// 'holds' '(' scalar-expression ')'
6534 /// 'no_openmp'
6535 /// 'no_openmp_routines'
6536 /// 'no_openmp_constructs' (OpenMP 6.0)
6537 /// 'no_parallelism'
6538 /// \endverbatim
6539 ///
6540 void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
6541 SourceLocation Loc);
6542
6543 /// Parse 'omp end assumes' directive.
6544 void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
6545
6546 /// Parses clauses for directive.
6547 ///
6548 /// \verbatim
6549 /// <clause> [clause[ [,] clause] ... ]
6550 ///
6551 /// clauses: for error directive
6552 /// 'at' '(' compilation | execution ')'
6553 /// 'severity' '(' fatal | warning ')'
6554 /// 'message' '(' msg-string ')'
6555 /// ....
6556 /// \endverbatim
6557 ///
6558 /// \param DKind Kind of current directive.
6559 /// \param clauses for current directive.
6560 /// \param start location for clauses of current directive
6561 void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
6562 SmallVectorImpl<clang::OMPClause *> &Clauses,
6563 SourceLocation Loc);
6564
6565 /// Parse clauses for '#pragma omp [begin] declare target'.
6566 void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
6567
6568 /// Parse '#pragma omp end declare target'.
6569 void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
6570 OpenMPDirectiveKind EndDKind,
6571 SourceLocation Loc);
6572
6573 /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
6574 /// it is not the current token.
6575 void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
6576
6577 /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
6578 /// that the "end" matching the "begin" directive of kind \p BeginKind was not
6579 /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
6580 /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
6581 void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
6582 OpenMPDirectiveKind ExpectedKind,
6583 OpenMPDirectiveKind FoundKind,
6584 SourceLocation MatchingLoc, SourceLocation FoundLoc,
6585 bool SkipUntilOpenMPEnd);
6586
6587 /// Parses declarative OpenMP directives.
6588 ///
6589 /// \verbatim
6590 /// threadprivate-directive:
6591 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6592 /// annot_pragma_openmp_end
6593 ///
6594 /// allocate-directive:
6595 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
6596 /// annot_pragma_openmp_end
6597 ///
6598 /// declare-reduction-directive:
6599 /// annot_pragma_openmp 'declare' 'reduction' [...]
6600 /// annot_pragma_openmp_end
6601 ///
6602 /// declare-mapper-directive:
6603 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6604 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6605 /// annot_pragma_openmp_end
6606 ///
6607 /// declare-simd-directive:
6608 /// annot_pragma_openmp 'declare simd' {<clause> [,]}
6609 /// annot_pragma_openmp_end
6610 /// <function declaration/definition>
6611 ///
6612 /// requires directive:
6613 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
6614 /// annot_pragma_openmp_end
6615 ///
6616 /// assumes directive:
6617 /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
6618 /// annot_pragma_openmp_end
6619 /// or
6620 /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
6621 /// annot_pragma_openmp 'end assumes'
6622 /// annot_pragma_openmp_end
6623 /// \endverbatim
6624 ///
6625 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
6626 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
6628 Decl *TagDecl = nullptr);
6629
6630 /// Parse 'omp declare reduction' construct.
6631 ///
6632 /// \verbatim
6633 /// declare-reduction-directive:
6634 /// annot_pragma_openmp 'declare' 'reduction'
6635 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
6636 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
6637 /// annot_pragma_openmp_end
6638 /// \endverbatim
6639 /// <reduction_id> is either a base language identifier or one of the
6640 /// following operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
6641 ///
6642 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
6643
6644 /// Parses initializer for provided omp_priv declaration inside the reduction
6645 /// initializer.
6646 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
6647
6648 /// Parses 'omp declare mapper' directive.
6649 ///
6650 /// \verbatim
6651 /// declare-mapper-directive:
6652 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
6653 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6654 /// annot_pragma_openmp_end
6655 /// \endverbatim
6656 /// <mapper-identifier> and <var> are base language identifiers.
6657 ///
6658 DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
6659
6660 /// Parses variable declaration in 'omp declare mapper' directive.
6661 TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
6662 DeclarationName &Name,
6663 AccessSpecifier AS = AS_none);
6664
6665 /// Parses simple list of variables.
6666 ///
6667 /// \verbatim
6668 /// simple-variable-list:
6669 /// '(' id-expression {, id-expression} ')'
6670 /// \endverbatim
6671 ///
6672 /// \param Kind Kind of the directive.
6673 /// \param Callback Callback function to be called for the list elements.
6674 /// \param AllowScopeSpecifier true, if the variables can have fully
6675 /// qualified names.
6676 ///
6677 bool ParseOpenMPSimpleVarList(
6678 OpenMPDirectiveKind Kind,
6679 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
6680 &Callback,
6681 bool AllowScopeSpecifier);
6682
6683 /// Parses declarative or executable directive.
6684 ///
6685 /// \verbatim
6686 /// threadprivate-directive:
6687 /// annot_pragma_openmp 'threadprivate' simple-variable-list
6688 /// annot_pragma_openmp_end
6689 ///
6690 /// allocate-directive:
6691 /// annot_pragma_openmp 'allocate' simple-variable-list
6692 /// annot_pragma_openmp_end
6693 ///
6694 /// declare-reduction-directive:
6695 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
6696 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
6697 /// ('omp_priv' '=' <expression>|<function_call>) ')']
6698 /// annot_pragma_openmp_end
6699 ///
6700 /// declare-mapper-directive:
6701 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
6702 /// <type> <var> ')' [<clause>[[,] <clause>] ... ]
6703 /// annot_pragma_openmp_end
6704 ///
6705 /// executable-directive:
6706 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
6707 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
6708 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task'
6709 /// | 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' |
6710 /// 'error' | 'atomic' | 'for simd' | 'parallel for simd' | 'target' |
6711 /// 'target data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop
6712 /// simd' | 'master taskloop' | 'master taskloop simd' | 'parallel
6713 /// master taskloop' | 'parallel master taskloop simd' | 'distribute'
6714 /// | 'target enter data' | 'target exit data' | 'target parallel' |
6715 /// 'target parallel for' | 'target update' | 'distribute parallel
6716 /// for' | 'distribute paralle for simd' | 'distribute simd' | 'target
6717 /// parallel for simd' | 'target simd' | 'teams distribute' | 'teams
6718 /// distribute simd' | 'teams distribute parallel for simd' | 'teams
6719 /// distribute parallel for' | 'target teams' | 'target teams
6720 /// distribute' | 'target teams distribute parallel for' | 'target
6721 /// teams distribute parallel for simd' | 'target teams distribute
6722 /// simd' | 'masked' | 'parallel masked' {clause}
6723 /// annot_pragma_openmp_end
6724 /// \endverbatim
6725 ///
6726 ///
6727 /// \param StmtCtx The context in which we're parsing the directive.
6728 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6729 /// metadirective and therefore ends on the closing paren.
6730 StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
6731 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
6732
6733 /// Parses executable directive.
6734 ///
6735 /// \param StmtCtx The context in which we're parsing the directive.
6736 /// \param DKind The kind of the executable directive.
6737 /// \param Loc Source location of the beginning of the directive.
6738 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6739 /// metadirective and therefore ends on the closing paren.
6740 StmtResult
6741 ParseOpenMPExecutableDirective(ParsedStmtContext StmtCtx,
6742 OpenMPDirectiveKind DKind, SourceLocation Loc,
6743 bool ReadDirectiveWithinMetadirective);
6744
6745 /// Parses informational directive.
6746 ///
6747 /// \param StmtCtx The context in which we're parsing the directive.
6748 /// \param DKind The kind of the informational directive.
6749 /// \param Loc Source location of the beginning of the directive.
6750 /// \param ReadDirectiveWithinMetadirective true if directive is within a
6751 /// metadirective and therefore ends on the closing paren.
6752 StmtResult ParseOpenMPInformationalDirective(
6753 ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
6754 bool ReadDirectiveWithinMetadirective);
6755
6756 /// Parses clause of kind \a CKind for directive of a kind \a Kind.
6757 ///
6758 /// \verbatim
6759 /// clause:
6760 /// if-clause | final-clause | num_threads-clause | safelen-clause |
6761 /// default-clause | private-clause | firstprivate-clause |
6762 /// shared-clause | linear-clause | aligned-clause | collapse-clause |
6763 /// bind-clause | lastprivate-clause | reduction-clause |
6764 /// proc_bind-clause | schedule-clause | copyin-clause |
6765 /// copyprivate-clause | untied-clause | mergeable-clause | flush-clause
6766 /// | read-clause | write-clause | update-clause | capture-clause |
6767 /// seq_cst-clause | device-clause | simdlen-clause | threads-clause |
6768 /// simd-clause | num_teams-clause | thread_limit-clause |
6769 /// priority-clause | grainsize-clause | nogroup-clause |
6770 /// num_tasks-clause | hint-clause | to-clause | from-clause |
6771 /// is_device_ptr-clause | task_reduction-clause | in_reduction-clause |
6772 /// allocator-clause | allocate-clause | acq_rel-clause | acquire-clause
6773 /// | release-clause | relaxed-clause | depobj-clause | destroy-clause |
6774 /// detach-clause | inclusive-clause | exclusive-clause |
6775 /// uses_allocators-clause | use_device_addr-clause | has_device_addr
6776 /// \endverbatim
6777 ///
6778 /// \param DKind Kind of current directive.
6779 /// \param CKind Kind of current clause.
6780 /// \param FirstClause true, if this is the first clause of a kind \a CKind
6781 /// in current directive.
6782 ///
6783 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
6784 OpenMPClauseKind CKind, bool FirstClause);
6785
6786 /// Parses clause with a single expression of a kind \a Kind.
6787 ///
6788 /// Parsing of OpenMP clauses with single expressions like 'final',
6789 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
6790 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
6791 /// 'detach'.
6792 ///
6793 /// \verbatim
6794 /// final-clause:
6795 /// 'final' '(' expression ')'
6796 ///
6797 /// num_threads-clause:
6798 /// 'num_threads' '(' expression ')'
6799 ///
6800 /// safelen-clause:
6801 /// 'safelen' '(' expression ')'
6802 ///
6803 /// simdlen-clause:
6804 /// 'simdlen' '(' expression ')'
6805 ///
6806 /// collapse-clause:
6807 /// 'collapse' '(' expression ')'
6808 ///
6809 /// priority-clause:
6810 /// 'priority' '(' expression ')'
6811 ///
6812 /// grainsize-clause:
6813 /// 'grainsize' '(' expression ')'
6814 ///
6815 /// num_tasks-clause:
6816 /// 'num_tasks' '(' expression ')'
6817 ///
6818 /// hint-clause:
6819 /// 'hint' '(' expression ')'
6820 ///
6821 /// allocator-clause:
6822 /// 'allocator' '(' expression ')'
6823 ///
6824 /// detach-clause:
6825 /// 'detach' '(' event-handler-expression ')'
6826 ///
6827 /// align-clause
6828 /// 'align' '(' positive-integer-constant ')'
6829 ///
6830 /// holds-clause
6831 /// 'holds' '(' expression ')'
6832 /// \endverbatim
6833 ///
6834 /// \param Kind Kind of current clause.
6835 /// \param ParseOnly true to skip the clause's semantic actions and return
6836 /// nullptr.
6837 ///
6838 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly);
6839 /// Parses simple clause like 'default' or 'proc_bind' of a kind \a Kind.
6840 ///
6841 /// \verbatim
6842 /// default-clause:
6843 /// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
6844 ///
6845 /// proc_bind-clause:
6846 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')'
6847 ///
6848 /// bind-clause:
6849 /// 'bind' '(' 'teams' | 'parallel' | 'thread' ')'
6850 ///
6851 /// update-clause:
6852 /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
6853 /// 'inoutset' ')'
6854 /// \endverbatim
6855 ///
6856 /// \param Kind Kind of current clause.
6857 /// \param ParseOnly true to skip the clause's semantic actions and return
6858 /// nullptr.
6859 ///
6860 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
6861
6862 /// Parse indirect clause for '#pragma omp declare target' directive.
6863 /// 'indirect' '[' '(' invoked-by-fptr ')' ']'
6864 /// where invoked-by-fptr is a constant boolean expression that evaluates to
6865 /// true or false at compile time.
6866 /// \param ParseOnly true to skip the clause's semantic actions and return
6867 /// false;
6868 bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
6869 bool ParseOnly);
6870 /// Parses clause with a single expression and an additional argument
6871 /// of a kind \a Kind like 'schedule' or 'dist_schedule'.
6872 ///
6873 /// \verbatim
6874 /// schedule-clause:
6875 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
6876 /// ')'
6877 ///
6878 /// if-clause:
6879 /// 'if' '(' [ directive-name-modifier ':' ] expression ')'
6880 ///
6881 /// defaultmap:
6882 /// 'defaultmap' '(' modifier [ ':' kind ] ')'
6883 ///
6884 /// device-clause:
6885 /// 'device' '(' [ device-modifier ':' ] expression ')'
6886 /// \endverbatim
6887 ///
6888 /// \param DKind Directive kind.
6889 /// \param Kind Kind of current clause.
6890 /// \param ParseOnly true to skip the clause's semantic actions and return
6891 /// nullptr.
6892 ///
6893 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
6894 OpenMPClauseKind Kind,
6895 bool ParseOnly);
6896
6897 /// Parses the 'looprange' clause of a '#pragma omp fuse' directive.
6898 OMPClause *ParseOpenMPLoopRangeClause();
6899
6900 /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
6901 OMPClause *ParseOpenMPSizesClause();
6902
6903 /// Parses the 'counts' clause of a '#pragma omp split' directive.
6904 OMPClause *ParseOpenMPCountsClause();
6905
6906 /// Parses the 'permutation' clause of a '#pragma omp interchange' directive.
6907 OMPClause *ParseOpenMPPermutationClause();
6908
6909 /// Parses clause without any additional arguments like 'ordered'.
6910 ///
6911 /// \verbatim
6912 /// ordered-clause:
6913 /// 'ordered'
6914 ///
6915 /// nowait-clause:
6916 /// 'nowait'
6917 ///
6918 /// untied-clause:
6919 /// 'untied'
6920 ///
6921 /// mergeable-clause:
6922 /// 'mergeable'
6923 ///
6924 /// read-clause:
6925 /// 'read'
6926 ///
6927 /// threads-clause:
6928 /// 'threads'
6929 ///
6930 /// simd-clause:
6931 /// 'simd'
6932 ///
6933 /// nogroup-clause:
6934 /// 'nogroup'
6935 /// \endverbatim
6936 ///
6937 /// \param Kind Kind of current clause.
6938 /// \param ParseOnly true to skip the clause's semantic actions and return
6939 /// nullptr.
6940 ///
6941 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
6942
6943 /// Parses clause with the list of variables of a kind \a Kind:
6944 /// 'private', 'firstprivate', 'lastprivate',
6945 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
6946 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
6947 ///
6948 /// \verbatim
6949 /// private-clause:
6950 /// 'private' '(' list ')'
6951 /// firstprivate-clause:
6952 /// 'firstprivate' '(' list ')'
6953 /// lastprivate-clause:
6954 /// 'lastprivate' '(' list ')'
6955 /// shared-clause:
6956 /// 'shared' '(' list ')'
6957 /// linear-clause:
6958 /// 'linear' '(' linear-list [ ':' linear-step ] ')'
6959 /// aligned-clause:
6960 /// 'aligned' '(' list [ ':' alignment ] ')'
6961 /// reduction-clause:
6962 /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
6963 /// task_reduction-clause:
6964 /// 'task_reduction' '(' reduction-identifier ':' list ')'
6965 /// in_reduction-clause:
6966 /// 'in_reduction' '(' reduction-identifier ':' list ')'
6967 /// copyprivate-clause:
6968 /// 'copyprivate' '(' list ')'
6969 /// flush-clause:
6970 /// 'flush' '(' list ')'
6971 /// depend-clause:
6972 /// 'depend' '(' in | out | inout : list | source ')'
6973 /// map-clause:
6974 /// 'map' '(' [ [ always [,] ] [ close [,] ]
6975 /// [ mapper '(' mapper-identifier ')' [,] ]
6976 /// to | from | tofrom | alloc | release | delete ':' ] list ')';
6977 /// to-clause:
6978 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6979 /// from-clause:
6980 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
6981 /// use_device_ptr-clause:
6982 /// 'use_device_ptr' '(' list ')'
6983 /// use_device_addr-clause:
6984 /// 'use_device_addr' '(' list ')'
6985 /// is_device_ptr-clause:
6986 /// 'is_device_ptr' '(' list ')'
6987 /// has_device_addr-clause:
6988 /// 'has_device_addr' '(' list ')'
6989 /// allocate-clause:
6990 /// 'allocate' '(' [ allocator ':' ] list ')'
6991 /// As of OpenMP 5.1 there's also
6992 /// 'allocate' '(' allocate-modifier: list ')'
6993 /// where allocate-modifier is: 'allocator' '(' allocator ')'
6994 /// nontemporal-clause:
6995 /// 'nontemporal' '(' list ')'
6996 /// inclusive-clause:
6997 /// 'inclusive' '(' list ')'
6998 /// exclusive-clause:
6999 /// 'exclusive' '(' list ')'
7000 /// \endverbatim
7001 ///
7002 /// For 'linear' clause linear-list may have the following forms:
7003 /// list
7004 /// modifier(list)
7005 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
7006 ///
7007 /// \param Kind Kind of current clause.
7008 /// \param ParseOnly true to skip the clause's semantic actions and return
7009 /// nullptr.
7010 ///
7011 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
7012 OpenMPClauseKind Kind, bool ParseOnly);
7013
7014 /// Parses a clause consisting of a list of expressions.
7015 ///
7016 /// \param Kind The clause to parse.
7017 /// \param ClauseNameLoc [out] The location of the clause name.
7018 /// \param OpenLoc [out] The location of '('.
7019 /// \param CloseLoc [out] The location of ')'.
7020 /// \param Exprs [out] The parsed expressions.
7021 /// \param ReqIntConst If true, each expression must be an integer constant.
7022 ///
7023 /// \return Whether the clause was parsed successfully.
7024 bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
7025 SourceLocation &ClauseNameLoc,
7026 SourceLocation &OpenLoc,
7027 SourceLocation &CloseLoc,
7028 SmallVectorImpl<Expr *> &Exprs,
7029 bool ReqIntConst = false);
7030
7031 /// Parses simple expression in parens for single-expression clauses of OpenMP
7032 /// constructs.
7033 /// \verbatim
7034 /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
7035 /// <range-specification> }+ ')'
7036 /// \endverbatim
7037 ExprResult ParseOpenMPIteratorsExpr();
7038
7039 /// Parses allocators and traits in the context of the uses_allocator clause.
7040 /// Expected format:
7041 /// \verbatim
7042 /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
7043 /// \endverbatim
7044 OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
7045
7046 /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
7047 bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
7048
7049 /// Parses 'fr(<foreign-runtime-id>)'.
7050 ExprResult ParseOMPInteropFrSelector();
7051
7052 /// Parses 'attr(<string-literal>[, ...])', appending to \p Attrs.
7053 bool ParseOMPInteropAttrSelector(SmallVectorImpl<Expr *> &Attrs);
7054
7055 /// Parses clause with an interop variable of kind \a Kind.
7056 ///
7057 /// \verbatim
7058 /// init-clause:
7059 /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
7060 ///
7061 /// destroy-clause:
7062 /// destroy(interop-var)
7063 ///
7064 /// use-clause:
7065 /// use(interop-var)
7066 ///
7067 /// interop-modifier:
7068 /// prefer_type(preference-list)
7069 ///
7070 /// preference-list:
7071 /// foreign-runtime-id [, foreign-runtime-id]...
7072 ///
7073 /// foreign-runtime-id:
7074 /// <string-literal> | <constant-integral-expression>
7075 ///
7076 /// interop-type:
7077 /// target | targetsync
7078 /// \endverbatim
7079 ///
7080 /// \param Kind Kind of current clause.
7081 /// \param ParseOnly true to skip the clause's semantic actions and return
7082 /// nullptr.
7083 //
7084 OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
7085
7086 /// Parses a ompx_attribute clause
7087 ///
7088 /// \param ParseOnly true to skip the clause's semantic actions and return
7089 /// nullptr.
7090 //
7091 OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
7092
7093public:
7094 /// Parses simple expression in parens for single-expression clauses of OpenMP
7095 /// constructs.
7096 /// \param RLoc Returned location of right paren.
7097 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
7098 bool IsAddressOfOperand = false);
7099
7100 /// Parses a reserved locator like 'omp_all_memory'.
7102 SemaOpenMP::OpenMPVarListDataTy &Data,
7103 const LangOptions &LangOpts);
7104
7105 /// Parses one bound of an OpenMP 6.0 'adjust_args' parameter range, which may
7106 /// be 'omp_num_args' with an optional logical offset, or the whole
7107 /// parameter-list item when no range colon follows it.
7108 bool ParseOpenMPAdjustArgsBound(OMPAdjustArgsItem::Bound &Bound);
7109
7110 /// Parses an OpenMP 6.0 'adjust_args' parameter list, whose items may be
7111 /// parameter names, positions, or ranges with optional bounds.
7112 /// Returns true on error.
7113 bool ParseOpenMPAdjustArgsList(SmallVectorImpl<OMPAdjustArgsItem> &Items);
7114
7115 /// Parses clauses with list.
7116 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
7117 SmallVectorImpl<Expr *> &Vars,
7118 SemaOpenMP::OpenMPVarListDataTy &Data,
7119 SmallVectorImpl<OMPAdjustArgsItem> &AdjustArgsItems);
7120
7121 /// Parses the mapper modifier in map, to, and from clauses.
7122 bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
7123
7124 /// Parse map-type-modifiers in map clause.
7125 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list)
7126 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
7127 /// present
7128 /// where, map-type ::= alloc | delete | from | release | to | tofrom
7129 bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
7130
7131 /// Parses 'omp begin declare variant' directive.
7132 /// The syntax is:
7133 /// \verbatim
7134 /// { #pragma omp begin declare variant clause }
7135 /// <function-declaration-or-definition-sequence>
7136 /// { #pragma omp end declare variant }
7137 /// \endverbatim
7138 ///
7139 bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc);
7140
7141 ///@}
7142
7143 //
7144 //
7145 // -------------------------------------------------------------------------
7146 //
7147 //
7148
7149 /// \name Pragmas
7150 /// Implementations are in ParsePragma.cpp
7151 ///@{
7152
7153private:
7154 std::unique_ptr<PragmaHandler> AlignHandler;
7155 std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
7156 std::unique_ptr<PragmaHandler> OptionsHandler;
7157 std::unique_ptr<PragmaHandler> PackHandler;
7158 std::unique_ptr<PragmaHandler> MSStructHandler;
7159 std::unique_ptr<PragmaHandler> UnusedHandler;
7160 std::unique_ptr<PragmaHandler> WeakHandler;
7161 std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
7162 std::unique_ptr<PragmaHandler> FPContractHandler;
7163 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
7164 std::unique_ptr<PragmaHandler> OpenMPHandler;
7165 std::unique_ptr<PragmaHandler> OpenACCHandler;
7166 std::unique_ptr<PragmaHandler> PCSectionHandler;
7167 std::unique_ptr<PragmaHandler> MSCommentHandler;
7168 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
7169 std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
7170 std::unique_ptr<PragmaHandler> FloatControlHandler;
7171 std::unique_ptr<PragmaHandler> MSPointersToMembers;
7172 std::unique_ptr<PragmaHandler> MSVtorDisp;
7173 std::unique_ptr<PragmaHandler> MSInitSeg;
7174 std::unique_ptr<PragmaHandler> MSDataSeg;
7175 std::unique_ptr<PragmaHandler> MSBSSSeg;
7176 std::unique_ptr<PragmaHandler> MSConstSeg;
7177 std::unique_ptr<PragmaHandler> MSCodeSeg;
7178 std::unique_ptr<PragmaHandler> MSSection;
7179 std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
7180 std::unique_ptr<PragmaHandler> MSRuntimeChecks;
7181 std::unique_ptr<PragmaHandler> MSIntrinsic;
7182 std::unique_ptr<PragmaHandler> MSFunction;
7183 std::unique_ptr<PragmaHandler> MSOptimize;
7184 std::unique_ptr<PragmaHandler> MSFenvAccess;
7185 std::unique_ptr<PragmaHandler> MSAllocText;
7186 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
7187 std::unique_ptr<PragmaHandler> OptimizeHandler;
7188 std::unique_ptr<PragmaHandler> LoopHintHandler;
7189 std::unique_ptr<PragmaHandler> UnrollHintHandler;
7190 std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
7191 std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
7192 std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
7193 std::unique_ptr<PragmaHandler> FPHandler;
7194 std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
7195 std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
7196 std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
7197 std::unique_ptr<PragmaHandler> STDCUnknownHandler;
7198 std::unique_ptr<PragmaHandler> AttributePragmaHandler;
7199 std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
7200 std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
7201 std::unique_ptr<PragmaHandler> ExportHandler;
7202 std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
7203
7204 /// Initialize all pragma handlers.
7205 void initializePragmaHandlers();
7206
7207 /// Destroy and reset all pragma handlers.
7208 void resetPragmaHandlers();
7209
7210 /// Handle the annotation token produced for #pragma unused(...)
7211 ///
7212 /// Each annot_pragma_unused is followed by the argument token so e.g.
7213 /// "#pragma unused(x,y)" becomes:
7214 /// annot_pragma_unused 'x' annot_pragma_unused 'y'
7215 void HandlePragmaUnused();
7216
7217 /// Handle the annotation token produced for
7218 /// #pragma GCC visibility...
7219 void HandlePragmaVisibility();
7220
7221 /// Handle the annotation token produced for
7222 /// #pragma pack...
7223 void HandlePragmaPack();
7224
7225 /// Handle the annotation token produced for
7226 /// #pragma ms_struct...
7227 void HandlePragmaMSStruct();
7228
7229 void HandlePragmaMSPointersToMembers();
7230
7231 void HandlePragmaMSVtorDisp();
7232
7233 void HandlePragmaMSPragma();
7234 bool HandlePragmaMSSection(StringRef PragmaName,
7235 SourceLocation PragmaLocation);
7236 bool HandlePragmaMSSegment(StringRef PragmaName,
7237 SourceLocation PragmaLocation);
7238
7239 // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
7240 bool HandlePragmaMSInitSeg(StringRef PragmaName,
7241 SourceLocation PragmaLocation);
7242
7243 // #pragma strict_gs_check(pop)
7244 // #pragma strict_gs_check(push, "on" | "off")
7245 // #pragma strict_gs_check("on" | "off")
7246 bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
7247 SourceLocation PragmaLocation);
7248 bool HandlePragmaMSFunction(StringRef PragmaName,
7249 SourceLocation PragmaLocation);
7250 bool HandlePragmaMSAllocText(StringRef PragmaName,
7251 SourceLocation PragmaLocation);
7252
7253 // #pragma optimize("gsty", on|off)
7254 bool HandlePragmaMSOptimize(StringRef PragmaName,
7255 SourceLocation PragmaLocation);
7256
7257 // #pragma intrinsic("foo")
7258 bool HandlePragmaMSIntrinsic(StringRef PragmaName,
7259 SourceLocation PragmaLocation);
7260
7261 /// Handle the annotation token produced for
7262 /// #pragma align...
7263 void HandlePragmaAlign();
7264
7265 /// Handle the annotation token produced for
7266 /// #pragma clang __debug dump...
7267 void HandlePragmaDump();
7268
7269 /// Handle the annotation token produced for
7270 /// #pragma weak id...
7271 void HandlePragmaWeak();
7272
7273 /// Handle the annotation token produced for
7274 /// #pragma weak id = id...
7275 void HandlePragmaWeakAlias();
7276
7277 /// Handle the annotation token produced for
7278 /// #pragma redefine_extname...
7279 void HandlePragmaRedefineExtname();
7280
7281 /// Handle the annotation token produced for
7282 /// #pragma STDC FP_CONTRACT...
7283 void HandlePragmaFPContract();
7284
7285 /// Handle the annotation token produced for
7286 /// #pragma STDC FENV_ACCESS...
7287 void HandlePragmaFEnvAccess();
7288
7289 /// Handle the annotation token produced for
7290 /// #pragma STDC FENV_ROUND...
7291 void HandlePragmaFEnvRound();
7292
7293 /// Handle the annotation token produced for
7294 /// #pragma STDC CX_LIMITED_RANGE...
7295 void HandlePragmaCXLimitedRange();
7296
7297 /// Handle the annotation token produced for
7298 /// #pragma float_control
7299 void HandlePragmaFloatControl();
7300
7301 /// \brief Handle the annotation token produced for
7302 /// #pragma clang fp ...
7303 void HandlePragmaFP();
7304
7305 /// Handle the annotation token produced for
7306 /// #pragma OPENCL EXTENSION...
7307 void HandlePragmaOpenCLExtension();
7308
7309 /// Handle the annotation token produced for
7310 /// #pragma clang __debug captured
7311 StmtResult HandlePragmaCaptured();
7312
7313 /// Handle the annotation token produced for
7314 /// #pragma clang loop and #pragma unroll.
7315 bool HandlePragmaLoopHint(LoopHint &Hint);
7316
7317 bool ParsePragmaAttributeSubjectMatchRuleSet(
7318 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
7319 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
7320
7321 void HandlePragmaAttribute();
7322
7323 void zOSHandlePragmaHelper(tok::TokenKind);
7324
7325 /// Handle the annotation token produced for
7326 /// #pragma export ...
7327 void HandlePragmaExport();
7328
7329 ///@}
7330
7331 //
7332 //
7333 // -------------------------------------------------------------------------
7334 //
7335 //
7336
7337 /// \name Statements
7338 /// Implementations are in ParseStmt.cpp
7339 ///@{
7340
7341public:
7342 /// A SmallVector of statements.
7344
7345 /// The location of the first statement inside an else that might
7346 /// have a missleading indentation. If there is no
7347 /// MisleadingIndentationChecker on an else active, this location is invalid.
7349
7350 private:
7351
7352 /// Flags describing a context in which we're parsing a statement.
7353 enum class ParsedStmtContext {
7354 /// This context permits declarations in language modes where declarations
7355 /// are not statements.
7356 AllowDeclarationsInC = 0x1,
7357 /// This context permits standalone OpenMP directives.
7358 AllowStandaloneOpenMPDirectives = 0x2,
7359 /// This context is at the top level of a GNU statement expression.
7360 InStmtExpr = 0x4,
7361
7362 /// The context of a regular substatement.
7363 SubStmt = 0,
7364 /// The context of a compound-statement.
7365 Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
7366
7367 LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
7368 };
7369
7370 /// Act on an expression statement that might be the last statement in a
7371 /// GNU statement expression. Checks whether we are actually at the end of
7372 /// a statement expression and builds a suitable expression statement.
7373 StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
7374
7375 //===--------------------------------------------------------------------===//
7376 // C99 6.8: Statements and Blocks.
7377
7378 /// Parse a standalone statement (for instance, as the body of an 'if',
7379 /// 'while', or 'for').
7381 ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
7382 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt,
7383 LabelDecl *PrecedingLabel = nullptr);
7384
7385 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
7386 /// \verbatim
7387 /// StatementOrDeclaration:
7388 /// statement
7389 /// declaration
7390 ///
7391 /// statement:
7392 /// labeled-statement
7393 /// compound-statement
7394 /// expression-statement
7395 /// selection-statement
7396 /// iteration-statement
7397 /// jump-statement
7398 /// [C++] declaration-statement
7399 /// [C++] try-block
7400 /// [MS] seh-try-block
7401 /// [OBC] objc-throw-statement
7402 /// [OBC] objc-try-catch-statement
7403 /// [OBC] objc-synchronized-statement
7404 /// [GNU] asm-statement
7405 /// [OMP] openmp-construct [TODO]
7406 ///
7407 /// labeled-statement:
7408 /// identifier ':' statement
7409 /// 'case' constant-expression ':' statement
7410 /// 'default' ':' statement
7411 ///
7412 /// selection-statement:
7413 /// if-statement
7414 /// switch-statement
7415 ///
7416 /// iteration-statement:
7417 /// while-statement
7418 /// do-statement
7419 /// for-statement
7420 ///
7421 /// expression-statement:
7422 /// expression[opt] ';'
7423 ///
7424 /// jump-statement:
7425 /// 'goto' identifier ';'
7426 /// 'continue' ';'
7427 /// 'break' ';'
7428 /// 'return' expression[opt] ';'
7429 /// [GNU] 'goto' '*' expression ';'
7430 ///
7431 /// [OBC] objc-throw-statement:
7432 /// [OBC] '@' 'throw' expression ';'
7433 /// [OBC] '@' 'throw' ';'
7434 /// \endverbatim
7435 ///
7437 ParseStatementOrDeclaration(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7438 SourceLocation *TrailingElseLoc = nullptr,
7439 LabelDecl *PrecedingLabel = nullptr);
7440
7441 StmtResult ParseStatementOrDeclarationAfterAttributes(
7442 StmtVector &Stmts, ParsedStmtContext StmtCtx,
7443 SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
7444 ParsedAttributes &DeclSpecAttrs, LabelDecl *PrecedingLabel);
7445
7446 /// Parse an expression statement.
7447 StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
7448
7449 /// ParseLabeledStatement - We have an identifier and a ':' after it.
7450 ///
7451 /// \verbatim
7452 /// label:
7453 /// identifier ':'
7454 /// [GNU] identifier ':' attributes[opt]
7455 ///
7456 /// labeled-statement:
7457 /// label statement
7458 /// \endverbatim
7459 ///
7460 StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
7461 ParsedStmtContext StmtCtx);
7462
7463 /// ParseCaseStatement
7464 /// \verbatim
7465 /// labeled-statement:
7466 /// 'case' constant-expression ':' statement
7467 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement
7468 /// \endverbatim
7469 ///
7470 StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
7471 bool MissingCase = false,
7473
7474 /// ParseDefaultStatement
7475 /// \verbatim
7476 /// labeled-statement:
7477 /// 'default' ':' statement
7478 /// \endverbatim
7479 /// Note that this does not parse the 'statement' at the end.
7480 ///
7481 StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
7482
7483 StmtResult ParseCompoundStatement(bool isStmtExpr = false);
7484
7485 /// ParseCompoundStatement - Parse a "{}" block.
7486 ///
7487 /// \verbatim
7488 /// compound-statement: [C99 6.8.2]
7489 /// { block-item-list[opt] }
7490 /// [GNU] { label-declarations block-item-list } [TODO]
7491 ///
7492 /// block-item-list:
7493 /// block-item
7494 /// block-item-list block-item
7495 ///
7496 /// block-item:
7497 /// declaration
7498 /// [GNU] '__extension__' declaration
7499 /// statement
7500 ///
7501 /// [GNU] label-declarations:
7502 /// [GNU] label-declaration
7503 /// [GNU] label-declarations label-declaration
7504 ///
7505 /// [GNU] label-declaration:
7506 /// [GNU] '__label__' identifier-list ';'
7507 /// \endverbatim
7508 ///
7509 StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags);
7510
7511 /// Parse any pragmas at the start of the compound expression. We handle these
7512 /// separately since some pragmas (FP_CONTRACT) must appear before any C
7513 /// statement in the compound, but may be intermingled with other pragmas.
7514 void ParseCompoundStatementLeadingPragmas();
7515
7516 void DiagnoseLabelAtEndOfCompoundStatement();
7517
7518 /// Consume any extra semi-colons resulting in null statements,
7519 /// returning true if any tok::semi were consumed.
7520 bool ConsumeNullStmt(StmtVector &Stmts);
7521
7522 /// ParseCompoundStatementBody - Parse a sequence of statements optionally
7523 /// followed by a label and invoke the ActOnCompoundStmt action. This expects
7524 /// the '{' to be the current token, and consume the '}' at the end of the
7525 /// block. It does not manipulate the scope stack.
7526 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
7527
7528 /// ParseParenExprOrCondition:
7529 /// \verbatim
7530 /// [C ] '(' expression ')'
7531 /// [C++] '(' condition ')'
7532 /// [C++1z] '(' init-statement[opt] condition ')'
7533 /// \endverbatim
7534 ///
7535 /// This function parses and performs error recovery on the specified
7536 /// condition or expression (depending on whether we're in C++ or C mode).
7537 /// This function goes out of its way to recover well. It returns true if
7538 /// there was a parser error (the right paren couldn't be found), which
7539 /// indicates that the caller should try to recover harder. It returns false
7540 /// if the condition is successfully parsed. Note that a successful parse can
7541 /// still have semantic errors in the condition. Additionally, it will assign
7542 /// the location of the outer-most '(' and ')', to LParenLoc and RParenLoc,
7543 /// respectively.
7544 bool ParseParenExprOrCondition(StmtResult *InitStmt,
7545 Sema::ConditionResult &CondResult,
7547 SourceLocation &LParenLoc,
7548 SourceLocation &RParenLoc);
7549
7550 /// ParseIfStatement
7551 /// \verbatim
7552 /// if-statement: [C99 6.8.4.1]
7553 /// 'if' '(' expression ')' statement
7554 /// 'if' '(' expression ')' statement 'else' statement
7555 /// [C++] 'if' '(' condition ')' statement
7556 /// [C++] 'if' '(' condition ')' statement 'else' statement
7557 /// [C++23] 'if' '!' [opt] consteval compound-statement
7558 /// [C++23] 'if' '!' [opt] consteval compound-statement 'else' statement
7559 /// \endverbatim
7560 ///
7561 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
7562
7563 /// ParseSwitchStatement
7564 /// \verbatim
7565 /// switch-statement:
7566 /// 'switch' '(' expression ')' statement
7567 /// [C++] 'switch' '(' condition ')' statement
7568 /// \endverbatim
7569 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc,
7570 LabelDecl *PrecedingLabel);
7571
7572 /// ParseWhileStatement
7573 /// \verbatim
7574 /// while-statement: [C99 6.8.5.1]
7575 /// 'while' '(' expression ')' statement
7576 /// [C++] 'while' '(' condition ')' statement
7577 /// \endverbatim
7578 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc,
7579 LabelDecl *PrecedingLabel);
7580
7581 /// ParseDoStatement
7582 /// \verbatim
7583 /// do-statement: [C99 6.8.5.2]
7584 /// 'do' statement 'while' '(' expression ')' ';'
7585 /// \endverbatim
7586 /// Note: this lets the caller parse the end ';'.
7587 StmtResult ParseDoStatement(LabelDecl *PrecedingLabel);
7588
7589 /// ParseForStatement
7590 /// \verbatim
7591 /// for-statement: [C99 6.8.5.3]
7592 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
7593 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
7594 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
7595 /// [C++] statement
7596 /// [C++0x] 'for'
7597 /// 'co_await'[opt] [Coroutines]
7598 /// '(' for-range-declaration ':' for-range-initializer ')'
7599 /// statement
7600 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
7601 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
7602 ///
7603 /// [C++] for-init-statement:
7604 /// [C++] expression-statement
7605 /// [C++] simple-declaration
7606 /// [C++23] alias-declaration
7607 ///
7608 /// [C++0x] for-range-declaration:
7609 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
7610 /// [C++0x] for-range-initializer:
7611 /// [C++0x] expression
7612 /// [C++0x] braced-init-list [TODO]
7613 /// \endverbatim
7614 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc,
7615 LabelDecl *PrecedingLabel,
7616 CXXExpansionStmtDecl *ESD = nullptr);
7617
7618 void ParseForRangeInitializerAfterColon(ForRangeInit &FRI,
7619 ParsingDeclSpec *VarDeclSpec);
7620
7621 /// ParseGotoStatement
7622 /// \verbatim
7623 /// jump-statement:
7624 /// 'goto' identifier ';'
7625 /// [GNU] 'goto' '*' expression ';'
7626 /// \endverbatim
7627 ///
7628 /// Note: this lets the caller parse the end ';'.
7629 ///
7630 StmtResult ParseGotoStatement();
7631
7632 /// ParseContinueStatement
7633 /// \verbatim
7634 /// jump-statement:
7635 /// 'continue' ';'
7636 /// [C2y] 'continue' identifier ';'
7637 /// \endverbatim
7638 ///
7639 /// Note: this lets the caller parse the end ';'.
7640 ///
7641 StmtResult ParseContinueStatement();
7642
7643 /// ParseBreakStatement
7644 /// \verbatim
7645 /// jump-statement:
7646 /// 'break' ';'
7647 /// [C2y] 'break' identifier ';'
7648 /// \endverbatim
7649 ///
7650 /// Note: this lets the caller parse the end ';'.
7651 ///
7652 StmtResult ParseBreakStatement();
7653
7654 /// ParseReturnStatement
7655 /// \verbatim
7656 /// jump-statement:
7657 /// 'return' expression[opt] ';'
7658 /// 'return' braced-init-list ';'
7659 /// 'co_return' expression[opt] ';'
7660 /// 'co_return' braced-init-list ';'
7661 /// \endverbatim
7662 StmtResult ParseReturnStatement();
7663
7664 StmtResult ParseBreakOrContinueStatement(bool IsContinue);
7665
7666 /// ParseDeferStatement
7667 /// \verbatim
7668 /// defer-statement:
7669 /// '_Defer' deferred-block
7670 ///
7671 /// deferred-block:
7672 /// unlabeled-statement
7673 /// \endverbatim
7674 StmtResult ParseDeferStatement(SourceLocation *TrailingElseLoc);
7675
7676 /// ParseExpansionStatement - Parse a C++26 expansion
7677 /// statement ('template for').
7678 ///
7679 /// \verbatim
7680 /// expansion-statement:
7681 /// 'template' 'for' '(' init-statement[opt]
7682 /// for-range-declaration ':' expansion-initializer ')'
7683 /// compound-statement
7684 ///
7685 /// expansion-initializer:
7686 /// expression
7687 /// expansion-init-list
7688 /// \endverbatim
7689 StmtResult ParseExpansionStatement(SourceLocation *TrailingElseLoc,
7690 LabelDecl *PrecedingLabel,
7691 SourceLocation TemplateLoc);
7692
7693 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
7694 SourceLocation *TrailingElseLoc,
7695 ParsedAttributes &Attrs,
7696 LabelDecl *PrecedingLabel);
7697
7698 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
7699
7700 //===--------------------------------------------------------------------===//
7701 // C++ 6: Statements and Blocks
7702
7703 /// ParseCXXTryBlock - Parse a C++ try-block.
7704 ///
7705 /// \verbatim
7706 /// try-block:
7707 /// 'try' compound-statement handler-seq
7708 /// \endverbatim
7709 ///
7710 StmtResult ParseCXXTryBlock();
7711
7712 /// ParseCXXTryBlockCommon - Parse the common part of try-block and
7713 /// function-try-block.
7714 ///
7715 /// \verbatim
7716 /// try-block:
7717 /// 'try' compound-statement handler-seq
7718 ///
7719 /// function-try-block:
7720 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7721 ///
7722 /// handler-seq:
7723 /// handler handler-seq[opt]
7724 ///
7725 /// [Borland] try-block:
7726 /// 'try' compound-statement seh-except-block
7727 /// 'try' compound-statement seh-finally-block
7728 /// \endverbatim
7729 ///
7730 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
7731
7732 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the
7733 /// standard
7734 ///
7735 /// \verbatim
7736 /// handler:
7737 /// 'catch' '(' exception-declaration ')' compound-statement
7738 ///
7739 /// exception-declaration:
7740 /// attribute-specifier-seq[opt] type-specifier-seq declarator
7741 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
7742 /// '...'
7743 /// \endverbatim
7744 ///
7745 StmtResult ParseCXXCatchBlock(bool FnCatch = false);
7746
7747 //===--------------------------------------------------------------------===//
7748 // MS: SEH Statements and Blocks
7749
7750 /// ParseSEHTryBlockCommon
7751 ///
7752 /// \verbatim
7753 /// seh-try-block:
7754 /// '__try' compound-statement seh-handler
7755 ///
7756 /// seh-handler:
7757 /// seh-except-block
7758 /// seh-finally-block
7759 /// \endverbatim
7760 ///
7761 StmtResult ParseSEHTryBlock();
7762
7763 /// ParseSEHExceptBlock - Handle __except
7764 ///
7765 /// \verbatim
7766 /// seh-except-block:
7767 /// '__except' '(' seh-filter-expression ')' compound-statement
7768 /// \endverbatim
7769 ///
7770 StmtResult ParseSEHExceptBlock(SourceLocation Loc);
7771
7772 /// ParseSEHFinallyBlock - Handle __finally
7773 ///
7774 /// \verbatim
7775 /// seh-finally-block:
7776 /// '__finally' compound-statement
7777 /// \endverbatim
7778 ///
7779 StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
7780
7781 StmtResult ParseSEHLeaveStatement();
7782
7783 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
7784
7785 /// ParseFunctionTryBlock - Parse a C++ function-try-block.
7786 ///
7787 /// \verbatim
7788 /// function-try-block:
7789 /// 'try' ctor-initializer[opt] compound-statement handler-seq
7790 /// \endverbatim
7791 ///
7792 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
7793
7794 /// ParseFunctionBody - Parse the body of a function definition. The
7795 /// '= default' and '= delete' forms are handled by the caller.
7796 ///
7797 /// \verbatim
7798 /// function-body:
7799 /// ctor-initializer[opt] compound-statement
7800 /// function-try-block
7801 /// \endverbatim
7802 ///
7803 Decl *ParseFunctionBody(Decl *D, ParseScope &BodyScope);
7804
7805 /// When in code-completion, skip parsing of the function/method body
7806 /// unless the body contains the code-completion point.
7807 ///
7808 /// \returns true if the function body was skipped.
7809 bool trySkippingFunctionBody();
7810
7811 /// isDeclarationStatement - Disambiguates between a declaration or an
7812 /// expression statement, when parsing function bodies.
7813 ///
7814 /// \param DisambiguatingWithExpression - True to indicate that the purpose of
7815 /// this check is to disambiguate between an expression and a declaration.
7816 /// Returns true for declaration, false for expression.
7817 bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
7818 if (getLangOpts().CPlusPlus)
7819 return isCXXDeclarationStatement(DisambiguatingWithExpression);
7820 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7821 }
7822
7823 /// isForInitDeclaration - Disambiguates between a declaration or an
7824 /// expression in the context of the C 'clause-1' or the C++
7825 // 'for-init-statement' part of a 'for' statement.
7826 /// Returns true for declaration, false for expression.
7827 bool isForInitDeclaration() {
7828 if (getLangOpts().OpenMP)
7829 Actions.OpenMP().startOpenMPLoop();
7830 if (getLangOpts().CPlusPlus)
7831 return Tok.is(tok::kw_using) ||
7832 isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
7833 return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
7834 }
7835
7836 /// Determine whether this is a C++1z for-range-identifier.
7837 bool isForRangeIdentifier();
7838
7839 ///@}
7840
7841 //
7842 //
7843 // -------------------------------------------------------------------------
7844 //
7845 //
7846
7847 /// \name `inline asm` Statement
7848 /// Implementations are in ParseStmtAsm.cpp
7849 ///@{
7850
7851public:
7852 /// Parse an identifier in an MS-style inline assembly block.
7853 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
7854 unsigned &NumLineToksConsumed,
7855 bool IsUnevaluated);
7856
7857private:
7858 /// ParseAsmStatement - Parse a GNU extended asm statement.
7859 /// \verbatim
7860 /// asm-statement:
7861 /// gnu-asm-statement
7862 /// ms-asm-statement
7863 ///
7864 /// [GNU] gnu-asm-statement:
7865 /// 'asm' asm-qualifier-list[opt] '(' asm-argument ')' ';'
7866 ///
7867 /// [GNU] asm-argument:
7868 /// asm-string-literal
7869 /// asm-string-literal ':' asm-operands[opt]
7870 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7871 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
7872 /// ':' asm-clobbers
7873 ///
7874 /// [GNU] asm-clobbers:
7875 /// asm-string-literal
7876 /// asm-clobbers ',' asm-string-literal
7877 /// \endverbatim
7878 ///
7879 StmtResult ParseAsmStatement(bool &msAsm);
7880
7881 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
7882 /// this routine is called to collect the tokens for an MS asm statement.
7883 ///
7884 /// \verbatim
7885 /// [MS] ms-asm-statement:
7886 /// ms-asm-block
7887 /// ms-asm-block ms-asm-statement
7888 ///
7889 /// [MS] ms-asm-block:
7890 /// '__asm' ms-asm-line '\n'
7891 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
7892 ///
7893 /// [MS] ms-asm-instruction-block
7894 /// ms-asm-line
7895 /// ms-asm-line '\n' ms-asm-instruction-block
7896 /// \endverbatim
7897 ///
7898 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
7899
7900 /// ParseAsmOperands - Parse the asm-operands production as used by
7901 /// asm-statement, assuming the leading ':' token was eaten.
7902 ///
7903 /// \verbatim
7904 /// [GNU] asm-operands:
7905 /// asm-operand
7906 /// asm-operands ',' asm-operand
7907 ///
7908 /// [GNU] asm-operand:
7909 /// asm-string-literal '(' expression ')'
7910 /// '[' identifier ']' asm-string-literal '(' expression ')'
7911 /// \endverbatim
7912 ///
7913 // FIXME: Avoid unnecessary std::string trashing.
7914 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
7915 SmallVectorImpl<Expr *> &Constraints,
7916 SmallVectorImpl<Expr *> &Exprs);
7917
7918 class GNUAsmQualifiers {
7919 unsigned Qualifiers = AQ_unspecified;
7920
7921 public:
7922 enum AQ {
7923 AQ_unspecified = 0,
7924 AQ_volatile = 1,
7925 AQ_inline = 2,
7926 AQ_goto = 4,
7927 };
7928 static const char *getQualifierName(AQ Qualifier);
7929 bool setAsmQualifier(AQ Qualifier);
7930 inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
7931 inline bool isInline() const { return Qualifiers & AQ_inline; };
7932 inline bool isGoto() const { return Qualifiers & AQ_goto; }
7933 };
7934
7935 // Determine if this is a GCC-style asm statement.
7936 bool isGCCAsmStatement(const Token &TokAfterAsm) const;
7937
7938 bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
7939 GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
7940
7941 /// parseGNUAsmQualifierListOpt - Parse a GNU extended asm qualifier list.
7942 /// \verbatim
7943 /// asm-qualifier:
7944 /// volatile
7945 /// inline
7946 /// goto
7947 ///
7948 /// asm-qualifier-list:
7949 /// asm-qualifier
7950 /// asm-qualifier-list asm-qualifier
7951 /// \endverbatim
7952 bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
7953
7954 ///@}
7955
7956 //
7957 //
7958 // -------------------------------------------------------------------------
7959 //
7960 //
7961
7962 /// \name C++ Templates
7963 /// Implementations are in ParseTemplate.cpp
7964 ///@{
7965
7966public:
7968
7969 /// Re-enter a possible template scope, creating as many template parameter
7970 /// scopes as necessary.
7971 /// \return The number of template parameter scopes entered.
7973
7974private:
7975 /// The "depth" of the template parameters currently being parsed.
7976 unsigned TemplateParameterDepth;
7977
7978 /// RAII class that manages the template parameter depth.
7979 class TemplateParameterDepthRAII {
7980 unsigned &Depth;
7981 unsigned AddedLevels;
7982
7983 public:
7984 explicit TemplateParameterDepthRAII(unsigned &Depth)
7985 : Depth(Depth), AddedLevels(0) {}
7986
7987 ~TemplateParameterDepthRAII() { Depth -= AddedLevels; }
7988
7989 void operator++() {
7990 ++Depth;
7991 ++AddedLevels;
7992 }
7993 void addDepth(unsigned D) {
7994 Depth += D;
7995 AddedLevels += D;
7996 }
7997 void setAddedDepth(unsigned D) {
7998 Depth = Depth - AddedLevels + D;
7999 AddedLevels = D;
8000 }
8001
8002 unsigned getDepth() const { return Depth; }
8003 unsigned getOriginalDepth() const { return Depth - AddedLevels; }
8004 };
8005
8006 /// Gathers and cleans up TemplateIdAnnotations when parsing of a
8007 /// top-level declaration is finished.
8008 SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
8009
8010 /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
8011 /// we're at the end of a declaration. Instead, we defer the destruction until
8012 /// after a top-level declaration.
8013 /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
8014 bool DelayTemplateIdDestruction = false;
8015
8016 void MaybeDestroyTemplateIds() {
8017 if (DelayTemplateIdDestruction)
8018 return;
8019 if (!TemplateIds.empty() &&
8020 (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
8021 DestroyTemplateIds();
8022 }
8023 void DestroyTemplateIds();
8024
8025 /// RAII object to destroy TemplateIdAnnotations where possible, from a
8026 /// likely-good position during parsing.
8027 struct DestroyTemplateIdAnnotationsRAIIObj {
8028 Parser &Self;
8029
8030 DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
8031 ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
8032 };
8033
8034 struct DelayTemplateIdDestructionRAII {
8035 Parser &Self;
8036 bool PrevDelayTemplateIdDestruction;
8037
8038 DelayTemplateIdDestructionRAII(Parser &Self,
8039 bool DelayTemplateIdDestruction) noexcept
8040 : Self(Self),
8041 PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
8042 Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
8043 }
8044
8045 ~DelayTemplateIdDestructionRAII() noexcept {
8046 Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
8047 }
8048 };
8049
8050 /// Identifiers which have been declared within a tentative parse.
8051 SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
8052
8053 /// Tracker for '<' tokens that might have been intended to be treated as an
8054 /// angle bracket instead of a less-than comparison.
8055 ///
8056 /// This happens when the user intends to form a template-id, but typoes the
8057 /// template-name or forgets a 'template' keyword for a dependent template
8058 /// name.
8059 ///
8060 /// We track these locations from the point where we see a '<' with a
8061 /// name-like expression on its left until we see a '>' or '>>' that might
8062 /// match it.
8063 struct AngleBracketTracker {
8064 /// Flags used to rank candidate template names when there is more than one
8065 /// '<' in a scope.
8066 enum Priority : unsigned short {
8067 /// A non-dependent name that is a potential typo for a template name.
8068 PotentialTypo = 0x0,
8069 /// A dependent name that might instantiate to a template-name.
8070 DependentName = 0x2,
8071
8072 /// A space appears before the '<' token.
8073 SpaceBeforeLess = 0x0,
8074 /// No space before the '<' token
8075 NoSpaceBeforeLess = 0x1,
8076
8077 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
8078 };
8079
8080 struct Loc {
8083 AngleBracketTracker::Priority Priority;
8085
8086 bool isActive(Parser &P) const {
8087 return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
8088 P.BraceCount == BraceCount;
8089 }
8090
8091 bool isActiveOrNested(Parser &P) const {
8092 return isActive(P) || P.ParenCount > ParenCount ||
8093 P.BracketCount > BracketCount || P.BraceCount > BraceCount;
8094 }
8095 };
8096
8098
8099 /// Add an expression that might have been intended to be a template name.
8100 /// In the case of ambiguity, we arbitrarily select the innermost such
8101 /// expression, for example in 'foo < bar < baz', 'bar' is the current
8102 /// candidate. No attempt is made to track that 'foo' is also a candidate
8103 /// for the case where we see a second suspicious '>' token.
8104 void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
8105 Priority Prio) {
8106 if (!Locs.empty() && Locs.back().isActive(P)) {
8107 if (Locs.back().Priority <= Prio) {
8108 Locs.back().TemplateName = TemplateName;
8109 Locs.back().LessLoc = LessLoc;
8110 Locs.back().Priority = Prio;
8111 }
8112 } else {
8113 Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount,
8114 P.BracketCount, P.BraceCount});
8115 }
8116 }
8117
8118 /// Mark the current potential missing template location as having been
8119 /// handled (this happens if we pass a "corresponding" '>' or '>>' token
8120 /// or leave a bracket scope).
8121 void clear(Parser &P) {
8122 while (!Locs.empty() && Locs.back().isActiveOrNested(P))
8123 Locs.pop_back();
8124 }
8125
8126 /// Get the current enclosing expression that might hve been intended to be
8127 /// a template name.
8128 Loc *getCurrent(Parser &P) {
8129 if (!Locs.empty() && Locs.back().isActive(P))
8130 return &Locs.back();
8131 return nullptr;
8132 }
8133 };
8134
8135 AngleBracketTracker AngleBrackets;
8136
8137 /// Contains information about any template-specific
8138 /// information that has been parsed prior to parsing declaration
8139 /// specifiers.
8140 struct ParsedTemplateInfo {
8141 ParsedTemplateInfo()
8142 : Kind(ParsedTemplateKind::NonTemplate), TemplateParams(nullptr) {}
8143
8144 ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
8145 bool isSpecialization,
8146 bool lastParameterListWasEmpty = false)
8147 : Kind(isSpecialization ? ParsedTemplateKind::ExplicitSpecialization
8149 TemplateParams(TemplateParams),
8150 LastParameterListWasEmpty(lastParameterListWasEmpty) {}
8151
8152 explicit ParsedTemplateInfo(SourceLocation ExternLoc,
8153 SourceLocation TemplateLoc)
8155 TemplateParams(nullptr), ExternLoc(ExternLoc),
8156 TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false) {}
8157
8158 ParsedTemplateKind Kind;
8159
8160 /// The template parameter lists, for template declarations
8161 /// and explicit specializations.
8162 TemplateParameterLists *TemplateParams;
8163
8164 /// The location of the 'extern' keyword, if any, for an explicit
8165 /// instantiation
8166 SourceLocation ExternLoc;
8167
8168 /// The location of the 'template' keyword, for an explicit
8169 /// instantiation.
8170 SourceLocation TemplateLoc;
8171
8172 /// Whether the last template parameter list was empty.
8173 bool LastParameterListWasEmpty;
8174
8175 SourceRange getSourceRange() const LLVM_READONLY;
8176 };
8177
8178 /// Lex a delayed template function for late parsing.
8179 void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
8180
8181 /// Late parse a C++ function template in Microsoft mode.
8182 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
8183
8184 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
8185
8186 /// We've parsed something that could plausibly be intended to be a template
8187 /// name (\p LHS) followed by a '<' token, and the following code can't
8188 /// possibly be an expression. Determine if this is likely to be a template-id
8189 /// and if so, diagnose it.
8190 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
8191
8192 void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
8193 bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
8194 const Token &OpToken);
8195 bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
8196 if (auto *Info = AngleBrackets.getCurrent(*this))
8197 return checkPotentialAngleBracketDelimiter(*Info, OpToken);
8198 return false;
8199 }
8200
8201 //===--------------------------------------------------------------------===//
8202 // C++ 14: Templates [temp]
8203
8204 /// Parse a template declaration, explicit instantiation, or
8205 /// explicit specialization.
8207 ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
8208 SourceLocation &DeclEnd,
8209 ParsedAttributes &AccessAttrs);
8210
8211 /// Parse a template declaration or an explicit specialization.
8212 ///
8213 /// Template declarations include one or more template parameter lists
8214 /// and either the function or class template declaration. Explicit
8215 /// specializations contain one or more 'template < >' prefixes
8216 /// followed by a (possibly templated) declaration. Since the
8217 /// syntactic form of both features is nearly identical, we parse all
8218 /// of the template headers together and let semantic analysis sort
8219 /// the declarations from the explicit specializations.
8220 ///
8221 /// \verbatim
8222 /// template-declaration: [C++ temp]
8223 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
8224 ///
8225 /// template-declaration: [C++2a]
8226 /// template-head declaration
8227 /// template-head concept-definition
8228 ///
8229 /// TODO: requires-clause
8230 /// template-head: [C++2a]
8231 /// 'template' '<' template-parameter-list '>'
8232 /// requires-clause[opt]
8233 ///
8234 /// explicit-specialization: [ C++ temp.expl.spec]
8235 /// 'template' '<' '>' declaration
8236 /// \endverbatim
8237 DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8238 DeclaratorContext Context, SourceLocation &DeclEnd,
8239 ParsedAttributes &AccessAttrs, AccessSpecifier AS);
8240
8241 clang::Parser::DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
8242 DeclaratorContext Context, SourceLocation &DeclEnd, AccessSpecifier AS);
8243
8244 /// Parse a single declaration that declares a template,
8245 /// template specialization, or explicit instantiation of a template.
8246 ///
8247 /// \param DeclEnd will receive the source location of the last token
8248 /// within this declaration.
8249 ///
8250 /// \param AS the access specifier associated with this
8251 /// declaration. Will be AS_none for namespace-scope declarations.
8252 ///
8253 /// \returns the new declaration.
8254 DeclGroupPtrTy ParseDeclarationAfterTemplate(
8255 DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
8256 ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
8257 ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
8258
8259 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
8260 /// angle brackets. Depth is the depth of this template-parameter-list, which
8261 /// is the number of template headers directly enclosing this template header.
8262 /// TemplateParams is the current list of template parameters we're building.
8263 /// The template parameter we parse will be added to this list. LAngleLoc and
8264 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
8265 /// that enclose this template parameter list.
8266 ///
8267 /// \returns true if an error occurred, false otherwise.
8268 bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
8269 SmallVectorImpl<NamedDecl *> &TemplateParams,
8270 SourceLocation &LAngleLoc,
8271 SourceLocation &RAngleLoc);
8272
8273 /// ParseTemplateParameterList - Parse a template parameter list. If
8274 /// the parsing fails badly (i.e., closing bracket was left out), this
8275 /// will try to put the token stream in a reasonable position (closing
8276 /// a statement, etc.) and return false.
8277 ///
8278 /// \verbatim
8279 /// template-parameter-list: [C++ temp]
8280 /// template-parameter
8281 /// template-parameter-list ',' template-parameter
8282 /// \endverbatim
8283 bool ParseTemplateParameterList(unsigned Depth,
8284 SmallVectorImpl<NamedDecl *> &TemplateParams);
8285
8286 enum class TPResult;
8287
8288 /// Determine whether the parser is at the start of a template
8289 /// type parameter.
8290 TPResult isStartOfTemplateTypeParameter();
8291
8292 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
8293 ///
8294 /// \verbatim
8295 /// template-parameter: [C++ temp.param]
8296 /// type-parameter
8297 /// parameter-declaration
8298 ///
8299 /// type-parameter: (See below)
8300 /// type-parameter-key ...[opt] identifier[opt]
8301 /// type-parameter-key identifier[opt] = type-id
8302 /// (C++2a) type-constraint ...[opt] identifier[opt]
8303 /// (C++2a) type-constraint identifier[opt] = type-id
8304 /// 'template' '<' template-parameter-list '>' type-parameter-key
8305 /// ...[opt] identifier[opt]
8306 /// 'template' '<' template-parameter-list '>' type-parameter-key
8307 /// identifier[opt] '=' id-expression
8308 ///
8309 /// type-parameter-key:
8310 /// class
8311 /// typename
8312 /// \endverbatim
8313 ///
8314 NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
8315
8316 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
8317 /// Other kinds of template parameters are parsed in
8318 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
8319 ///
8320 /// \verbatim
8321 /// type-parameter: [C++ temp.param]
8322 /// 'class' ...[opt][C++0x] identifier[opt]
8323 /// 'class' identifier[opt] '=' type-id
8324 /// 'typename' ...[opt][C++0x] identifier[opt]
8325 /// 'typename' identifier[opt] '=' type-id
8326 /// \endverbatim
8327 NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
8328
8329 /// ParseTemplateTemplateParameter - Handle the parsing of template
8330 /// template parameters.
8331 ///
8332 /// \verbatim
8333 /// type-parameter: [C++ temp.param]
8334 /// template-head type-parameter-key ...[opt] identifier[opt]
8335 /// template-head type-parameter-key identifier[opt] = id-expression
8336 /// type-parameter-key:
8337 /// 'class'
8338 /// 'typename' [C++1z]
8339 /// template-head: [C++2a]
8340 /// 'template' '<' template-parameter-list '>'
8341 /// requires-clause[opt]
8342 /// \endverbatim
8343 NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
8344
8345 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
8346 /// template parameters (e.g., in "template<int Size> class array;").
8347 ///
8348 /// \verbatim
8349 /// template-parameter:
8350 /// ...
8351 /// parameter-declaration
8352 /// \endverbatim
8353 NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
8354
8355 /// Check whether the current token is a template-id annotation denoting a
8356 /// type-constraint.
8357 bool isTypeConstraintAnnotation();
8358
8359 /// Try parsing a type-constraint at the current location.
8360 ///
8361 /// \verbatim
8362 /// type-constraint:
8363 /// nested-name-specifier[opt] concept-name
8364 /// nested-name-specifier[opt] concept-name
8365 /// '<' template-argument-list[opt] '>'[opt]
8366 /// \endverbatim
8367 ///
8368 /// \returns true if an error occurred, and false otherwise.
8369 bool TryAnnotateTypeConstraint();
8370
8371 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
8372 SourceLocation CorrectLoc,
8373 bool AlreadyHasEllipsis,
8374 bool IdentifierHasName);
8375 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
8376 Declarator &D);
8377 // C++ 14.3: Template arguments [temp.arg]
8378 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
8379
8380 /// Parses a '>' at the end of a template list.
8381 ///
8382 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
8383 /// to determine if these tokens were supposed to be a '>' followed by
8384 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
8385 ///
8386 /// \param RAngleLoc the location of the consumed '>'.
8387 ///
8388 /// \param ConsumeLastToken if true, the '>' is consumed.
8389 ///
8390 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
8391 /// type parameter or type argument list, rather than a C++ template parameter
8392 /// or argument list.
8393 ///
8394 /// \returns true, if current token does not start with '>', false otherwise.
8395 bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
8396 SourceLocation &RAngleLoc,
8397 bool ConsumeLastToken,
8398 bool ObjCGenericList);
8399
8400 /// Parses a template-id that after the template name has
8401 /// already been parsed.
8402 ///
8403 /// This routine takes care of parsing the enclosed template argument
8404 /// list ('<' template-parameter-list [opt] '>') and placing the
8405 /// results into a form that can be transferred to semantic analysis.
8406 ///
8407 /// \param ConsumeLastToken if true, then we will consume the last
8408 /// token that forms the template-id. Otherwise, we will leave the
8409 /// last token in the stream (e.g., so that it can be replaced with an
8410 /// annotation token).
8411 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
8412 SourceLocation &LAngleLoc,
8413 TemplateArgList &TemplateArgs,
8414 SourceLocation &RAngleLoc,
8415 TemplateTy NameHint = nullptr);
8416
8417 /// Replace the tokens that form a simple-template-id with an
8418 /// annotation token containing the complete template-id.
8419 ///
8420 /// The first token in the stream must be the name of a template that
8421 /// is followed by a '<'. This routine will parse the complete
8422 /// simple-template-id and replace the tokens with a single annotation
8423 /// token with one of two different kinds: if the template-id names a
8424 /// type (and \p AllowTypeAnnotation is true), the annotation token is
8425 /// a type annotation that includes the optional nested-name-specifier
8426 /// (\p SS). Otherwise, the annotation token is a template-id
8427 /// annotation that does not include the optional
8428 /// nested-name-specifier.
8429 ///
8430 /// \param Template the declaration of the template named by the first
8431 /// token (an identifier), as returned from \c Action::isTemplateName().
8432 ///
8433 /// \param TNK the kind of template that \p Template
8434 /// refers to, as returned from \c Action::isTemplateName().
8435 ///
8436 /// \param SS if non-NULL, the nested-name-specifier that precedes
8437 /// this template name.
8438 ///
8439 /// \param TemplateKWLoc if valid, specifies that this template-id
8440 /// annotation was preceded by the 'template' keyword and gives the
8441 /// location of that keyword. If invalid (the default), then this
8442 /// template-id was not preceded by a 'template' keyword.
8443 ///
8444 /// \param AllowTypeAnnotation if true (the default), then a
8445 /// simple-template-id that refers to a class template, template
8446 /// template parameter, or other template that produces a type will be
8447 /// replaced with a type annotation token. Otherwise, the
8448 /// simple-template-id is always replaced with a template-id
8449 /// annotation token.
8450 ///
8451 /// \param TypeConstraint if true, then this is actually a type-constraint,
8452 /// meaning that the template argument list can be omitted (and the template
8453 /// in question must be a concept).
8454 ///
8455 /// If an unrecoverable parse error occurs and no annotation token can be
8456 /// formed, this function returns true.
8457 ///
8458 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
8459 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8460 UnqualifiedId &TemplateName,
8461 bool AllowTypeAnnotation = true,
8462 bool TypeConstraint = false);
8463
8464 /// Replaces a template-id annotation token with a type
8465 /// annotation token.
8466 ///
8467 /// If there was a failure when forming the type from the template-id,
8468 /// a type annotation token will still be created, but will have a
8469 /// NULL type pointer to signify an error.
8470 ///
8471 /// \param SS The scope specifier appearing before the template-id, if any.
8472 ///
8473 /// \param AllowImplicitTypename whether this is a context where T::type
8474 /// denotes a dependent type.
8475 /// \param IsClassName Is this template-id appearing in a context where we
8476 /// know it names a class, such as in an elaborated-type-specifier or
8477 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
8478 /// in those contexts.)
8479 void
8480 AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
8481 ImplicitTypenameContext AllowImplicitTypename,
8482 bool IsClassName = false);
8483
8484 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
8485 /// (C++ [temp.names]). Returns true if there was an error.
8486 ///
8487 /// \verbatim
8488 /// template-argument-list: [C++ 14.2]
8489 /// template-argument
8490 /// template-argument-list ',' template-argument
8491 /// \endverbatim
8492 ///
8493 /// \param Template is only used for code completion, and may be null.
8494 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
8495 TemplateTy Template, SourceLocation OpenLoc);
8496
8497 /// Parse a C++ template template argument.
8498 ParsedTemplateArgument ParseTemplateTemplateArgument();
8499
8500 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
8501 ///
8502 /// \verbatim
8503 /// template-argument: [C++ 14.2]
8504 /// constant-expression
8505 /// type-id
8506 /// id-expression
8507 /// braced-init-list [C++26, DR]
8508 /// \endverbatim
8509 ///
8510 ParsedTemplateArgument ParseTemplateArgument();
8511
8512 /// Parse a C++ explicit template instantiation
8513 /// (C++ [temp.explicit]).
8514 ///
8515 /// \verbatim
8516 /// explicit-instantiation:
8517 /// 'extern' [opt] 'template' declaration
8518 /// \endverbatim
8519 ///
8520 /// Note that the 'extern' is a GNU extension and C++11 feature.
8521 DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
8522 SourceLocation ExternLoc,
8523 SourceLocation TemplateLoc,
8524 SourceLocation &DeclEnd,
8525 ParsedAttributes &AccessAttrs,
8527
8528 /// \brief Parse a single declaration that declares a concept.
8529 ///
8530 /// \param DeclEnd will receive the source location of the last token
8531 /// within this declaration.
8532 ///
8533 /// \returns the new declaration.
8534 Decl *ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
8535 SourceLocation &DeclEnd);
8536
8537 ///@}
8538
8539 //
8540 //
8541 // -------------------------------------------------------------------------
8542 //
8543 //
8544
8545 /// \name Tentative Parsing
8546 /// Implementations are in ParseTentative.cpp
8547 ///@{
8548
8549private:
8550 /// TentativeParsingAction - An object that is used as a kind of "tentative
8551 /// parsing transaction". It gets instantiated to mark the token position and
8552 /// after the token consumption is done, Commit() or Revert() is called to
8553 /// either "commit the consumed tokens" or revert to the previously marked
8554 /// token position. Example:
8555 ///
8556 /// TentativeParsingAction TPA(*this);
8557 /// ConsumeToken();
8558 /// ....
8559 /// TPA.Revert();
8560 ///
8561 /// If the Unannotated parameter is true, any token annotations created
8562 /// during the tentative parse are reverted.
8563 class TentativeParsingAction {
8564 Parser &P;
8565 PreferredTypeBuilder PrevPreferredType;
8566 Token PrevTok;
8567 size_t PrevTentativelyDeclaredIdentifierCount;
8568 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
8569 bool isActive;
8570
8571 public:
8572 explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
8573 : P(p), PrevPreferredType(P.PreferredType) {
8574 PrevTok = P.Tok;
8575 PrevTentativelyDeclaredIdentifierCount =
8576 P.TentativelyDeclaredIdentifiers.size();
8577 PrevParenCount = P.ParenCount;
8578 PrevBracketCount = P.BracketCount;
8579 PrevBraceCount = P.BraceCount;
8580 P.PP.EnableBacktrackAtThisPos(Unannotated);
8581 isActive = true;
8582 }
8583 void Commit() {
8584 assert(isActive && "Parsing action was finished!");
8585 P.TentativelyDeclaredIdentifiers.resize(
8586 PrevTentativelyDeclaredIdentifierCount);
8587 P.PP.CommitBacktrackedTokens();
8588 isActive = false;
8589 }
8590 void Revert() {
8591 assert(isActive && "Parsing action was finished!");
8592 P.PP.Backtrack();
8593 P.PreferredType = PrevPreferredType;
8594 P.Tok = PrevTok;
8595 P.TentativelyDeclaredIdentifiers.resize(
8596 PrevTentativelyDeclaredIdentifierCount);
8597 P.ParenCount = PrevParenCount;
8598 P.BracketCount = PrevBracketCount;
8599 P.BraceCount = PrevBraceCount;
8600 isActive = false;
8601 }
8602 ~TentativeParsingAction() {
8603 assert(!isActive && "Forgot to call Commit or Revert!");
8604 }
8605 };
8606
8607 /// A TentativeParsingAction that automatically reverts in its destructor.
8608 /// Useful for disambiguation parses that will always be reverted.
8609 class RevertingTentativeParsingAction
8610 : private Parser::TentativeParsingAction {
8611 public:
8612 using TentativeParsingAction::TentativeParsingAction;
8613
8614 ~RevertingTentativeParsingAction() { Revert(); }
8615 };
8616
8617 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
8618 /// between a declaration or an expression statement, when parsing function
8619 /// bodies. Returns true for declaration, false for expression.
8620 ///
8621 /// \verbatim
8622 /// declaration-statement:
8623 /// block-declaration
8624 ///
8625 /// block-declaration:
8626 /// simple-declaration
8627 /// asm-definition
8628 /// namespace-alias-definition
8629 /// using-declaration
8630 /// using-directive
8631 /// [C++0x] static_assert-declaration
8632 ///
8633 /// asm-definition:
8634 /// 'asm' '(' string-literal ')' ';'
8635 ///
8636 /// namespace-alias-definition:
8637 /// 'namespace' identifier = qualified-namespace-specifier ';'
8638 ///
8639 /// using-declaration:
8640 /// 'using' typename[opt] '::'[opt] nested-name-specifier
8641 /// unqualified-id ';'
8642 /// 'using' '::' unqualified-id ;
8643 ///
8644 /// using-directive:
8645 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
8646 /// namespace-name ';'
8647 /// \endverbatim
8648 ///
8649 bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
8650
8651 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
8652 /// between a simple-declaration or an expression-statement.
8653 /// If during the disambiguation process a parsing error is encountered,
8654 /// the function returns true to let the declaration parsing code handle it.
8655 /// Returns false if the statement is disambiguated as expression.
8656 ///
8657 /// \verbatim
8658 /// simple-declaration:
8659 /// decl-specifier-seq init-declarator-list[opt] ';'
8660 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8661 /// brace-or-equal-initializer ';' [C++17]
8662 /// \endverbatim
8663 ///
8664 /// (if AllowForRangeDecl specified)
8665 /// for ( for-range-declaration : for-range-initializer ) statement
8666 ///
8667 /// \verbatim
8668 /// for-range-declaration:
8669 /// decl-specifier-seq declarator
8670 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
8671 /// \endverbatim
8672 ///
8673 /// In any of the above cases there can be a preceding
8674 /// attribute-specifier-seq, but the caller is expected to handle that.
8675 bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
8676
8677 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
8678 /// a constructor-style initializer, when parsing declaration statements.
8679 /// Returns true for function declarator and false for constructor-style
8680 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
8681 /// might be a constructor-style initializer.
8682 /// If during the disambiguation process a parsing error is encountered,
8683 /// the function returns true to let the declaration parsing code handle it.
8684 ///
8685 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
8686 /// exception-specification[opt]
8687 ///
8688 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
8689 ImplicitTypenameContext AllowImplicitTypename =
8691
8692 struct ConditionDeclarationOrInitStatementState;
8693 enum class ConditionOrInitStatement {
8694 Expression, ///< Disambiguated as an expression (either kind).
8695 ConditionDecl, ///< Disambiguated as the declaration form of condition.
8696 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement.
8697 ForRangeDecl, ///< Disambiguated as a for-range declaration.
8698 Error ///< Can't be any of the above!
8699 };
8700
8701 /// Disambiguates between a declaration in a condition, a
8702 /// simple-declaration in an init-statement, and an expression for
8703 /// a condition of a if/switch statement.
8704 ///
8705 /// \verbatim
8706 /// condition:
8707 /// expression
8708 /// type-specifier-seq declarator '=' assignment-expression
8709 /// [C++11] type-specifier-seq declarator '=' initializer-clause
8710 /// [C++11] type-specifier-seq declarator braced-init-list
8711 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
8712 /// '=' assignment-expression
8713 /// simple-declaration:
8714 /// decl-specifier-seq init-declarator-list[opt] ';'
8715 /// \endverbatim
8716 ///
8717 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
8718 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
8719 /// 'int(x);' (a simple-declaration in an init-statement).
8720 ConditionOrInitStatement
8721 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
8722 bool CanBeForRangeDecl);
8723
8724 /// Determine whether the next set of tokens contains a type-id.
8725 ///
8726 /// The context parameter states what context we're parsing right
8727 /// now, which affects how this routine copes with the token
8728 /// following the type-id. If the context is
8729 /// TentativeCXXTypeIdContext::InParens, we have already parsed the '(' and we
8730 /// will cease lookahead when we hit the corresponding ')'. If the context is
8731 /// TentativeCXXTypeIdContext::AsTemplateArgument, we've already parsed the
8732 /// '<' or ',' before this template argument, and will cease lookahead when we
8733 /// hit a
8734 /// '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
8735 /// preceding such. Returns true for a type-id and false for an expression.
8736 /// If during the disambiguation process a parsing error is encountered,
8737 /// the function returns true to let the declaration parsing code handle it.
8738 ///
8739 /// \verbatim
8740 /// type-id:
8741 /// type-specifier-seq abstract-declarator[opt]
8742 /// \endverbatim
8743 ///
8744 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
8745
8746 bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
8747 bool isAmbiguous;
8748 return isCXXTypeId(Context, isAmbiguous);
8749 }
8750
8751 /// TPResult - Used as the result value for functions whose purpose is to
8752 /// disambiguate C++ constructs by "tentatively parsing" them.
8753 enum class TPResult { True, False, Ambiguous, Error };
8754
8755 /// Determine whether we could have an enum-base.
8756 ///
8757 /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
8758 /// only consider this to be an enum-base if the next token is a '{'.
8759 ///
8760 /// \return \c false if this cannot possibly be an enum base; \c true
8761 /// otherwise.
8762 bool isEnumBase(bool AllowSemi);
8763
8764 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
8765 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
8766 /// be either a decl-specifier or a function-style cast, and TPResult::Error
8767 /// if a parsing error was found and reported.
8768 ///
8769 /// Does not consume tokens.
8770 ///
8771 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
8772 /// declaration specifiers but possibly valid as some other kind of construct
8773 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
8774 /// the intent is to keep trying to disambiguate, on the basis that we might
8775 /// find a better reason to treat this construct as a declaration later on.
8776 /// When this happens and the name could possibly be valid in some other
8777 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
8778 /// that trigger this are:
8779 ///
8780 /// * When parsing X::Y (with no 'typename') where X is dependent
8781 /// * When parsing X<Y> where X is undeclared
8782 ///
8783 /// \verbatim
8784 /// decl-specifier:
8785 /// storage-class-specifier
8786 /// type-specifier
8787 /// function-specifier
8788 /// 'friend'
8789 /// 'typedef'
8790 /// [C++11] 'constexpr'
8791 /// [C++20] 'consteval'
8792 /// [GNU] attributes declaration-specifiers[opt]
8793 ///
8794 /// storage-class-specifier:
8795 /// 'register'
8796 /// 'static'
8797 /// 'extern'
8798 /// 'mutable'
8799 /// 'auto'
8800 /// [GNU] '__thread'
8801 /// [C++11] 'thread_local'
8802 /// [C11] '_Thread_local'
8803 ///
8804 /// function-specifier:
8805 /// 'inline'
8806 /// 'virtual'
8807 /// 'explicit'
8808 ///
8809 /// typedef-name:
8810 /// identifier
8811 ///
8812 /// type-specifier:
8813 /// simple-type-specifier
8814 /// class-specifier
8815 /// enum-specifier
8816 /// elaborated-type-specifier
8817 /// typename-specifier
8818 /// cv-qualifier
8819 ///
8820 /// simple-type-specifier:
8821 /// '::'[opt] nested-name-specifier[opt] type-name
8822 /// '::'[opt] nested-name-specifier 'template'
8823 /// simple-template-id [TODO]
8824 /// 'char'
8825 /// 'wchar_t'
8826 /// 'bool'
8827 /// 'short'
8828 /// 'int'
8829 /// 'long'
8830 /// 'signed'
8831 /// 'unsigned'
8832 /// 'float'
8833 /// 'double'
8834 /// 'void'
8835 /// [GNU] typeof-specifier
8836 /// [GNU] '_Complex'
8837 /// [C++11] 'auto'
8838 /// [GNU] '__auto_type'
8839 /// [C++11] 'decltype' ( expression )
8840 /// [C++1y] 'decltype' ( 'auto' )
8841 ///
8842 /// type-name:
8843 /// class-name
8844 /// enum-name
8845 /// typedef-name
8846 ///
8847 /// elaborated-type-specifier:
8848 /// class-key '::'[opt] nested-name-specifier[opt] identifier
8849 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
8850 /// simple-template-id
8851 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
8852 ///
8853 /// enum-name:
8854 /// identifier
8855 ///
8856 /// enum-specifier:
8857 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
8858 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
8859 ///
8860 /// class-specifier:
8861 /// class-head '{' member-specification[opt] '}'
8862 ///
8863 /// class-head:
8864 /// class-key identifier[opt] base-clause[opt]
8865 /// class-key nested-name-specifier identifier base-clause[opt]
8866 /// class-key nested-name-specifier[opt] simple-template-id
8867 /// base-clause[opt]
8868 ///
8869 /// class-key:
8870 /// 'class'
8871 /// 'struct'
8872 /// 'union'
8873 ///
8874 /// cv-qualifier:
8875 /// 'const'
8876 /// 'volatile'
8877 /// [GNU] restrict
8878 /// \endverbatim
8879 ///
8880 TPResult
8881 isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
8882 TPResult BracedCastResult = TPResult::False,
8883 bool *InvalidAsDeclSpec = nullptr);
8884
8885 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
8886 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
8887 /// a type-specifier other than a cv-qualifier.
8888 bool isCXXDeclarationSpecifierAType();
8889
8890 /// Determine whether we might be looking at the '<' template-argument-list
8891 /// '>' of a template-id or simple-template-id, rather than a less-than
8892 /// comparison. This will often fail and produce an ambiguity, but should
8893 /// never be wrong if it returns True or False.
8894 TPResult isTemplateArgumentList(unsigned TokensToSkip);
8895
8896 /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
8897 /// 'explicit(bool)' declaration, in earlier language modes where that is an
8898 /// extension.
8899 TPResult isExplicitBool();
8900
8901 /// Determine whether an identifier has been tentatively declared as a
8902 /// non-type. Such tentative declarations should not be found to name a type
8903 /// during a tentative parse, but also should not be annotated as a non-type.
8904 bool isTentativelyDeclared(IdentifierInfo *II);
8905
8906 // "Tentative parsing" functions, used for disambiguation. If a parsing error
8907 // is encountered they will return TPResult::Error.
8908 // Returning TPResult::True/False indicates that the ambiguity was
8909 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
8910 // that more tentative parsing is necessary for disambiguation.
8911 // They all consume tokens, so backtracking should be used after calling them.
8912
8913 /// \verbatim
8914 /// simple-declaration:
8915 /// decl-specifier-seq init-declarator-list[opt] ';'
8916 ///
8917 /// (if AllowForRangeDecl specified)
8918 /// for ( for-range-declaration : for-range-initializer ) statement
8919 /// for-range-declaration:
8920 /// attribute-specifier-seqopt type-specifier-seq declarator
8921 /// \endverbatim
8922 ///
8923 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
8924
8925 /// \verbatim
8926 /// [GNU] typeof-specifier:
8927 /// 'typeof' '(' expressions ')'
8928 /// 'typeof' '(' type-name ')'
8929 /// \endverbatim
8930 ///
8931 TPResult TryParseTypeofSpecifier();
8932
8933 /// [ObjC] protocol-qualifiers:
8934 /// '<' identifier-list '>'
8935 TPResult TryParseProtocolQualifiers();
8936
8937 TPResult TryParsePtrOperatorSeq();
8938
8939 /// \verbatim
8940 /// operator-function-id:
8941 /// 'operator' operator
8942 ///
8943 /// operator: one of
8944 /// new delete new[] delete[] + - * / % ^ [...]
8945 ///
8946 /// conversion-function-id:
8947 /// 'operator' conversion-type-id
8948 ///
8949 /// conversion-type-id:
8950 /// type-specifier-seq conversion-declarator[opt]
8951 ///
8952 /// conversion-declarator:
8953 /// ptr-operator conversion-declarator[opt]
8954 ///
8955 /// literal-operator-id:
8956 /// 'operator' string-literal identifier
8957 /// 'operator' user-defined-string-literal
8958 /// \endverbatim
8959 TPResult TryParseOperatorId();
8960
8961 /// Tentatively parse an init-declarator-list in order to disambiguate it from
8962 /// an expression.
8963 ///
8964 /// \verbatim
8965 /// init-declarator-list:
8966 /// init-declarator
8967 /// init-declarator-list ',' init-declarator
8968 ///
8969 /// init-declarator:
8970 /// declarator initializer[opt]
8971 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
8972 ///
8973 /// initializer:
8974 /// brace-or-equal-initializer
8975 /// '(' expression-list ')'
8976 ///
8977 /// brace-or-equal-initializer:
8978 /// '=' initializer-clause
8979 /// [C++11] braced-init-list
8980 ///
8981 /// initializer-clause:
8982 /// assignment-expression
8983 /// braced-init-list
8984 ///
8985 /// braced-init-list:
8986 /// '{' initializer-list ','[opt] '}'
8987 /// '{' '}'
8988 /// \endverbatim
8989 ///
8990 TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
8991
8992 /// \verbatim
8993 /// declarator:
8994 /// direct-declarator
8995 /// ptr-operator declarator
8996 ///
8997 /// direct-declarator:
8998 /// declarator-id
8999 /// direct-declarator '(' parameter-declaration-clause ')'
9000 /// cv-qualifier-seq[opt] exception-specification[opt]
9001 /// direct-declarator '[' constant-expression[opt] ']'
9002 /// '(' declarator ')'
9003 /// [GNU] '(' attributes declarator ')'
9004 ///
9005 /// abstract-declarator:
9006 /// ptr-operator abstract-declarator[opt]
9007 /// direct-abstract-declarator
9008 ///
9009 /// direct-abstract-declarator:
9010 /// direct-abstract-declarator[opt]
9011 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
9012 /// exception-specification[opt]
9013 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
9014 /// '(' abstract-declarator ')'
9015 /// [C++0x] ...
9016 ///
9017 /// ptr-operator:
9018 /// '*' cv-qualifier-seq[opt]
9019 /// '&'
9020 /// [C++0x] '&&' [TODO]
9021 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
9022 ///
9023 /// cv-qualifier-seq:
9024 /// cv-qualifier cv-qualifier-seq[opt]
9025 ///
9026 /// cv-qualifier:
9027 /// 'const'
9028 /// 'volatile'
9029 ///
9030 /// declarator-id:
9031 /// '...'[opt] id-expression
9032 ///
9033 /// id-expression:
9034 /// unqualified-id
9035 /// qualified-id [TODO]
9036 ///
9037 /// unqualified-id:
9038 /// identifier
9039 /// operator-function-id
9040 /// conversion-function-id
9041 /// literal-operator-id
9042 /// '~' class-name [TODO]
9043 /// '~' decltype-specifier [TODO]
9044 /// template-id [TODO]
9045 /// \endverbatim
9046 ///
9047 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
9048 bool mayHaveDirectInit = false,
9049 bool mayHaveTrailingReturnType = false);
9050
9051 /// \verbatim
9052 /// parameter-declaration-clause:
9053 /// parameter-declaration-list[opt] '...'[opt]
9054 /// parameter-declaration-list ',' '...'
9055 ///
9056 /// parameter-declaration-list:
9057 /// parameter-declaration
9058 /// parameter-declaration-list ',' parameter-declaration
9059 ///
9060 /// parameter-declaration:
9061 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
9062 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
9063 /// '=' assignment-expression
9064 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
9065 /// attributes[opt]
9066 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
9067 /// attributes[opt] '=' assignment-expression
9068 /// \endverbatim
9069 ///
9070 TPResult TryParseParameterDeclarationClause(
9071 bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
9072 ImplicitTypenameContext AllowImplicitTypename =
9074
9075 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to
9076 /// continue parsing as a function declarator. If TryParseFunctionDeclarator
9077 /// fully parsed the function declarator, it will return TPResult::Ambiguous,
9078 /// otherwise it will return either False() or Error().
9079 ///
9080 /// \verbatim
9081 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
9082 /// exception-specification[opt]
9083 ///
9084 /// exception-specification:
9085 /// 'throw' '(' type-id-list[opt] ')'
9086 /// \endverbatim
9087 ///
9088 TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
9089
9090 // When parsing an identifier after an arrow it may be a member expression,
9091 // in which case we should not annotate it as an independant expression
9092 // so we just lookup that name, if it's not a type the construct is not
9093 // a function declaration.
9094 bool NameAfterArrowIsNonType();
9095
9096 /// \verbatim
9097 /// '[' constant-expression[opt] ']'
9098 /// \endverbatim
9099 ///
9100 TPResult TryParseBracketDeclarator();
9101
9102 /// Try to consume a token sequence that we've already identified as
9103 /// (potentially) starting a decl-specifier.
9104 TPResult TryConsumeDeclarationSpecifier();
9105
9106 /// Try to skip a possibly empty sequence of 'attribute-specifier's without
9107 /// full validation of the syntactic structure of attributes.
9108 bool TrySkipAttributes();
9109
9110 /// Whether tentative lookahead from the current '[' finds a lambda-like
9111 /// continuation. This does not parse or validate a lambda.
9112 bool hasLambdaLikeContinuation();
9113
9114 //===--------------------------------------------------------------------===//
9115 // C++ 7: Declarations [dcl.dcl]
9116
9117 /// Returns true if this is a C++11 attribute-specifier. Per
9118 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
9119 /// always introduce an attribute. In Objective-C++11, this rule does not
9120 /// apply if either '[' begins a message-send.
9121 ///
9122 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
9123 /// an attribute-specifier, and return
9124 /// CXX11AttributeKind::InvalidAttributeSpecifier if not.
9125 ///
9126 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
9127 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
9128 /// is not an Obj-C message send.
9129 ///
9130 /// C++11 [dcl.attr.grammar]:
9131 ///
9132 /// \verbatim
9133 /// attribute-specifier:
9134 /// '[' '[' attribute-list ']' ']'
9135 /// alignment-specifier
9136 ///
9137 /// attribute-list:
9138 /// attribute[opt]
9139 /// attribute-list ',' attribute[opt]
9140 /// attribute '...'
9141 /// attribute-list ',' attribute '...'
9142 ///
9143 /// attribute:
9144 /// attribute-token attribute-argument-clause[opt]
9145 ///
9146 /// attribute-token:
9147 /// identifier
9148 /// identifier '::' identifier
9149 ///
9150 /// attribute-argument-clause:
9151 /// '(' balanced-token-seq ')'
9152 /// \endverbatim
9154 isCXX11AttributeSpecifier(bool Disambiguate = false,
9155 bool OuterMightBeMessageSend = false);
9156
9157 ///@}
9158};
9159
9160} // end namespace clang
9161
9162#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:1888
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:100
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1863
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:2016
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:6438
ExprResult ParseConstantExpressionInExprEvalContext(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
SmallVector< Stmt *, 24 > StmtVector
A SmallVector of statements.
Definition Parser.h:7343
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:5449
friend class ParsingOpenACCDirectiveRAII
Definition Parser.h:6170
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:5458
friend class ObjCDeclContextSwitch
Definition Parser.h:5450
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:7348
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:5452
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:7967
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:2133
bool ParseOpenMPDeclareBeginVariantDirective(SourceLocation Loc)
Parses 'omp begin declare variant' directive.
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
A class for parsing a declarator.
A class for parsing a field declarator.
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition Pragma.h:65
Tracks expected type during expression parsing, for use in code completion.
Definition Sema.h:297
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void startOpenMPLoop()
If the current region is a loop-based region, mark the start of the loop construct.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
SemaOpenMP & OpenMP()
Definition Sema.h:1571
ProcessingContextState ParsingClassState
Definition Sema.h:6738
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:10101
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:10110
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:3900
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:610
TentativeCXXTypeIdContext
Specifies the context in which type-id/expression disambiguation will occur.
Definition Parser.h:147
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
const FunctionProtoType * T
ParsedTemplateKind
The kind of template we are parsing.
Definition Parser.h:77
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ ExplicitSpecialization
We are parsing an explicit specialization.
Definition Parser.h:83
@ ExplicitInstantiation
We are parsing an explicit instantiation.
Definition Parser.h:85
@ NonTemplate
We are not parsing a template at all.
Definition Parser.h:79
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
CachedInitKind
Definition Parser.h:88
ObjCTypeQual
Definition Parser.h:91
TagUseKind
Definition Sema.h:445
ExtraSemiKind
The kind of extra semi diagnostic to emit.
Definition Parser.h:69
@ AfterMemberFunctionDefinition
Definition Parser.h:73
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
ConversionAction
@ CA_ToLiteralEncoding
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:8083
bool isActiveOrNested(Parser &P) const
Definition Parser.h:8091