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