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