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