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