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