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