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