xref: /llvm-project/clang/include/clang/Parse/Parser.h (revision e34cc7c99375c43e1698c78ec9150fa40c88d486)
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/SmallVector.h"
25 #include "llvm/Frontend/OpenMP/OMPContext.h"
26 #include "llvm/Support/SaveAndRestore.h"
27 #include <optional>
28 #include <stack>
29 
30 namespace clang {
31   class PragmaHandler;
32   class Scope;
33   class BalancedDelimiterTracker;
34   class CorrectionCandidateCallback;
35   class DeclGroupRef;
36   class DiagnosticBuilder;
37   struct LoopHint;
38   class Parser;
39   class ParsingDeclRAIIObject;
40   class ParsingDeclSpec;
41   class ParsingDeclarator;
42   class ParsingFieldDeclarator;
43   class ColonProtectionRAIIObject;
44   class InMessageExpressionRAIIObject;
45   class PoisonSEHIdentifiersRAIIObject;
46   class OMPClause;
47   class OpenACCClause;
48   class ObjCTypeParamList;
49   struct OMPTraitProperty;
50   struct OMPTraitSelector;
51   struct OMPTraitSet;
52   class OMPTraitInfo;
53 
54 /// Parser - This implements a parser for the C family of languages.  After
55 /// parsing units of the grammar, productions are invoked to handle whatever has
56 /// been read.
57 ///
58 class Parser : public CodeCompletionHandler {
59   friend class ColonProtectionRAIIObject;
60   friend class ParsingOpenMPDirectiveRAII;
61   friend class ParsingOpenACCDirectiveRAII;
62   friend class InMessageExpressionRAIIObject;
63   friend class OffsetOfStateRAIIObject;
64   friend class PoisonSEHIdentifiersRAIIObject;
65   friend class ObjCDeclContextSwitch;
66   friend class ParenBraceBracketBalancer;
67   friend class BalancedDelimiterTracker;
68 
69   Preprocessor &PP;
70 
71   /// Tok - The current token we are peeking ahead.  All parsing methods assume
72   /// that this is valid.
73   Token Tok;
74 
75   // PrevTokLocation - The location of the token we previously
76   // consumed. This token is used for diagnostics where we expected to
77   // see a token following another token (e.g., the ';' at the end of
78   // a statement).
79   SourceLocation PrevTokLocation;
80 
81   /// Tracks an expected type for the current token when parsing an expression.
82   /// Used by code completion for ranking.
83   PreferredTypeBuilder PreferredType;
84 
85   unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
86   unsigned short MisplacedModuleBeginCount = 0;
87 
88   /// Actions - These are the callbacks we invoke as we parse various constructs
89   /// in the file.
90   Sema &Actions;
91 
92   DiagnosticsEngine &Diags;
93 
94   /// ScopeCache - Cache scopes to reduce malloc traffic.
95   enum { ScopeCacheSize = 16 };
96   unsigned NumCachedScopes;
97   Scope *ScopeCache[ScopeCacheSize];
98 
99   /// Identifiers used for SEH handling in Borland. These are only
100   /// allowed in particular circumstances
101   // __except block
102   IdentifierInfo *Ident__exception_code,
103                  *Ident___exception_code,
104                  *Ident_GetExceptionCode;
105   // __except filter expression
106   IdentifierInfo *Ident__exception_info,
107                  *Ident___exception_info,
108                  *Ident_GetExceptionInfo;
109   // __finally
110   IdentifierInfo *Ident__abnormal_termination,
111                  *Ident___abnormal_termination,
112                  *Ident_AbnormalTermination;
113 
114   /// Contextual keywords for Microsoft extensions.
115   IdentifierInfo *Ident__except;
116   mutable IdentifierInfo *Ident_sealed;
117   mutable IdentifierInfo *Ident_abstract;
118 
119   /// Ident_super - IdentifierInfo for "super", to support fast
120   /// comparison.
121   IdentifierInfo *Ident_super;
122   /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
123   /// and "bool" fast comparison.  Only present if AltiVec or ZVector are
124   /// enabled.
125   IdentifierInfo *Ident_vector;
126   IdentifierInfo *Ident_bool;
127   IdentifierInfo *Ident_Bool;
128   /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
129   /// Only present if AltiVec enabled.
130   IdentifierInfo *Ident_pixel;
131 
132   /// Objective-C contextual keywords.
133   IdentifierInfo *Ident_instancetype;
134 
135   /// Identifier for "introduced".
136   IdentifierInfo *Ident_introduced;
137 
138   /// Identifier for "deprecated".
139   IdentifierInfo *Ident_deprecated;
140 
141   /// Identifier for "obsoleted".
142   IdentifierInfo *Ident_obsoleted;
143 
144   /// Identifier for "unavailable".
145   IdentifierInfo *Ident_unavailable;
146 
147   /// Identifier for "message".
148   IdentifierInfo *Ident_message;
149 
150   /// Identifier for "strict".
151   IdentifierInfo *Ident_strict;
152 
153   /// Identifier for "replacement".
154   IdentifierInfo *Ident_replacement;
155 
156   /// Identifier for "environment".
157   IdentifierInfo *Ident_environment;
158 
159   /// Identifiers used by the 'external_source_symbol' attribute.
160   IdentifierInfo *Ident_language, *Ident_defined_in,
161       *Ident_generated_declaration, *Ident_USR;
162 
163   /// C++11 contextual keywords.
164   mutable IdentifierInfo *Ident_final;
165   mutable IdentifierInfo *Ident_GNU_final;
166   mutable IdentifierInfo *Ident_override;
167 
168   // C++2a contextual keywords.
169   mutable IdentifierInfo *Ident_import;
170   mutable IdentifierInfo *Ident_module;
171 
172   // C++ type trait keywords that can be reverted to identifiers and still be
173   // used as type traits.
174   llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
175 
176   std::unique_ptr<PragmaHandler> AlignHandler;
177   std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
178   std::unique_ptr<PragmaHandler> OptionsHandler;
179   std::unique_ptr<PragmaHandler> PackHandler;
180   std::unique_ptr<PragmaHandler> MSStructHandler;
181   std::unique_ptr<PragmaHandler> UnusedHandler;
182   std::unique_ptr<PragmaHandler> WeakHandler;
183   std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
184   std::unique_ptr<PragmaHandler> FPContractHandler;
185   std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
186   std::unique_ptr<PragmaHandler> OpenMPHandler;
187   std::unique_ptr<PragmaHandler> OpenACCHandler;
188   std::unique_ptr<PragmaHandler> PCSectionHandler;
189   std::unique_ptr<PragmaHandler> MSCommentHandler;
190   std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
191   std::unique_ptr<PragmaHandler> FPEvalMethodHandler;
192   std::unique_ptr<PragmaHandler> FloatControlHandler;
193   std::unique_ptr<PragmaHandler> MSPointersToMembers;
194   std::unique_ptr<PragmaHandler> MSVtorDisp;
195   std::unique_ptr<PragmaHandler> MSInitSeg;
196   std::unique_ptr<PragmaHandler> MSDataSeg;
197   std::unique_ptr<PragmaHandler> MSBSSSeg;
198   std::unique_ptr<PragmaHandler> MSConstSeg;
199   std::unique_ptr<PragmaHandler> MSCodeSeg;
200   std::unique_ptr<PragmaHandler> MSSection;
201   std::unique_ptr<PragmaHandler> MSStrictGuardStackCheck;
202   std::unique_ptr<PragmaHandler> MSRuntimeChecks;
203   std::unique_ptr<PragmaHandler> MSIntrinsic;
204   std::unique_ptr<PragmaHandler> MSFunction;
205   std::unique_ptr<PragmaHandler> MSOptimize;
206   std::unique_ptr<PragmaHandler> MSFenvAccess;
207   std::unique_ptr<PragmaHandler> MSAllocText;
208   std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
209   std::unique_ptr<PragmaHandler> OptimizeHandler;
210   std::unique_ptr<PragmaHandler> LoopHintHandler;
211   std::unique_ptr<PragmaHandler> UnrollHintHandler;
212   std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
213   std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
214   std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
215   std::unique_ptr<PragmaHandler> FPHandler;
216   std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
217   std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
218   std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
219   std::unique_ptr<PragmaHandler> STDCUnknownHandler;
220   std::unique_ptr<PragmaHandler> AttributePragmaHandler;
221   std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
222   std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
223   std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
224 
225   std::unique_ptr<CommentHandler> CommentSemaHandler;
226 
227   /// Whether the '>' token acts as an operator or not. This will be
228   /// true except when we are parsing an expression within a C++
229   /// template argument list, where the '>' closes the template
230   /// argument list.
231   bool GreaterThanIsOperator;
232 
233   /// ColonIsSacred - When this is false, we aggressively try to recover from
234   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
235   /// safe in case statements and a few other things.  This is managed by the
236   /// ColonProtectionRAIIObject RAII object.
237   bool ColonIsSacred;
238 
239   /// Parsing OpenMP directive mode.
240   bool OpenMPDirectiveParsing = false;
241 
242   /// Parsing OpenACC directive mode.
243   bool OpenACCDirectiveParsing = false;
244 
245   /// Currently parsing a situation where an OpenACC array section could be
246   /// legal, such as a 'var-list'.
247   bool AllowOpenACCArraySections = false;
248 
249   /// RAII object to set reset OpenACC parsing a context where Array Sections
250   /// are allowed.
251   class OpenACCArraySectionRAII {
252     Parser &P;
253 
254   public:
255     OpenACCArraySectionRAII(Parser &P) : P(P) {
256       assert(!P.AllowOpenACCArraySections);
257       P.AllowOpenACCArraySections = true;
258     }
259     ~OpenACCArraySectionRAII() {
260       assert(P.AllowOpenACCArraySections);
261       P.AllowOpenACCArraySections = false;
262     }
263   };
264 
265   /// When true, we are directly inside an Objective-C message
266   /// send expression.
267   ///
268   /// This is managed by the \c InMessageExpressionRAIIObject class, and
269   /// should not be set directly.
270   bool InMessageExpression;
271 
272   /// Gets set to true after calling ProduceSignatureHelp, it is for a
273   /// workaround to make sure ProduceSignatureHelp is only called at the deepest
274   /// function call.
275   bool CalledSignatureHelp = false;
276 
277   Sema::OffsetOfKind OffsetOfState = Sema::OffsetOfKind::OOK_Outside;
278 
279   /// The "depth" of the template parameters currently being parsed.
280   unsigned TemplateParameterDepth;
281 
282   /// Current kind of OpenMP clause
283   OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
284 
285   /// RAII class that manages the template parameter depth.
286   class TemplateParameterDepthRAII {
287     unsigned &Depth;
288     unsigned AddedLevels;
289   public:
290     explicit TemplateParameterDepthRAII(unsigned &Depth)
291       : Depth(Depth), AddedLevels(0) {}
292 
293     ~TemplateParameterDepthRAII() {
294       Depth -= AddedLevels;
295     }
296 
297     void operator++() {
298       ++Depth;
299       ++AddedLevels;
300     }
301     void addDepth(unsigned D) {
302       Depth += D;
303       AddedLevels += D;
304     }
305     void setAddedDepth(unsigned D) {
306       Depth = Depth - AddedLevels + D;
307       AddedLevels = D;
308     }
309 
310     unsigned getDepth() const { return Depth; }
311     unsigned getOriginalDepth() const { return Depth - AddedLevels; }
312   };
313 
314   /// Factory object for creating ParsedAttr objects.
315   AttributeFactory AttrFactory;
316 
317   /// Gathers and cleans up TemplateIdAnnotations when parsing of a
318   /// top-level declaration is finished.
319   SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
320 
321   /// Don't destroy template annotations in MaybeDestroyTemplateIds even if
322   /// we're at the end of a declaration. Instead, we defer the destruction until
323   /// after a top-level declaration.
324   /// Use DelayTemplateIdDestructionRAII rather than setting it directly.
325   bool DelayTemplateIdDestruction = false;
326 
327   void MaybeDestroyTemplateIds() {
328     if (DelayTemplateIdDestruction)
329       return;
330     if (!TemplateIds.empty() &&
331         (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
332       DestroyTemplateIds();
333   }
334   void DestroyTemplateIds();
335 
336   /// RAII object to destroy TemplateIdAnnotations where possible, from a
337   /// likely-good position during parsing.
338   struct DestroyTemplateIdAnnotationsRAIIObj {
339     Parser &Self;
340 
341     DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
342     ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
343   };
344 
345   struct DelayTemplateIdDestructionRAII {
346     Parser &Self;
347     bool PrevDelayTemplateIdDestruction;
348 
349     DelayTemplateIdDestructionRAII(Parser &Self,
350                                    bool DelayTemplateIdDestruction) noexcept
351         : Self(Self),
352           PrevDelayTemplateIdDestruction(Self.DelayTemplateIdDestruction) {
353       Self.DelayTemplateIdDestruction = DelayTemplateIdDestruction;
354     }
355 
356     ~DelayTemplateIdDestructionRAII() noexcept {
357       Self.DelayTemplateIdDestruction = PrevDelayTemplateIdDestruction;
358     }
359   };
360 
361   /// Identifiers which have been declared within a tentative parse.
362   SmallVector<const IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
363 
364   /// Tracker for '<' tokens that might have been intended to be treated as an
365   /// angle bracket instead of a less-than comparison.
366   ///
367   /// This happens when the user intends to form a template-id, but typoes the
368   /// template-name or forgets a 'template' keyword for a dependent template
369   /// name.
370   ///
371   /// We track these locations from the point where we see a '<' with a
372   /// name-like expression on its left until we see a '>' or '>>' that might
373   /// match it.
374   struct AngleBracketTracker {
375     /// Flags used to rank candidate template names when there is more than one
376     /// '<' in a scope.
377     enum Priority : unsigned short {
378       /// A non-dependent name that is a potential typo for a template name.
379       PotentialTypo = 0x0,
380       /// A dependent name that might instantiate to a template-name.
381       DependentName = 0x2,
382 
383       /// A space appears before the '<' token.
384       SpaceBeforeLess = 0x0,
385       /// No space before the '<' token
386       NoSpaceBeforeLess = 0x1,
387 
388       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
389     };
390 
391     struct Loc {
392       Expr *TemplateName;
393       SourceLocation LessLoc;
394       AngleBracketTracker::Priority Priority;
395       unsigned short ParenCount, BracketCount, BraceCount;
396 
397       bool isActive(Parser &P) const {
398         return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
399                P.BraceCount == BraceCount;
400       }
401 
402       bool isActiveOrNested(Parser &P) const {
403         return isActive(P) || P.ParenCount > ParenCount ||
404                P.BracketCount > BracketCount || P.BraceCount > BraceCount;
405       }
406     };
407 
408     SmallVector<Loc, 8> Locs;
409 
410     /// Add an expression that might have been intended to be a template name.
411     /// In the case of ambiguity, we arbitrarily select the innermost such
412     /// expression, for example in 'foo < bar < baz', 'bar' is the current
413     /// candidate. No attempt is made to track that 'foo' is also a candidate
414     /// for the case where we see a second suspicious '>' token.
415     void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
416              Priority Prio) {
417       if (!Locs.empty() && Locs.back().isActive(P)) {
418         if (Locs.back().Priority <= Prio) {
419           Locs.back().TemplateName = TemplateName;
420           Locs.back().LessLoc = LessLoc;
421           Locs.back().Priority = Prio;
422         }
423       } else {
424         Locs.push_back({TemplateName, LessLoc, Prio,
425                         P.ParenCount, P.BracketCount, P.BraceCount});
426       }
427     }
428 
429     /// Mark the current potential missing template location as having been
430     /// handled (this happens if we pass a "corresponding" '>' or '>>' token
431     /// or leave a bracket scope).
432     void clear(Parser &P) {
433       while (!Locs.empty() && Locs.back().isActiveOrNested(P))
434         Locs.pop_back();
435     }
436 
437     /// Get the current enclosing expression that might hve been intended to be
438     /// a template name.
439     Loc *getCurrent(Parser &P) {
440       if (!Locs.empty() && Locs.back().isActive(P))
441         return &Locs.back();
442       return nullptr;
443     }
444   };
445 
446   AngleBracketTracker AngleBrackets;
447 
448   IdentifierInfo *getSEHExceptKeyword();
449 
450   /// True if we are within an Objective-C container while parsing C-like decls.
451   ///
452   /// This is necessary because Sema thinks we have left the container
453   /// to parse the C-like decls, meaning Actions.ObjC().getObjCDeclContext()
454   /// will be NULL.
455   bool ParsingInObjCContainer;
456 
457   /// Whether to skip parsing of function bodies.
458   ///
459   /// This option can be used, for example, to speed up searches for
460   /// declarations/definitions when indexing.
461   bool SkipFunctionBodies;
462 
463   /// The location of the expression statement that is being parsed right now.
464   /// Used to determine if an expression that is being parsed is a statement or
465   /// just a regular sub-expression.
466   SourceLocation ExprStatementTokLoc;
467 
468   /// Flags describing a context in which we're parsing a statement.
469   enum class ParsedStmtContext {
470     /// This context permits declarations in language modes where declarations
471     /// are not statements.
472     AllowDeclarationsInC = 0x1,
473     /// This context permits standalone OpenMP directives.
474     AllowStandaloneOpenMPDirectives = 0x2,
475     /// This context is at the top level of a GNU statement expression.
476     InStmtExpr = 0x4,
477 
478     /// The context of a regular substatement.
479     SubStmt = 0,
480     /// The context of a compound-statement.
481     Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
482 
483     LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
484   };
485 
486   /// Act on an expression statement that might be the last statement in a
487   /// GNU statement expression. Checks whether we are actually at the end of
488   /// a statement expression and builds a suitable expression statement.
489   StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
490 
491 public:
492   Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
493   ~Parser() override;
494 
495   const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
496   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
497   Preprocessor &getPreprocessor() const { return PP; }
498   Sema &getActions() const { return Actions; }
499   AttributeFactory &getAttrFactory() { return AttrFactory; }
500 
501   const Token &getCurToken() const { return Tok; }
502   Scope *getCurScope() const { return Actions.getCurScope(); }
503   void incrementMSManglingNumber() const {
504     return Actions.incrementMSManglingNumber();
505   }
506 
507   ObjCContainerDecl *getObjCDeclContext() const {
508     return Actions.ObjC().getObjCDeclContext();
509   }
510 
511   // Type forwarding.  All of these are statically 'void*', but they may all be
512   // different actual classes based on the actions in place.
513   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
514   typedef OpaquePtr<TemplateName> TemplateTy;
515 
516   typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
517 
518   typedef Sema::FullExprArg FullExprArg;
519 
520   /// A SmallVector of statements.
521   typedef SmallVector<Stmt *, 32> StmtVector;
522 
523   // Parsing methods.
524 
525   /// Initialize - Warm up the parser.
526   ///
527   void Initialize();
528 
529   /// Parse the first top-level declaration in a translation unit.
530   bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
531                               Sema::ModuleImportState &ImportState);
532 
533   /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
534   /// the EOF was encountered.
535   bool ParseTopLevelDecl(DeclGroupPtrTy &Result,
536                          Sema::ModuleImportState &ImportState);
537   bool ParseTopLevelDecl() {
538     DeclGroupPtrTy Result;
539     Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
540     return ParseTopLevelDecl(Result, IS);
541   }
542 
543   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
544   /// This does not work with special tokens: string literals, code completion,
545   /// annotation tokens and balanced tokens must be handled using the specific
546   /// consume methods.
547   /// Returns the location of the consumed token.
548   SourceLocation ConsumeToken() {
549     assert(!isTokenSpecial() &&
550            "Should consume special tokens with Consume*Token");
551     PrevTokLocation = Tok.getLocation();
552     PP.Lex(Tok);
553     return PrevTokLocation;
554   }
555 
556   bool TryConsumeToken(tok::TokenKind Expected) {
557     if (Tok.isNot(Expected))
558       return false;
559     assert(!isTokenSpecial() &&
560            "Should consume special tokens with Consume*Token");
561     PrevTokLocation = Tok.getLocation();
562     PP.Lex(Tok);
563     return true;
564   }
565 
566   bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
567     if (!TryConsumeToken(Expected))
568       return false;
569     Loc = PrevTokLocation;
570     return true;
571   }
572 
573   /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
574   /// current token type.  This should only be used in cases where the type of
575   /// the token really isn't known, e.g. in error recovery.
576   SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
577     if (isTokenParen())
578       return ConsumeParen();
579     if (isTokenBracket())
580       return ConsumeBracket();
581     if (isTokenBrace())
582       return ConsumeBrace();
583     if (isTokenStringLiteral())
584       return ConsumeStringToken();
585     if (Tok.is(tok::code_completion))
586       return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
587                                       : handleUnexpectedCodeCompletionToken();
588     if (Tok.isAnnotation())
589       return ConsumeAnnotationToken();
590     return ConsumeToken();
591   }
592 
593 
594   SourceLocation getEndOfPreviousToken() {
595     return PP.getLocForEndOfToken(PrevTokLocation);
596   }
597 
598   /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
599   /// to the given nullability kind.
600   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
601     return Actions.getNullabilityKeyword(nullability);
602   }
603 
604 private:
605   //===--------------------------------------------------------------------===//
606   // Low-Level token peeking and consumption methods.
607   //
608 
609   /// isTokenParen - Return true if the cur token is '(' or ')'.
610   bool isTokenParen() const {
611     return Tok.isOneOf(tok::l_paren, tok::r_paren);
612   }
613   /// isTokenBracket - Return true if the cur token is '[' or ']'.
614   bool isTokenBracket() const {
615     return Tok.isOneOf(tok::l_square, tok::r_square);
616   }
617   /// isTokenBrace - Return true if the cur token is '{' or '}'.
618   bool isTokenBrace() const {
619     return Tok.isOneOf(tok::l_brace, tok::r_brace);
620   }
621   /// isTokenStringLiteral - True if this token is a string-literal.
622   bool isTokenStringLiteral() const {
623     return tok::isStringLiteral(Tok.getKind());
624   }
625   /// isTokenSpecial - True if this token requires special consumption methods.
626   bool isTokenSpecial() const {
627     return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
628            isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
629   }
630 
631   /// Returns true if the current token is '=' or is a type of '='.
632   /// For typos, give a fixit to '='
633   bool isTokenEqualOrEqualTypo();
634 
635   /// Return the current token to the token stream and make the given
636   /// token the current token.
637   void UnconsumeToken(Token &Consumed) {
638       Token Next = Tok;
639       PP.EnterToken(Consumed, /*IsReinject*/true);
640       PP.Lex(Tok);
641       PP.EnterToken(Next, /*IsReinject*/true);
642   }
643 
644   SourceLocation ConsumeAnnotationToken() {
645     assert(Tok.isAnnotation() && "wrong consume method");
646     SourceLocation Loc = Tok.getLocation();
647     PrevTokLocation = Tok.getAnnotationEndLoc();
648     PP.Lex(Tok);
649     return Loc;
650   }
651 
652   /// ConsumeParen - This consume method keeps the paren count up-to-date.
653   ///
654   SourceLocation ConsumeParen() {
655     assert(isTokenParen() && "wrong consume method");
656     if (Tok.getKind() == tok::l_paren)
657       ++ParenCount;
658     else if (ParenCount) {
659       AngleBrackets.clear(*this);
660       --ParenCount;       // Don't let unbalanced )'s drive the count negative.
661     }
662     PrevTokLocation = Tok.getLocation();
663     PP.Lex(Tok);
664     return PrevTokLocation;
665   }
666 
667   /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
668   ///
669   SourceLocation ConsumeBracket() {
670     assert(isTokenBracket() && "wrong consume method");
671     if (Tok.getKind() == tok::l_square)
672       ++BracketCount;
673     else if (BracketCount) {
674       AngleBrackets.clear(*this);
675       --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
676     }
677 
678     PrevTokLocation = Tok.getLocation();
679     PP.Lex(Tok);
680     return PrevTokLocation;
681   }
682 
683   /// ConsumeBrace - This consume method keeps the brace count up-to-date.
684   ///
685   SourceLocation ConsumeBrace() {
686     assert(isTokenBrace() && "wrong consume method");
687     if (Tok.getKind() == tok::l_brace)
688       ++BraceCount;
689     else if (BraceCount) {
690       AngleBrackets.clear(*this);
691       --BraceCount;     // Don't let unbalanced }'s drive the count negative.
692     }
693 
694     PrevTokLocation = Tok.getLocation();
695     PP.Lex(Tok);
696     return PrevTokLocation;
697   }
698 
699   /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
700   /// and returning the token kind.  This method is specific to strings, as it
701   /// handles string literal concatenation, as per C99 5.1.1.2, translation
702   /// phase #6.
703   SourceLocation ConsumeStringToken() {
704     assert(isTokenStringLiteral() &&
705            "Should only consume string literals with this method");
706     PrevTokLocation = Tok.getLocation();
707     PP.Lex(Tok);
708     return PrevTokLocation;
709   }
710 
711   /// Consume the current code-completion token.
712   ///
713   /// This routine can be called to consume the code-completion token and
714   /// continue processing in special cases where \c cutOffParsing() isn't
715   /// desired, such as token caching or completion with lookahead.
716   SourceLocation ConsumeCodeCompletionToken() {
717     assert(Tok.is(tok::code_completion));
718     PrevTokLocation = Tok.getLocation();
719     PP.Lex(Tok);
720     return PrevTokLocation;
721   }
722 
723   /// When we are consuming a code-completion token without having matched
724   /// specific position in the grammar, provide code-completion results based
725   /// on context.
726   ///
727   /// \returns the source location of the code-completion token.
728   SourceLocation handleUnexpectedCodeCompletionToken();
729 
730   /// Abruptly cut off parsing; mainly used when we have reached the
731   /// code-completion point.
732   void cutOffParsing() {
733     if (PP.isCodeCompletionEnabled())
734       PP.setCodeCompletionReached();
735     // Cut off parsing by acting as if we reached the end-of-file.
736     Tok.setKind(tok::eof);
737   }
738 
739   /// Determine if we're at the end of the file or at a transition
740   /// between modules.
741   bool isEofOrEom() {
742     tok::TokenKind Kind = Tok.getKind();
743     return Kind == tok::eof || Kind == tok::annot_module_begin ||
744            Kind == tok::annot_module_end || Kind == tok::annot_module_include ||
745            Kind == tok::annot_repl_input_end;
746   }
747 
748   /// Checks if the \p Level is valid for use in a fold expression.
749   bool isFoldOperator(prec::Level Level) const;
750 
751   /// Checks if the \p Kind is a valid operator for fold expressions.
752   bool isFoldOperator(tok::TokenKind Kind) const;
753 
754   /// Initialize all pragma handlers.
755   void initializePragmaHandlers();
756 
757   /// Destroy and reset all pragma handlers.
758   void resetPragmaHandlers();
759 
760   /// Handle the annotation token produced for #pragma unused(...)
761   void HandlePragmaUnused();
762 
763   /// Handle the annotation token produced for
764   /// #pragma GCC visibility...
765   void HandlePragmaVisibility();
766 
767   /// Handle the annotation token produced for
768   /// #pragma pack...
769   void HandlePragmaPack();
770 
771   /// Handle the annotation token produced for
772   /// #pragma ms_struct...
773   void HandlePragmaMSStruct();
774 
775   void HandlePragmaMSPointersToMembers();
776 
777   void HandlePragmaMSVtorDisp();
778 
779   void HandlePragmaMSPragma();
780   bool HandlePragmaMSSection(StringRef PragmaName,
781                              SourceLocation PragmaLocation);
782   bool HandlePragmaMSSegment(StringRef PragmaName,
783                              SourceLocation PragmaLocation);
784   bool HandlePragmaMSInitSeg(StringRef PragmaName,
785                              SourceLocation PragmaLocation);
786   bool HandlePragmaMSStrictGuardStackCheck(StringRef PragmaName,
787                                            SourceLocation PragmaLocation);
788   bool HandlePragmaMSFunction(StringRef PragmaName,
789                               SourceLocation PragmaLocation);
790   bool HandlePragmaMSAllocText(StringRef PragmaName,
791                                SourceLocation PragmaLocation);
792   bool HandlePragmaMSOptimize(StringRef PragmaName,
793                               SourceLocation PragmaLocation);
794 
795   /// Handle the annotation token produced for
796   /// #pragma align...
797   void HandlePragmaAlign();
798 
799   /// Handle the annotation token produced for
800   /// #pragma clang __debug dump...
801   void HandlePragmaDump();
802 
803   /// Handle the annotation token produced for
804   /// #pragma weak id...
805   void HandlePragmaWeak();
806 
807   /// Handle the annotation token produced for
808   /// #pragma weak id = id...
809   void HandlePragmaWeakAlias();
810 
811   /// Handle the annotation token produced for
812   /// #pragma redefine_extname...
813   void HandlePragmaRedefineExtname();
814 
815   /// Handle the annotation token produced for
816   /// #pragma STDC FP_CONTRACT...
817   void HandlePragmaFPContract();
818 
819   /// Handle the annotation token produced for
820   /// #pragma STDC FENV_ACCESS...
821   void HandlePragmaFEnvAccess();
822 
823   /// Handle the annotation token produced for
824   /// #pragma STDC FENV_ROUND...
825   void HandlePragmaFEnvRound();
826 
827   /// Handle the annotation token produced for
828   /// #pragma STDC CX_LIMITED_RANGE...
829   void HandlePragmaCXLimitedRange();
830 
831   /// Handle the annotation token produced for
832   /// #pragma float_control
833   void HandlePragmaFloatControl();
834 
835   /// \brief Handle the annotation token produced for
836   /// #pragma clang fp ...
837   void HandlePragmaFP();
838 
839   /// Handle the annotation token produced for
840   /// #pragma OPENCL EXTENSION...
841   void HandlePragmaOpenCLExtension();
842 
843   /// Handle the annotation token produced for
844   /// #pragma clang __debug captured
845   StmtResult HandlePragmaCaptured();
846 
847   /// Handle the annotation token produced for
848   /// #pragma clang loop and #pragma unroll.
849   bool HandlePragmaLoopHint(LoopHint &Hint);
850 
851   bool ParsePragmaAttributeSubjectMatchRuleSet(
852       attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
853       SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
854 
855   void HandlePragmaAttribute();
856 
857   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
858   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
859   /// returns the token after Tok, etc.
860   ///
861   /// Note that this differs from the Preprocessor's LookAhead method, because
862   /// the Parser always has one token lexed that the preprocessor doesn't.
863   ///
864   const Token &GetLookAheadToken(unsigned N) {
865     if (N == 0 || Tok.is(tok::eof)) return Tok;
866     return PP.LookAhead(N-1);
867   }
868 
869 public:
870   /// NextToken - This peeks ahead one token and returns it without
871   /// consuming it.
872   const Token &NextToken() {
873     return PP.LookAhead(0);
874   }
875 
876   /// getTypeAnnotation - Read a parsed type out of an annotation token.
877   static TypeResult getTypeAnnotation(const Token &Tok) {
878     if (!Tok.getAnnotationValue())
879       return TypeError();
880     return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
881   }
882 
883 private:
884   static void setTypeAnnotation(Token &Tok, TypeResult T) {
885     assert((T.isInvalid() || T.get()) &&
886            "produced a valid-but-null type annotation?");
887     Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
888   }
889 
890   static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
891     return static_cast<NamedDecl*>(Tok.getAnnotationValue());
892   }
893 
894   static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
895     Tok.setAnnotationValue(ND);
896   }
897 
898   static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
899     return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
900   }
901 
902   static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
903     Tok.setAnnotationValue(ND);
904   }
905 
906   /// Read an already-translated primary expression out of an annotation
907   /// token.
908   static ExprResult getExprAnnotation(const Token &Tok) {
909     return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
910   }
911 
912   /// Set the primary expression corresponding to the given annotation
913   /// token.
914   static void setExprAnnotation(Token &Tok, ExprResult ER) {
915     Tok.setAnnotationValue(ER.getAsOpaquePointer());
916   }
917 
918 public:
919   // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
920   // find a type name by attempting typo correction.
921   bool
922   TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename =
923                                   ImplicitTypenameContext::No);
924   bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(
925       CXXScopeSpec &SS, bool IsNewScope,
926       ImplicitTypenameContext AllowImplicitTypename);
927   bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
928 
929   bool MightBeCXXScopeToken() {
930     return getLangOpts().CPlusPlus &&
931            (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
932             (Tok.is(tok::annot_template_id) &&
933              NextToken().is(tok::coloncolon)) ||
934             Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super));
935   }
936   bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
937     return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
938   }
939 
940 private:
941   enum AnnotatedNameKind {
942     /// Annotation has failed and emitted an error.
943     ANK_Error,
944     /// The identifier is a tentatively-declared name.
945     ANK_TentativeDecl,
946     /// The identifier is a template name. FIXME: Add an annotation for that.
947     ANK_TemplateName,
948     /// The identifier can't be resolved.
949     ANK_Unresolved,
950     /// Annotation was successful.
951     ANK_Success
952   };
953 
954   AnnotatedNameKind
955   TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr,
956                   ImplicitTypenameContext AllowImplicitTypename =
957                       ImplicitTypenameContext::No);
958 
959   /// Push a tok::annot_cxxscope token onto the token stream.
960   void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
961 
962   /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
963   /// replacing them with the non-context-sensitive keywords.  This returns
964   /// true if the token was replaced.
965   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
966                        const char *&PrevSpec, unsigned &DiagID,
967                        bool &isInvalid) {
968     if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
969       return false;
970 
971     if (Tok.getIdentifierInfo() != Ident_vector &&
972         Tok.getIdentifierInfo() != Ident_bool &&
973         Tok.getIdentifierInfo() != Ident_Bool &&
974         (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
975       return false;
976 
977     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
978   }
979 
980   /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
981   /// identifier token, replacing it with the non-context-sensitive __vector.
982   /// This returns true if the token was replaced.
983   bool TryAltiVecVectorToken() {
984     if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
985         Tok.getIdentifierInfo() != Ident_vector) return false;
986     return TryAltiVecVectorTokenOutOfLine();
987   }
988 
989   bool TryAltiVecVectorTokenOutOfLine();
990   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
991                                 const char *&PrevSpec, unsigned &DiagID,
992                                 bool &isInvalid);
993 
994   /// Returns true if the current token is the identifier 'instancetype'.
995   ///
996   /// Should only be used in Objective-C language modes.
997   bool isObjCInstancetype() {
998     assert(getLangOpts().ObjC);
999     if (Tok.isAnnotation())
1000       return false;
1001     if (!Ident_instancetype)
1002       Ident_instancetype = PP.getIdentifierInfo("instancetype");
1003     return Tok.getIdentifierInfo() == Ident_instancetype;
1004   }
1005 
1006   /// TryKeywordIdentFallback - For compatibility with system headers using
1007   /// keywords as identifiers, attempt to convert the current token to an
1008   /// identifier and optionally disable the keyword for the remainder of the
1009   /// translation unit. This returns false if the token was not replaced,
1010   /// otherwise emits a diagnostic and returns true.
1011   bool TryKeywordIdentFallback(bool DisableKeyword);
1012 
1013   /// Get the TemplateIdAnnotation from the token.
1014   TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
1015 
1016   /// TentativeParsingAction - An object that is used as a kind of "tentative
1017   /// parsing transaction". It gets instantiated to mark the token position and
1018   /// after the token consumption is done, Commit() or Revert() is called to
1019   /// either "commit the consumed tokens" or revert to the previously marked
1020   /// token position. Example:
1021   ///
1022   ///   TentativeParsingAction TPA(*this);
1023   ///   ConsumeToken();
1024   ///   ....
1025   ///   TPA.Revert();
1026   ///
1027   /// If the Unannotated parameter is true, any token annotations created
1028   /// during the tentative parse are reverted.
1029   class TentativeParsingAction {
1030     Parser &P;
1031     PreferredTypeBuilder PrevPreferredType;
1032     Token PrevTok;
1033     size_t PrevTentativelyDeclaredIdentifierCount;
1034     unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
1035     bool isActive;
1036 
1037   public:
1038     explicit TentativeParsingAction(Parser &p, bool Unannotated = false)
1039         : P(p), PrevPreferredType(P.PreferredType) {
1040       PrevTok = P.Tok;
1041       PrevTentativelyDeclaredIdentifierCount =
1042           P.TentativelyDeclaredIdentifiers.size();
1043       PrevParenCount = P.ParenCount;
1044       PrevBracketCount = P.BracketCount;
1045       PrevBraceCount = P.BraceCount;
1046       P.PP.EnableBacktrackAtThisPos(Unannotated);
1047       isActive = true;
1048     }
1049     void Commit() {
1050       assert(isActive && "Parsing action was finished!");
1051       P.TentativelyDeclaredIdentifiers.resize(
1052           PrevTentativelyDeclaredIdentifierCount);
1053       P.PP.CommitBacktrackedTokens();
1054       isActive = false;
1055     }
1056     void Revert() {
1057       assert(isActive && "Parsing action was finished!");
1058       P.PP.Backtrack();
1059       P.PreferredType = PrevPreferredType;
1060       P.Tok = PrevTok;
1061       P.TentativelyDeclaredIdentifiers.resize(
1062           PrevTentativelyDeclaredIdentifierCount);
1063       P.ParenCount = PrevParenCount;
1064       P.BracketCount = PrevBracketCount;
1065       P.BraceCount = PrevBraceCount;
1066       isActive = false;
1067     }
1068     ~TentativeParsingAction() {
1069       assert(!isActive && "Forgot to call Commit or Revert!");
1070     }
1071   };
1072   /// A TentativeParsingAction that automatically reverts in its destructor.
1073   /// Useful for disambiguation parses that will always be reverted.
1074   class RevertingTentativeParsingAction
1075       : private Parser::TentativeParsingAction {
1076   public:
1077     using TentativeParsingAction::TentativeParsingAction;
1078 
1079     ~RevertingTentativeParsingAction() { Revert(); }
1080   };
1081 
1082   /// ObjCDeclContextSwitch - An object used to switch context from
1083   /// an objective-c decl context to its enclosing decl context and
1084   /// back.
1085   class ObjCDeclContextSwitch {
1086     Parser &P;
1087     ObjCContainerDecl *DC;
1088     SaveAndRestore<bool> WithinObjCContainer;
1089   public:
1090     explicit ObjCDeclContextSwitch(Parser &p)
1091       : P(p), DC(p.getObjCDeclContext()),
1092         WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
1093       if (DC)
1094         P.Actions.ObjC().ActOnObjCTemporaryExitContainerContext(DC);
1095     }
1096     ~ObjCDeclContextSwitch() {
1097       if (DC)
1098         P.Actions.ObjC().ActOnObjCReenterContainerContext(DC);
1099     }
1100   };
1101 
1102   /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
1103   /// input.  If so, it is consumed and false is returned.
1104   ///
1105   /// If a trivial punctuator misspelling is encountered, a FixIt error
1106   /// diagnostic is issued and false is returned after recovery.
1107   ///
1108   /// If the input is malformed, this emits the specified diagnostic and true is
1109   /// returned.
1110   bool ExpectAndConsume(tok::TokenKind ExpectedTok,
1111                         unsigned Diag = diag::err_expected,
1112                         StringRef DiagMsg = "");
1113 
1114   /// The parser expects a semicolon and, if present, will consume it.
1115   ///
1116   /// If the next token is not a semicolon, this emits the specified diagnostic,
1117   /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
1118   /// to the semicolon, consumes that extra token.
1119   bool ExpectAndConsumeSemi(unsigned DiagID , StringRef TokenUsed = "");
1120 
1121   /// The kind of extra semi diagnostic to emit.
1122   enum ExtraSemiKind {
1123     OutsideFunction = 0,
1124     InsideStruct = 1,
1125     InstanceVariableList = 2,
1126     AfterMemberFunctionDefinition = 3
1127   };
1128 
1129   /// Consume any extra semi-colons until the end of the line.
1130   void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
1131 
1132   /// Return false if the next token is an identifier. An 'expected identifier'
1133   /// error is emitted otherwise.
1134   ///
1135   /// The parser tries to recover from the error by checking if the next token
1136   /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
1137   /// was successful.
1138   bool expectIdentifier();
1139 
1140   /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
1141   enum class CompoundToken {
1142     /// A '(' '{' beginning a statement-expression.
1143     StmtExprBegin,
1144     /// A '}' ')' ending a statement-expression.
1145     StmtExprEnd,
1146     /// A '[' '[' beginning a C++11 or C23 attribute.
1147     AttrBegin,
1148     /// A ']' ']' ending a C++11 or C23 attribute.
1149     AttrEnd,
1150     /// A '::' '*' forming a C++ pointer-to-member declaration.
1151     MemberPtr,
1152   };
1153 
1154   /// Check that a compound operator was written in a "sensible" way, and warn
1155   /// if not.
1156   void checkCompoundToken(SourceLocation FirstTokLoc,
1157                           tok::TokenKind FirstTokKind, CompoundToken Op);
1158 
1159   void diagnoseUseOfC11Keyword(const Token &Tok);
1160 
1161 public:
1162   //===--------------------------------------------------------------------===//
1163   // Scope manipulation
1164 
1165   /// ParseScope - Introduces a new scope for parsing. The kind of
1166   /// scope is determined by ScopeFlags. Objects of this type should
1167   /// be created on the stack to coincide with the position where the
1168   /// parser enters the new scope, and this object's constructor will
1169   /// create that new scope. Similarly, once the object is destroyed
1170   /// the parser will exit the scope.
1171   class ParseScope {
1172     Parser *Self;
1173     ParseScope(const ParseScope &) = delete;
1174     void operator=(const ParseScope &) = delete;
1175 
1176   public:
1177     // ParseScope - Construct a new object to manage a scope in the
1178     // parser Self where the new Scope is created with the flags
1179     // ScopeFlags, but only when we aren't about to enter a compound statement.
1180     ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
1181                bool BeforeCompoundStmt = false)
1182       : Self(Self) {
1183       if (EnteredScope && !BeforeCompoundStmt)
1184         Self->EnterScope(ScopeFlags);
1185       else {
1186         if (BeforeCompoundStmt)
1187           Self->incrementMSManglingNumber();
1188 
1189         this->Self = nullptr;
1190       }
1191     }
1192 
1193     // Exit - Exit the scope associated with this object now, rather
1194     // than waiting until the object is destroyed.
1195     void Exit() {
1196       if (Self) {
1197         Self->ExitScope();
1198         Self = nullptr;
1199       }
1200     }
1201 
1202     ~ParseScope() {
1203       Exit();
1204     }
1205   };
1206 
1207   /// Introduces zero or more scopes for parsing. The scopes will all be exited
1208   /// when the object is destroyed.
1209   class MultiParseScope {
1210     Parser &Self;
1211     unsigned NumScopes = 0;
1212 
1213     MultiParseScope(const MultiParseScope&) = delete;
1214 
1215   public:
1216     MultiParseScope(Parser &Self) : Self(Self) {}
1217     void Enter(unsigned ScopeFlags) {
1218       Self.EnterScope(ScopeFlags);
1219       ++NumScopes;
1220     }
1221     void Exit() {
1222       while (NumScopes) {
1223         Self.ExitScope();
1224         --NumScopes;
1225       }
1226     }
1227     ~MultiParseScope() {
1228       Exit();
1229     }
1230   };
1231 
1232   /// EnterScope - Start a new scope.
1233   void EnterScope(unsigned ScopeFlags);
1234 
1235   /// ExitScope - Pop a scope off the scope stack.
1236   void ExitScope();
1237 
1238   /// Re-enter the template scopes for a declaration that might be a template.
1239   unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
1240 
1241 private:
1242   /// RAII object used to modify the scope flags for the current scope.
1243   class ParseScopeFlags {
1244     Scope *CurScope;
1245     unsigned OldFlags = 0;
1246     ParseScopeFlags(const ParseScopeFlags &) = delete;
1247     void operator=(const ParseScopeFlags &) = delete;
1248 
1249   public:
1250     ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
1251     ~ParseScopeFlags();
1252   };
1253 
1254   //===--------------------------------------------------------------------===//
1255   // Diagnostic Emission and Error recovery.
1256 
1257 public:
1258   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1259   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
1260   DiagnosticBuilder Diag(unsigned DiagID) {
1261     return Diag(Tok, DiagID);
1262   }
1263 
1264 private:
1265   void SuggestParentheses(SourceLocation Loc, unsigned DK,
1266                           SourceRange ParenRange);
1267   void CheckNestedObjCContexts(SourceLocation AtLoc);
1268 
1269 public:
1270 
1271   /// Control flags for SkipUntil functions.
1272   enum SkipUntilFlags {
1273     StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
1274     /// Stop skipping at specified token, but don't skip the token itself
1275     StopBeforeMatch = 1 << 1,
1276     StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
1277   };
1278 
1279   friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
1280                                             SkipUntilFlags R) {
1281     return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
1282                                        static_cast<unsigned>(R));
1283   }
1284 
1285   /// SkipUntil - Read tokens until we get to the specified token, then consume
1286   /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
1287   /// that the token will ever occur, this skips to the next token, or to some
1288   /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
1289   /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
1290   /// skipping.
1291   ///
1292   /// If SkipUntil finds the specified token, it returns true, otherwise it
1293   /// returns false.
1294   bool SkipUntil(tok::TokenKind T,
1295                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1296     return SkipUntil(llvm::ArrayRef(T), Flags);
1297   }
1298   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
1299                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1300     tok::TokenKind TokArray[] = {T1, T2};
1301     return SkipUntil(TokArray, Flags);
1302   }
1303   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
1304                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1305     tok::TokenKind TokArray[] = {T1, T2, T3};
1306     return SkipUntil(TokArray, Flags);
1307   }
1308   bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
1309                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
1310 
1311   /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
1312   /// point for skipping past a simple-declaration.
1313   void SkipMalformedDecl();
1314 
1315   /// The location of the first statement inside an else that might
1316   /// have a missleading indentation. If there is no
1317   /// MisleadingIndentationChecker on an else active, this location is invalid.
1318   SourceLocation MisleadingIndentationElseLoc;
1319 
1320 private:
1321   //===--------------------------------------------------------------------===//
1322   // Lexing and parsing of C++ inline methods.
1323 
1324   struct ParsingClass;
1325 
1326   /// [class.mem]p1: "... the class is regarded as complete within
1327   /// - function bodies
1328   /// - default arguments
1329   /// - exception-specifications (TODO: C++0x)
1330   /// - and brace-or-equal-initializers for non-static data members
1331   /// (including such things in nested classes)."
1332   /// LateParsedDeclarations build the tree of those elements so they can
1333   /// be parsed after parsing the top-level class.
1334   class LateParsedDeclaration {
1335   public:
1336     virtual ~LateParsedDeclaration();
1337 
1338     virtual void ParseLexedMethodDeclarations();
1339     virtual void ParseLexedMemberInitializers();
1340     virtual void ParseLexedMethodDefs();
1341     virtual void ParseLexedAttributes();
1342     virtual void ParseLexedPragmas();
1343   };
1344 
1345   /// Inner node of the LateParsedDeclaration tree that parses
1346   /// all its members recursively.
1347   class LateParsedClass : public LateParsedDeclaration {
1348   public:
1349     LateParsedClass(Parser *P, ParsingClass *C);
1350     ~LateParsedClass() override;
1351 
1352     void ParseLexedMethodDeclarations() override;
1353     void ParseLexedMemberInitializers() override;
1354     void ParseLexedMethodDefs() override;
1355     void ParseLexedAttributes() override;
1356     void ParseLexedPragmas() override;
1357 
1358     // Delete copy constructor and copy assignment operator.
1359     LateParsedClass(const LateParsedClass &) = delete;
1360     LateParsedClass &operator=(const LateParsedClass &) = delete;
1361 
1362   private:
1363     Parser *Self;
1364     ParsingClass *Class;
1365   };
1366 
1367   /// Contains the lexed tokens of an attribute with arguments that
1368   /// may reference member variables and so need to be parsed at the
1369   /// end of the class declaration after parsing all other member
1370   /// member declarations.
1371   /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
1372   /// LateParsedTokens.
1373   struct LateParsedAttribute : public LateParsedDeclaration {
1374     Parser *Self;
1375     CachedTokens Toks;
1376     IdentifierInfo &AttrName;
1377     IdentifierInfo *MacroII = nullptr;
1378     SourceLocation AttrNameLoc;
1379     SmallVector<Decl*, 2> Decls;
1380 
1381     explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
1382                                  SourceLocation Loc)
1383       : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
1384 
1385     void ParseLexedAttributes() override;
1386 
1387     void addDecl(Decl *D) { Decls.push_back(D); }
1388   };
1389 
1390   /// Contains the lexed tokens of a pragma with arguments that
1391   /// may reference member variables and so need to be parsed at the
1392   /// end of the class declaration after parsing all other member
1393   /// member declarations.
1394   class LateParsedPragma : public LateParsedDeclaration {
1395     Parser *Self = nullptr;
1396     AccessSpecifier AS = AS_none;
1397     CachedTokens Toks;
1398 
1399   public:
1400     explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
1401         : Self(P), AS(AS) {}
1402 
1403     void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
1404     const CachedTokens &toks() const { return Toks; }
1405     AccessSpecifier getAccessSpecifier() const { return AS; }
1406 
1407     void ParseLexedPragmas() override;
1408   };
1409 
1410   // A list of late-parsed attributes.  Used by ParseGNUAttributes.
1411   class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
1412   public:
1413     LateParsedAttrList(bool PSoon = false,
1414                        bool LateAttrParseExperimentalExtOnly = false)
1415         : ParseSoon(PSoon),
1416           LateAttrParseExperimentalExtOnly(LateAttrParseExperimentalExtOnly) {}
1417 
1418     bool parseSoon() { return ParseSoon; }
1419     /// returns true iff the attribute to be parsed should only be late parsed
1420     /// if it is annotated with `LateAttrParseExperimentalExt`
1421     bool lateAttrParseExperimentalExtOnly() {
1422       return LateAttrParseExperimentalExtOnly;
1423     }
1424 
1425   private:
1426     bool ParseSoon; // Are we planning to parse these shortly after creation?
1427     bool LateAttrParseExperimentalExtOnly;
1428   };
1429 
1430   /// Contains the lexed tokens of a member function definition
1431   /// which needs to be parsed at the end of the class declaration
1432   /// after parsing all other member declarations.
1433   struct LexedMethod : public LateParsedDeclaration {
1434     Parser *Self;
1435     Decl *D;
1436     CachedTokens Toks;
1437 
1438     explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
1439 
1440     void ParseLexedMethodDefs() override;
1441   };
1442 
1443   /// LateParsedDefaultArgument - Keeps track of a parameter that may
1444   /// have a default argument that cannot be parsed yet because it
1445   /// occurs within a member function declaration inside the class
1446   /// (C++ [class.mem]p2).
1447   struct LateParsedDefaultArgument {
1448     explicit LateParsedDefaultArgument(Decl *P,
1449                                        std::unique_ptr<CachedTokens> Toks = nullptr)
1450       : Param(P), Toks(std::move(Toks)) { }
1451 
1452     /// Param - The parameter declaration for this parameter.
1453     Decl *Param;
1454 
1455     /// Toks - The sequence of tokens that comprises the default
1456     /// argument expression, not including the '=' or the terminating
1457     /// ')' or ','. This will be NULL for parameters that have no
1458     /// default argument.
1459     std::unique_ptr<CachedTokens> Toks;
1460   };
1461 
1462   /// LateParsedMethodDeclaration - A method declaration inside a class that
1463   /// contains at least one entity whose parsing needs to be delayed
1464   /// until the class itself is completely-defined, such as a default
1465   /// argument (C++ [class.mem]p2).
1466   struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1467     explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1468         : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
1469 
1470     void ParseLexedMethodDeclarations() override;
1471 
1472     Parser *Self;
1473 
1474     /// Method - The method declaration.
1475     Decl *Method;
1476 
1477     /// DefaultArgs - Contains the parameters of the function and
1478     /// their default arguments. At least one of the parameters will
1479     /// have a default argument, but all of the parameters of the
1480     /// method will be stored so that they can be reintroduced into
1481     /// scope at the appropriate times.
1482     SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1483 
1484     /// The set of tokens that make up an exception-specification that
1485     /// has not yet been parsed.
1486     CachedTokens *ExceptionSpecTokens;
1487   };
1488 
1489   /// LateParsedMemberInitializer - An initializer for a non-static class data
1490   /// member whose parsing must to be delayed until the class is completely
1491   /// defined (C++11 [class.mem]p2).
1492   struct LateParsedMemberInitializer : public LateParsedDeclaration {
1493     LateParsedMemberInitializer(Parser *P, Decl *FD)
1494       : Self(P), Field(FD) { }
1495 
1496     void ParseLexedMemberInitializers() override;
1497 
1498     Parser *Self;
1499 
1500     /// Field - The field declaration.
1501     Decl *Field;
1502 
1503     /// CachedTokens - The sequence of tokens that comprises the initializer,
1504     /// including any leading '='.
1505     CachedTokens Toks;
1506   };
1507 
1508   /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1509   /// C++ class, its method declarations that contain parts that won't be
1510   /// parsed until after the definition is completed (C++ [class.mem]p2),
1511   /// the method declarations and possibly attached inline definitions
1512   /// will be stored here with the tokens that will be parsed to create those
1513   /// entities.
1514   typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1515 
1516   /// Representation of a class that has been parsed, including
1517   /// any member function declarations or definitions that need to be
1518   /// parsed after the corresponding top-level class is complete.
1519   struct ParsingClass {
1520     ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1521         : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
1522           TagOrTemplate(TagOrTemplate) {}
1523 
1524     /// Whether this is a "top-level" class, meaning that it is
1525     /// not nested within another class.
1526     bool TopLevelClass : 1;
1527 
1528     /// Whether this class is an __interface.
1529     bool IsInterface : 1;
1530 
1531     /// The class or class template whose definition we are parsing.
1532     Decl *TagOrTemplate;
1533 
1534     /// LateParsedDeclarations - Method declarations, inline definitions and
1535     /// nested classes that contain pieces whose parsing will be delayed until
1536     /// the top-level class is fully defined.
1537     LateParsedDeclarationsContainer LateParsedDeclarations;
1538   };
1539 
1540   /// The stack of classes that is currently being
1541   /// parsed. Nested and local classes will be pushed onto this stack
1542   /// when they are parsed, and removed afterward.
1543   std::stack<ParsingClass *> ClassStack;
1544 
1545   ParsingClass &getCurrentClass() {
1546     assert(!ClassStack.empty() && "No lexed method stacks!");
1547     return *ClassStack.top();
1548   }
1549 
1550   /// RAII object used to manage the parsing of a class definition.
1551   class ParsingClassDefinition {
1552     Parser &P;
1553     bool Popped;
1554     Sema::ParsingClassState State;
1555 
1556   public:
1557     ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1558                            bool IsInterface)
1559       : P(P), Popped(false),
1560         State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1561     }
1562 
1563     /// Pop this class of the stack.
1564     void Pop() {
1565       assert(!Popped && "Nested class has already been popped");
1566       Popped = true;
1567       P.PopParsingClass(State);
1568     }
1569 
1570     ~ParsingClassDefinition() {
1571       if (!Popped)
1572         P.PopParsingClass(State);
1573     }
1574   };
1575 
1576   /// Contains information about any template-specific
1577   /// information that has been parsed prior to parsing declaration
1578   /// specifiers.
1579   struct ParsedTemplateInfo {
1580     ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr) {}
1581 
1582     ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1583                        bool isSpecialization,
1584                        bool lastParameterListWasEmpty = false)
1585       : Kind(isSpecialization? ExplicitSpecialization : Template),
1586         TemplateParams(TemplateParams),
1587         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1588 
1589     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1590                                 SourceLocation TemplateLoc)
1591       : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1592         ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1593         LastParameterListWasEmpty(false){ }
1594 
1595     /// The kind of template we are parsing.
1596     enum {
1597       /// We are not parsing a template at all.
1598       NonTemplate = 0,
1599       /// We are parsing a template declaration.
1600       Template,
1601       /// We are parsing an explicit specialization.
1602       ExplicitSpecialization,
1603       /// We are parsing an explicit instantiation.
1604       ExplicitInstantiation
1605     } Kind;
1606 
1607     /// The template parameter lists, for template declarations
1608     /// and explicit specializations.
1609     TemplateParameterLists *TemplateParams;
1610 
1611     /// The location of the 'extern' keyword, if any, for an explicit
1612     /// instantiation
1613     SourceLocation ExternLoc;
1614 
1615     /// The location of the 'template' keyword, for an explicit
1616     /// instantiation.
1617     SourceLocation TemplateLoc;
1618 
1619     /// Whether the last template parameter list was empty.
1620     bool LastParameterListWasEmpty;
1621 
1622     SourceRange getSourceRange() const LLVM_READONLY;
1623   };
1624 
1625   // In ParseCXXInlineMethods.cpp.
1626   struct ReenterTemplateScopeRAII;
1627   struct ReenterClassScopeRAII;
1628 
1629   void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1630   void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1631 
1632   static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1633 
1634   Sema::ParsingClassState
1635   PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1636   void DeallocateParsedClasses(ParsingClass *Class);
1637   void PopParsingClass(Sema::ParsingClassState);
1638 
1639   enum CachedInitKind {
1640     CIK_DefaultArgument,
1641     CIK_DefaultInitializer
1642   };
1643 
1644   NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1645                                      const ParsedAttributesView &AccessAttrs,
1646                                      ParsingDeclarator &D,
1647                                      const ParsedTemplateInfo &TemplateInfo,
1648                                      const VirtSpecifiers &VS,
1649                                      SourceLocation PureSpecLoc);
1650   StringLiteral *ParseCXXDeletedFunctionMessage();
1651   void SkipDeletedFunctionBody();
1652   void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1653   void ParseLexedAttributes(ParsingClass &Class);
1654   void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1655                                bool EnterScope, bool OnDefinition);
1656   void ParseLexedCAttributeList(LateParsedAttrList &LA, bool EnterScope,
1657                                 ParsedAttributes *OutAttrs = nullptr);
1658   void ParseLexedAttribute(LateParsedAttribute &LA,
1659                            bool EnterScope, bool OnDefinition);
1660   void ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
1661                             ParsedAttributes *OutAttrs = nullptr);
1662   void ParseLexedMethodDeclarations(ParsingClass &Class);
1663   void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1664   void ParseLexedMethodDefs(ParsingClass &Class);
1665   void ParseLexedMethodDef(LexedMethod &LM);
1666   void ParseLexedMemberInitializers(ParsingClass &Class);
1667   void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1668   void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1669   void ParseLexedPragmas(ParsingClass &Class);
1670   void ParseLexedPragma(LateParsedPragma &LP);
1671   bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1672   bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1673   bool ConsumeAndStoreConditional(CachedTokens &Toks);
1674   bool ConsumeAndStoreUntil(tok::TokenKind T1,
1675                             CachedTokens &Toks,
1676                             bool StopAtSemi = true,
1677                             bool ConsumeFinalToken = true) {
1678     return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1679   }
1680   bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1681                             CachedTokens &Toks,
1682                             bool StopAtSemi = true,
1683                             bool ConsumeFinalToken = true);
1684 
1685   //===--------------------------------------------------------------------===//
1686   // C99 6.9: External Definitions.
1687   DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributes &DeclAttrs,
1688                                           ParsedAttributes &DeclSpecAttrs,
1689                                           ParsingDeclSpec *DS = nullptr);
1690   bool isDeclarationAfterDeclarator();
1691   bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1692   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1693       ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1694       ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none);
1695   DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs,
1696                                                 ParsedAttributes &DeclSpecAttrs,
1697                                                 ParsingDeclSpec &DS,
1698                                                 AccessSpecifier AS);
1699 
1700   void SkipFunctionBody();
1701   Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1702                  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1703                  LateParsedAttrList *LateParsedAttrs = nullptr);
1704   void ParseKNRParamDeclarations(Declarator &D);
1705   // EndLoc is filled with the location of the last token of the simple-asm.
1706   ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1707   ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1708 
1709   // Objective-C External Declarations
1710   void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1711   DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributes &DeclAttrs,
1712                                        ParsedAttributes &DeclSpecAttrs);
1713   DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1714   Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1715                                         ParsedAttributes &prefixAttrs);
1716   class ObjCTypeParamListScope;
1717   ObjCTypeParamList *parseObjCTypeParamList();
1718   ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1719       ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1720       SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1721       SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1722 
1723   void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
1724                                         SourceLocation atLoc,
1725                                         BalancedDelimiterTracker &T,
1726                                         SmallVectorImpl<Decl *> &AllIvarDecls,
1727                                         bool RBraceMissing);
1728   void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
1729                                        tok::ObjCKeywordKind visibility,
1730                                        SourceLocation atLoc);
1731   bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1732                                    SmallVectorImpl<SourceLocation> &PLocs,
1733                                    bool WarnOnDeclarations,
1734                                    bool ForObjCContainer,
1735                                    SourceLocation &LAngleLoc,
1736                                    SourceLocation &EndProtoLoc,
1737                                    bool consumeLastToken);
1738 
1739   /// Parse the first angle-bracket-delimited clause for an
1740   /// Objective-C object or object pointer type, which may be either
1741   /// type arguments or protocol qualifiers.
1742   void parseObjCTypeArgsOrProtocolQualifiers(
1743          ParsedType baseType,
1744          SourceLocation &typeArgsLAngleLoc,
1745          SmallVectorImpl<ParsedType> &typeArgs,
1746          SourceLocation &typeArgsRAngleLoc,
1747          SourceLocation &protocolLAngleLoc,
1748          SmallVectorImpl<Decl *> &protocols,
1749          SmallVectorImpl<SourceLocation> &protocolLocs,
1750          SourceLocation &protocolRAngleLoc,
1751          bool consumeLastToken,
1752          bool warnOnIncompleteProtocols);
1753 
1754   /// Parse either Objective-C type arguments or protocol qualifiers; if the
1755   /// former, also parse protocol qualifiers afterward.
1756   void parseObjCTypeArgsAndProtocolQualifiers(
1757          ParsedType baseType,
1758          SourceLocation &typeArgsLAngleLoc,
1759          SmallVectorImpl<ParsedType> &typeArgs,
1760          SourceLocation &typeArgsRAngleLoc,
1761          SourceLocation &protocolLAngleLoc,
1762          SmallVectorImpl<Decl *> &protocols,
1763          SmallVectorImpl<SourceLocation> &protocolLocs,
1764          SourceLocation &protocolRAngleLoc,
1765          bool consumeLastToken);
1766 
1767   /// Parse a protocol qualifier type such as '<NSCopying>', which is
1768   /// an anachronistic way of writing 'id<NSCopying>'.
1769   TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1770 
1771   /// Parse Objective-C type arguments and protocol qualifiers, extending the
1772   /// current type with the parsed result.
1773   TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1774                                                     ParsedType type,
1775                                                     bool consumeLastToken,
1776                                                     SourceLocation &endLoc);
1777 
1778   void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1779                                   Decl *CDecl);
1780   DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1781                                                 ParsedAttributes &prefixAttrs);
1782 
1783   struct ObjCImplParsingDataRAII {
1784     Parser &P;
1785     Decl *Dcl;
1786     bool HasCFunction;
1787     typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1788     LateParsedObjCMethodContainer LateParsedObjCMethods;
1789 
1790     ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1791       : P(parser), Dcl(D), HasCFunction(false) {
1792       P.CurParsedObjCImpl = this;
1793       Finished = false;
1794     }
1795     ~ObjCImplParsingDataRAII();
1796 
1797     void finish(SourceRange AtEnd);
1798     bool isFinished() const { return Finished; }
1799 
1800   private:
1801     bool Finished;
1802   };
1803   ObjCImplParsingDataRAII *CurParsedObjCImpl;
1804   void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1805 
1806   DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
1807                                                       ParsedAttributes &Attrs);
1808   DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1809   Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1810   Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1811   Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1812 
1813   IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1814   // Definitions for Objective-c context sensitive keywords recognition.
1815   enum ObjCTypeQual {
1816     objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1817     objc_nonnull, objc_nullable, objc_null_unspecified,
1818     objc_NumQuals
1819   };
1820   IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1821 
1822   bool isTokIdentifier_in() const;
1823 
1824   ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
1825                                ParsedAttributes *ParamAttrs);
1826   Decl *ParseObjCMethodPrototype(
1827             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1828             bool MethodDefinition = true);
1829   Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1830             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1831             bool MethodDefinition=true);
1832   void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1833 
1834   Decl *ParseObjCMethodDefinition();
1835 
1836 public:
1837   //===--------------------------------------------------------------------===//
1838   // C99 6.5: Expressions.
1839 
1840   /// TypeCastState - State whether an expression is or may be a type cast.
1841   enum TypeCastState {
1842     NotTypeCast = 0,
1843     MaybeTypeCast,
1844     IsTypeCast
1845   };
1846 
1847   ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1848   ExprResult ParseConstantExpressionInExprEvalContext(
1849       TypeCastState isTypeCast = NotTypeCast);
1850   ExprResult ParseConstantExpression();
1851   ExprResult ParseArrayBoundExpression();
1852   ExprResult ParseCaseExpression(SourceLocation CaseLoc);
1853   ExprResult ParseConstraintExpression();
1854   ExprResult
1855   ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
1856   ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
1857   // Expr that doesn't include commas.
1858   ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1859   ExprResult ParseConditionalExpression();
1860 
1861   ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1862                                   unsigned &NumLineToksConsumed,
1863                                   bool IsUnevaluated);
1864 
1865   ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1866   ExprResult ParseUnevaluatedStringLiteralExpression();
1867 
1868 private:
1869   ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
1870                                           bool Unevaluated);
1871 
1872   ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1873 
1874   ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1875 
1876   ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1877                                         prec::Level MinPrec);
1878   /// Control what ParseCastExpression will parse.
1879   enum CastParseKind {
1880     AnyCastExpr = 0,
1881     UnaryExprOnly,
1882     PrimaryExprOnly
1883   };
1884 
1885   bool isRevertibleTypeTrait(const IdentifierInfo *Id,
1886                              clang::tok::TokenKind *Kind = nullptr);
1887 
1888   ExprResult ParseCastExpression(CastParseKind ParseKind,
1889                                  bool isAddressOfOperand,
1890                                  bool &NotCastExpr,
1891                                  TypeCastState isTypeCast,
1892                                  bool isVectorLiteral = false,
1893                                  bool *NotPrimaryExpression = nullptr);
1894   ExprResult ParseCastExpression(CastParseKind ParseKind,
1895                                  bool isAddressOfOperand = false,
1896                                  TypeCastState isTypeCast = NotTypeCast,
1897                                  bool isVectorLiteral = false,
1898                                  bool *NotPrimaryExpression = nullptr);
1899 
1900   /// Returns true if the next token cannot start an expression.
1901   bool isNotExpressionStart();
1902 
1903   /// Returns true if the next token would start a postfix-expression
1904   /// suffix.
1905   bool isPostfixExpressionSuffixStart() {
1906     tok::TokenKind K = Tok.getKind();
1907     return (K == tok::l_square || K == tok::l_paren ||
1908             K == tok::period || K == tok::arrow ||
1909             K == tok::plusplus || K == tok::minusminus);
1910   }
1911 
1912   bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1913   void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1914   bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1915                                            const Token &OpToken);
1916   bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1917     if (auto *Info = AngleBrackets.getCurrent(*this))
1918       return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1919     return false;
1920   }
1921 
1922   ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1923   ExprResult ParseUnaryExprOrTypeTraitExpression();
1924   ExprResult ParseBuiltinPrimaryExpression();
1925   ExprResult ParseSYCLUniqueStableNameExpression();
1926 
1927   ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1928                                                      bool &isCastExpr,
1929                                                      ParsedType &CastTy,
1930                                                      SourceRange &CastRange);
1931 
1932   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1933   bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1934                            llvm::function_ref<void()> ExpressionStarts =
1935                                llvm::function_ref<void()>(),
1936                            bool FailImmediatelyOnInvalidExpr = false,
1937                            bool EarlyTypoCorrection = false,
1938                            bool *HasTrailingComma = nullptr);
1939 
1940   /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1941   /// used for misc language extensions.
1942   bool ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs);
1943 
1944   /// ParenParseOption - Control what ParseParenExpression will parse.
1945   enum ParenParseOption {
1946     SimpleExpr,      // Only parse '(' expression ')'
1947     FoldExpr,        // Also allow fold-expression <anything>
1948     CompoundStmt,    // Also allow '(' compound-statement ')'
1949     CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1950     CastExpr         // Also allow '(' type-name ')' <anything>
1951   };
1952   ExprResult ParseParenExpression(ParenParseOption &ExprType,
1953                                         bool stopIfCastExpr,
1954                                         bool isTypeCast,
1955                                         ParsedType &CastTy,
1956                                         SourceLocation &RParenLoc);
1957 
1958   ExprResult ParseCXXAmbiguousParenExpression(
1959       ParenParseOption &ExprType, ParsedType &CastTy,
1960       BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1961   ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1962                                                   SourceLocation LParenLoc,
1963                                                   SourceLocation RParenLoc);
1964 
1965   ExprResult ParseGenericSelectionExpression();
1966 
1967   ExprResult ParseObjCBoolLiteral();
1968 
1969   ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1970 
1971   //===--------------------------------------------------------------------===//
1972   // C++ Expressions
1973   ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1974                                      Token &Replacement);
1975 
1976   ExprResult tryParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1977   ExprResult ParseCXXPackIndexingExpression(ExprResult PackIdExpression);
1978 
1979   ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1980 
1981   bool areTokensAdjacent(const Token &A, const Token &B);
1982 
1983   void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1984                                   bool EnteringContext, IdentifierInfo &II,
1985                                   CXXScopeSpec &SS);
1986 
1987   bool ParseOptionalCXXScopeSpecifier(
1988       CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors,
1989       bool EnteringContext, bool *MayBePseudoDestructor = nullptr,
1990       bool IsTypename = false, const IdentifierInfo **LastII = nullptr,
1991       bool OnlyNamespace = false, bool InUsingDeclaration = false,
1992       bool Disambiguation = false);
1993 
1994   //===--------------------------------------------------------------------===//
1995   // C++11 5.1.2: Lambda expressions
1996 
1997   /// Result of tentatively parsing a lambda-introducer.
1998   enum class LambdaIntroducerTentativeParse {
1999     /// This appears to be a lambda-introducer, which has been fully parsed.
2000     Success,
2001     /// This is a lambda-introducer, but has not been fully parsed, and this
2002     /// function needs to be called again to parse it.
2003     Incomplete,
2004     /// This is definitely an Objective-C message send expression, rather than
2005     /// a lambda-introducer, attribute-specifier, or array designator.
2006     MessageSend,
2007     /// This is not a lambda-introducer.
2008     Invalid,
2009   };
2010 
2011   // [...] () -> type {...}
2012   ExprResult ParseLambdaExpression();
2013   ExprResult TryParseLambdaExpression();
2014   bool
2015   ParseLambdaIntroducer(LambdaIntroducer &Intro,
2016                         LambdaIntroducerTentativeParse *Tentative = nullptr);
2017   ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
2018 
2019   //===--------------------------------------------------------------------===//
2020   // C++ 5.2p1: C++ Casts
2021   ExprResult ParseCXXCasts();
2022 
2023   /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
2024   ExprResult ParseBuiltinBitCast();
2025 
2026   //===--------------------------------------------------------------------===//
2027   // C++ 5.2p1: C++ Type Identification
2028   ExprResult ParseCXXTypeid();
2029 
2030   //===--------------------------------------------------------------------===//
2031   //  C++ : Microsoft __uuidof Expression
2032   ExprResult ParseCXXUuidof();
2033 
2034   //===--------------------------------------------------------------------===//
2035   // C++ 5.2.4: C++ Pseudo-Destructor Expressions
2036   ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
2037                                             tok::TokenKind OpKind,
2038                                             CXXScopeSpec &SS,
2039                                             ParsedType ObjectType);
2040 
2041   //===--------------------------------------------------------------------===//
2042   // C++ 9.3.2: C++ 'this' pointer
2043   ExprResult ParseCXXThis();
2044 
2045   //===--------------------------------------------------------------------===//
2046   // C++ 15: C++ Throw Expression
2047   ExprResult ParseThrowExpression();
2048 
2049   ExceptionSpecificationType tryParseExceptionSpecification(
2050                     bool Delayed,
2051                     SourceRange &SpecificationRange,
2052                     SmallVectorImpl<ParsedType> &DynamicExceptions,
2053                     SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2054                     ExprResult &NoexceptExpr,
2055                     CachedTokens *&ExceptionSpecTokens);
2056 
2057   // EndLoc is filled with the location of the last token of the specification.
2058   ExceptionSpecificationType ParseDynamicExceptionSpecification(
2059                                   SourceRange &SpecificationRange,
2060                                   SmallVectorImpl<ParsedType> &Exceptions,
2061                                   SmallVectorImpl<SourceRange> &Ranges);
2062 
2063   //===--------------------------------------------------------------------===//
2064   // C++0x 8: Function declaration trailing-return-type
2065   TypeResult ParseTrailingReturnType(SourceRange &Range,
2066                                      bool MayBeFollowedByDirectInit);
2067 
2068   //===--------------------------------------------------------------------===//
2069   // C++ 2.13.5: C++ Boolean Literals
2070   ExprResult ParseCXXBoolLiteral();
2071 
2072   //===--------------------------------------------------------------------===//
2073   // C++ 5.2.3: Explicit type conversion (functional notation)
2074   ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
2075 
2076   /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2077   /// This should only be called when the current token is known to be part of
2078   /// simple-type-specifier.
2079   void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
2080 
2081   bool ParseCXXTypeSpecifierSeq(
2082       DeclSpec &DS, DeclaratorContext Context = DeclaratorContext::TypeName);
2083 
2084   //===--------------------------------------------------------------------===//
2085   // C++ 5.3.4 and 5.3.5: C++ new and delete
2086   bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
2087                                    Declarator &D);
2088   void ParseDirectNewDeclarator(Declarator &D);
2089   ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
2090   ExprResult ParseCXXDeleteExpression(bool UseGlobal,
2091                                             SourceLocation Start);
2092 
2093   //===--------------------------------------------------------------------===//
2094   // C++ if/switch/while/for condition expression.
2095   struct ForRangeInfo;
2096   Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
2097                                           SourceLocation Loc,
2098                                           Sema::ConditionKind CK,
2099                                           bool MissingOK,
2100                                           ForRangeInfo *FRI = nullptr,
2101                                           bool EnterForConditionScope = false);
2102   DeclGroupPtrTy ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
2103                                                       ParsedAttributes &Attrs);
2104 
2105   //===--------------------------------------------------------------------===//
2106   // C++ Coroutines
2107 
2108   ExprResult ParseCoyieldExpression();
2109 
2110   //===--------------------------------------------------------------------===//
2111   // C++ Concepts
2112 
2113   ExprResult ParseRequiresExpression();
2114   void ParseTrailingRequiresClause(Declarator &D);
2115 
2116   //===--------------------------------------------------------------------===//
2117   // C99 6.7.8: Initialization.
2118 
2119   /// ParseInitializer
2120   ///       initializer: [C99 6.7.8]
2121   ///         assignment-expression
2122   ///         '{' ...
2123   ExprResult ParseInitializer() {
2124     if (Tok.isNot(tok::l_brace))
2125       return ParseAssignmentExpression();
2126     return ParseBraceInitializer();
2127   }
2128   bool MayBeDesignationStart();
2129   ExprResult ParseBraceInitializer();
2130   struct DesignatorCompletionInfo {
2131     SmallVectorImpl<Expr *> &InitExprs;
2132     QualType PreferredBaseType;
2133   };
2134   ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
2135   ExprResult createEmbedExpr();
2136   void injectEmbedTokens();
2137 
2138   //===--------------------------------------------------------------------===//
2139   // clang Expressions
2140 
2141   ExprResult ParseBlockLiteralExpression();  // ^{...}
2142 
2143   //===--------------------------------------------------------------------===//
2144   // Objective-C Expressions
2145   ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
2146   ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
2147   ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
2148   ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
2149   ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
2150   ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
2151   ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
2152   ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
2153   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
2154   ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
2155   ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
2156   bool isSimpleObjCMessageExpression();
2157   ExprResult ParseObjCMessageExpression();
2158   ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
2159                                             SourceLocation SuperLoc,
2160                                             ParsedType ReceiverType,
2161                                             Expr *ReceiverExpr);
2162   ExprResult ParseAssignmentExprWithObjCMessageExprStart(
2163       SourceLocation LBracloc, SourceLocation SuperLoc,
2164       ParsedType ReceiverType, Expr *ReceiverExpr);
2165   bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
2166 
2167   //===--------------------------------------------------------------------===//
2168   // C99 6.8: Statements and Blocks.
2169 
2170   /// A SmallVector of expressions.
2171   typedef SmallVector<Expr*, 12> ExprVector;
2172 
2173   StmtResult
2174   ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
2175                  ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
2176   StmtResult ParseStatementOrDeclaration(
2177       StmtVector &Stmts, ParsedStmtContext StmtCtx,
2178       SourceLocation *TrailingElseLoc = nullptr);
2179   StmtResult ParseStatementOrDeclarationAfterAttributes(
2180       StmtVector &Stmts, ParsedStmtContext StmtCtx,
2181       SourceLocation *TrailingElseLoc, ParsedAttributes &DeclAttrs,
2182       ParsedAttributes &DeclSpecAttrs);
2183   StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
2184   StmtResult ParseLabeledStatement(ParsedAttributes &Attrs,
2185                                    ParsedStmtContext StmtCtx);
2186   StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
2187                                 bool MissingCase = false,
2188                                 ExprResult Expr = ExprResult());
2189   StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
2190   StmtResult ParseCompoundStatement(bool isStmtExpr = false);
2191   StmtResult ParseCompoundStatement(bool isStmtExpr,
2192                                     unsigned ScopeFlags);
2193   void ParseCompoundStatementLeadingPragmas();
2194   void DiagnoseLabelAtEndOfCompoundStatement();
2195   bool ConsumeNullStmt(StmtVector &Stmts);
2196   StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
2197   bool ParseParenExprOrCondition(StmtResult *InitStmt,
2198                                  Sema::ConditionResult &CondResult,
2199                                  SourceLocation Loc, Sema::ConditionKind CK,
2200                                  SourceLocation &LParenLoc,
2201                                  SourceLocation &RParenLoc);
2202   StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
2203   StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
2204   StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
2205   StmtResult ParseDoStatement();
2206   StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
2207   StmtResult ParseGotoStatement();
2208   StmtResult ParseContinueStatement();
2209   StmtResult ParseBreakStatement();
2210   StmtResult ParseReturnStatement();
2211   StmtResult ParseAsmStatement(bool &msAsm);
2212   StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
2213   StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx,
2214                                  SourceLocation *TrailingElseLoc,
2215                                  ParsedAttributes &Attrs);
2216 
2217   /// Describes the behavior that should be taken for an __if_exists
2218   /// block.
2219   enum IfExistsBehavior {
2220     /// Parse the block; this code is always used.
2221     IEB_Parse,
2222     /// Skip the block entirely; this code is never used.
2223     IEB_Skip,
2224     /// Parse the block as a dependent block, which may be used in
2225     /// some template instantiations but not others.
2226     IEB_Dependent
2227   };
2228 
2229   /// Describes the condition of a Microsoft __if_exists or
2230   /// __if_not_exists block.
2231   struct IfExistsCondition {
2232     /// The location of the initial keyword.
2233     SourceLocation KeywordLoc;
2234     /// Whether this is an __if_exists block (rather than an
2235     /// __if_not_exists block).
2236     bool IsIfExists;
2237 
2238     /// Nested-name-specifier preceding the name.
2239     CXXScopeSpec SS;
2240 
2241     /// The name we're looking for.
2242     UnqualifiedId Name;
2243 
2244     /// The behavior of this __if_exists or __if_not_exists block
2245     /// should.
2246     IfExistsBehavior Behavior;
2247   };
2248 
2249   bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
2250   void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
2251   void ParseMicrosoftIfExistsExternalDeclaration();
2252   void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2253                                               ParsedAttributes &AccessAttrs,
2254                                               AccessSpecifier &CurAS);
2255   bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2256                                               bool &InitExprsOk);
2257   bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2258                            SmallVectorImpl<Expr *> &Constraints,
2259                            SmallVectorImpl<Expr *> &Exprs);
2260 
2261   //===--------------------------------------------------------------------===//
2262   // C++ 6: Statements and Blocks
2263 
2264   StmtResult ParseCXXTryBlock();
2265   StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2266   StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2267 
2268   //===--------------------------------------------------------------------===//
2269   // MS: SEH Statements and Blocks
2270 
2271   StmtResult ParseSEHTryBlock();
2272   StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2273   StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2274   StmtResult ParseSEHLeaveStatement();
2275 
2276   //===--------------------------------------------------------------------===//
2277   // Objective-C Statements
2278 
2279   StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2280                                   ParsedStmtContext StmtCtx);
2281   StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2282   StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2283   StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2284   StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2285 
2286 
2287   //===--------------------------------------------------------------------===//
2288   // C99 6.7: Declarations.
2289 
2290   /// A context for parsing declaration specifiers.  TODO: flesh this
2291   /// out, there are other significant restrictions on specifiers than
2292   /// would be best implemented in the parser.
2293   enum class DeclSpecContext {
2294     DSC_normal,         // normal context
2295     DSC_class,          // class context, enables 'friend'
2296     DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2297     DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2298     DSC_alias_declaration,  // C++11 type-specifier-seq in an alias-declaration
2299     DSC_conv_operator,      // C++ type-specifier-seq in an conversion operator
2300     DSC_top_level,          // top-level/namespace declaration context
2301     DSC_template_param,     // template parameter context
2302     DSC_template_arg,       // template argument context
2303     DSC_template_type_arg,  // template type argument context
2304     DSC_objc_method_result, // ObjC method result context, enables
2305                             // 'instancetype'
2306     DSC_condition,          // condition declaration context
2307     DSC_association, // A _Generic selection expression's type association
2308     DSC_new,         // C++ new expression
2309   };
2310 
2311   /// Is this a context in which we are parsing just a type-specifier (or
2312   /// trailing-type-specifier)?
2313   static bool isTypeSpecifier(DeclSpecContext DSC) {
2314     switch (DSC) {
2315     case DeclSpecContext::DSC_normal:
2316     case DeclSpecContext::DSC_template_param:
2317     case DeclSpecContext::DSC_template_arg:
2318     case DeclSpecContext::DSC_class:
2319     case DeclSpecContext::DSC_top_level:
2320     case DeclSpecContext::DSC_objc_method_result:
2321     case DeclSpecContext::DSC_condition:
2322       return false;
2323 
2324     case DeclSpecContext::DSC_template_type_arg:
2325     case DeclSpecContext::DSC_type_specifier:
2326     case DeclSpecContext::DSC_conv_operator:
2327     case DeclSpecContext::DSC_trailing:
2328     case DeclSpecContext::DSC_alias_declaration:
2329     case DeclSpecContext::DSC_association:
2330     case DeclSpecContext::DSC_new:
2331       return true;
2332     }
2333     llvm_unreachable("Missing DeclSpecContext case");
2334   }
2335 
2336   /// Whether a defining-type-specifier is permitted in a given context.
2337   enum class AllowDefiningTypeSpec {
2338     /// The grammar doesn't allow a defining-type-specifier here, and we must
2339     /// not parse one (eg, because a '{' could mean something else).
2340     No,
2341     /// The grammar doesn't allow a defining-type-specifier here, but we permit
2342     /// one for error recovery purposes. Sema will reject.
2343     NoButErrorRecovery,
2344     /// The grammar allows a defining-type-specifier here, even though it's
2345     /// always invalid. Sema will reject.
2346     YesButInvalid,
2347     /// The grammar allows a defining-type-specifier here, and one can be valid.
2348     Yes
2349   };
2350 
2351   /// Is this a context in which we are parsing defining-type-specifiers (and
2352   /// so permit class and enum definitions in addition to non-defining class and
2353   /// enum elaborated-type-specifiers)?
2354   static AllowDefiningTypeSpec
2355   isDefiningTypeSpecifierContext(DeclSpecContext DSC, bool IsCPlusPlus) {
2356     switch (DSC) {
2357     case DeclSpecContext::DSC_normal:
2358     case DeclSpecContext::DSC_class:
2359     case DeclSpecContext::DSC_top_level:
2360     case DeclSpecContext::DSC_alias_declaration:
2361     case DeclSpecContext::DSC_objc_method_result:
2362       return AllowDefiningTypeSpec::Yes;
2363 
2364     case DeclSpecContext::DSC_condition:
2365     case DeclSpecContext::DSC_template_param:
2366       return AllowDefiningTypeSpec::YesButInvalid;
2367 
2368     case DeclSpecContext::DSC_template_type_arg:
2369     case DeclSpecContext::DSC_type_specifier:
2370       return AllowDefiningTypeSpec::NoButErrorRecovery;
2371 
2372     case DeclSpecContext::DSC_association:
2373       return IsCPlusPlus ? AllowDefiningTypeSpec::NoButErrorRecovery
2374                          : AllowDefiningTypeSpec::Yes;
2375 
2376     case DeclSpecContext::DSC_trailing:
2377     case DeclSpecContext::DSC_conv_operator:
2378     case DeclSpecContext::DSC_template_arg:
2379     case DeclSpecContext::DSC_new:
2380       return AllowDefiningTypeSpec::No;
2381     }
2382     llvm_unreachable("Missing DeclSpecContext case");
2383   }
2384 
2385   /// Is this a context in which an opaque-enum-declaration can appear?
2386   static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
2387     switch (DSC) {
2388     case DeclSpecContext::DSC_normal:
2389     case DeclSpecContext::DSC_class:
2390     case DeclSpecContext::DSC_top_level:
2391       return true;
2392 
2393     case DeclSpecContext::DSC_alias_declaration:
2394     case DeclSpecContext::DSC_objc_method_result:
2395     case DeclSpecContext::DSC_condition:
2396     case DeclSpecContext::DSC_template_param:
2397     case DeclSpecContext::DSC_template_type_arg:
2398     case DeclSpecContext::DSC_type_specifier:
2399     case DeclSpecContext::DSC_trailing:
2400     case DeclSpecContext::DSC_association:
2401     case DeclSpecContext::DSC_conv_operator:
2402     case DeclSpecContext::DSC_template_arg:
2403     case DeclSpecContext::DSC_new:
2404 
2405       return false;
2406     }
2407     llvm_unreachable("Missing DeclSpecContext case");
2408   }
2409 
2410   /// Is this a context in which we can perform class template argument
2411   /// deduction?
2412   static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2413     switch (DSC) {
2414     case DeclSpecContext::DSC_normal:
2415     case DeclSpecContext::DSC_template_param:
2416     case DeclSpecContext::DSC_template_arg:
2417     case DeclSpecContext::DSC_class:
2418     case DeclSpecContext::DSC_top_level:
2419     case DeclSpecContext::DSC_condition:
2420     case DeclSpecContext::DSC_type_specifier:
2421     case DeclSpecContext::DSC_association:
2422     case DeclSpecContext::DSC_conv_operator:
2423     case DeclSpecContext::DSC_new:
2424       return true;
2425 
2426     case DeclSpecContext::DSC_objc_method_result:
2427     case DeclSpecContext::DSC_template_type_arg:
2428     case DeclSpecContext::DSC_trailing:
2429     case DeclSpecContext::DSC_alias_declaration:
2430       return false;
2431     }
2432     llvm_unreachable("Missing DeclSpecContext case");
2433   }
2434 
2435   // Is this a context in which an implicit 'typename' is allowed?
2436   static ImplicitTypenameContext
2437   getImplicitTypenameContext(DeclSpecContext DSC) {
2438     switch (DSC) {
2439     case DeclSpecContext::DSC_class:
2440     case DeclSpecContext::DSC_top_level:
2441     case DeclSpecContext::DSC_type_specifier:
2442     case DeclSpecContext::DSC_template_type_arg:
2443     case DeclSpecContext::DSC_trailing:
2444     case DeclSpecContext::DSC_alias_declaration:
2445     case DeclSpecContext::DSC_template_param:
2446     case DeclSpecContext::DSC_new:
2447       return ImplicitTypenameContext::Yes;
2448 
2449     case DeclSpecContext::DSC_normal:
2450     case DeclSpecContext::DSC_objc_method_result:
2451     case DeclSpecContext::DSC_condition:
2452     case DeclSpecContext::DSC_template_arg:
2453     case DeclSpecContext::DSC_conv_operator:
2454     case DeclSpecContext::DSC_association:
2455       return ImplicitTypenameContext::No;
2456     }
2457     llvm_unreachable("Missing DeclSpecContext case");
2458   }
2459 
2460   /// Information on a C++0x for-range-initializer found while parsing a
2461   /// declaration which turns out to be a for-range-declaration.
2462   struct ForRangeInit {
2463     SourceLocation ColonLoc;
2464     ExprResult RangeExpr;
2465     SmallVector<MaterializeTemporaryExpr *, 8> LifetimeExtendTemps;
2466     bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2467   };
2468   struct ForRangeInfo : ForRangeInit {
2469     StmtResult LoopVar;
2470   };
2471 
2472   DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2473                                   SourceLocation &DeclEnd,
2474                                   ParsedAttributes &DeclAttrs,
2475                                   ParsedAttributes &DeclSpecAttrs,
2476                                   SourceLocation *DeclSpecStart = nullptr);
2477   DeclGroupPtrTy
2478   ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
2479                          ParsedAttributes &DeclAttrs,
2480                          ParsedAttributes &DeclSpecAttrs, bool RequireSemi,
2481                          ForRangeInit *FRI = nullptr,
2482                          SourceLocation *DeclSpecStart = nullptr);
2483   bool MightBeDeclarator(DeclaratorContext Context);
2484   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2485                                 ParsedAttributes &Attrs,
2486                                 ParsedTemplateInfo &TemplateInfo,
2487                                 SourceLocation *DeclEnd = nullptr,
2488                                 ForRangeInit *FRI = nullptr);
2489   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2490                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2491   bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2492   Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2493       Declarator &D,
2494       const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2495       ForRangeInit *FRI = nullptr);
2496   Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2497   Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2498 
2499   /// When in code-completion, skip parsing of the function/method body
2500   /// unless the body contains the code-completion point.
2501   ///
2502   /// \returns true if the function body was skipped.
2503   bool trySkippingFunctionBody();
2504 
2505   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2506                         ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
2507                         DeclSpecContext DSC, ParsedAttributes &Attrs);
2508   DeclSpecContext
2509   getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2510   void
2511   ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2512                              AccessSpecifier AS = AS_none,
2513                              DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2514                              LateParsedAttrList *LateAttrs = nullptr) {
2515     return ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
2516                                       getImplicitTypenameContext(DSC));
2517   }
2518   void
2519   ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
2520                              AccessSpecifier AS, DeclSpecContext DSC,
2521                              LateParsedAttrList *LateAttrs,
2522                              ImplicitTypenameContext AllowImplicitTypename);
2523 
2524   SourceLocation ParsePackIndexingType(DeclSpec &DS);
2525   void AnnotateExistingIndexedTypeNamePack(ParsedType T,
2526                                            SourceLocation StartLoc,
2527                                            SourceLocation EndLoc);
2528 
2529   bool DiagnoseMissingSemiAfterTagDefinition(
2530       DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2531       LateParsedAttrList *LateAttrs = nullptr);
2532 
2533   void ParseSpecifierQualifierList(
2534       DeclSpec &DS, AccessSpecifier AS = AS_none,
2535       DeclSpecContext DSC = DeclSpecContext::DSC_normal) {
2536     ParseSpecifierQualifierList(DS, getImplicitTypenameContext(DSC), AS, DSC);
2537   }
2538 
2539   void ParseSpecifierQualifierList(
2540       DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2541       AccessSpecifier AS = AS_none,
2542       DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2543 
2544   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2545                                   DeclaratorContext Context);
2546 
2547   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2548                           const ParsedTemplateInfo &TemplateInfo,
2549                           AccessSpecifier AS, DeclSpecContext DSC);
2550   void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2551   void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2552                             RecordDecl *TagDecl);
2553 
2554   void ParseStructDeclaration(
2555       ParsingDeclSpec &DS,
2556       llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
2557       LateParsedAttrList *LateFieldAttrs = nullptr);
2558 
2559   DeclGroupPtrTy ParseTopLevelStmtDecl();
2560 
2561   bool isDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2562                               bool DisambiguatingWithExpression = false);
2563   bool isTypeSpecifierQualifier();
2564 
2565   /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2566   /// is definitely a type-specifier.  Return false if it isn't part of a type
2567   /// specifier or if we're not sure.
2568   bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2569 
2570   /// Return true if we know that we are definitely looking at a
2571   /// decl-specifier, and isn't part of an expression such as a function-style
2572   /// cast. Return false if it's no a decl-specifier, or we're not sure.
2573   bool isKnownToBeDeclarationSpecifier() {
2574     if (getLangOpts().CPlusPlus)
2575       return isCXXDeclarationSpecifier(ImplicitTypenameContext::No) ==
2576              TPResult::True;
2577     return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2578   }
2579 
2580   /// isDeclarationStatement - Disambiguates between a declaration or an
2581   /// expression statement, when parsing function bodies.
2582   ///
2583   /// \param DisambiguatingWithExpression - True to indicate that the purpose of
2584   /// this check is to disambiguate between an expression and a declaration.
2585   /// Returns true for declaration, false for expression.
2586   bool isDeclarationStatement(bool DisambiguatingWithExpression = false) {
2587     if (getLangOpts().CPlusPlus)
2588       return isCXXDeclarationStatement(DisambiguatingWithExpression);
2589     return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2590   }
2591 
2592   /// isForInitDeclaration - Disambiguates between a declaration or an
2593   /// expression in the context of the C 'clause-1' or the C++
2594   // 'for-init-statement' part of a 'for' statement.
2595   /// Returns true for declaration, false for expression.
2596   bool isForInitDeclaration() {
2597     if (getLangOpts().OpenMP)
2598       Actions.OpenMP().startOpenMPLoop();
2599     if (getLangOpts().CPlusPlus)
2600       return Tok.is(tok::kw_using) ||
2601              isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2602     return isDeclarationSpecifier(ImplicitTypenameContext::No, true);
2603   }
2604 
2605   /// Determine whether this is a C++1z for-range-identifier.
2606   bool isForRangeIdentifier();
2607 
2608   /// Determine whether we are currently at the start of an Objective-C
2609   /// class message that appears to be missing the open bracket '['.
2610   bool isStartOfObjCClassMessageMissingOpenBracket();
2611 
2612   /// Starting with a scope specifier, identifier, or
2613   /// template-id that refers to the current class, determine whether
2614   /// this is a constructor declarator.
2615   bool isConstructorDeclarator(
2616       bool Unqualified, bool DeductionGuide = false,
2617       DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No,
2618       const ParsedTemplateInfo *TemplateInfo = nullptr);
2619 
2620   /// Specifies the context in which type-id/expression
2621   /// disambiguation will occur.
2622   enum TentativeCXXTypeIdContext {
2623     TypeIdInParens,
2624     TypeIdUnambiguous,
2625     TypeIdAsTemplateArgument,
2626     TypeIdInTrailingReturnType,
2627     TypeIdAsGenericSelectionArgument,
2628   };
2629 
2630   /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2631   /// whether the parens contain an expression or a type-id.
2632   /// Returns true for a type-id and false for an expression.
2633   bool isTypeIdInParens(bool &isAmbiguous) {
2634     if (getLangOpts().CPlusPlus)
2635       return isCXXTypeId(TypeIdInParens, isAmbiguous);
2636     isAmbiguous = false;
2637     return isTypeSpecifierQualifier();
2638   }
2639   bool isTypeIdInParens() {
2640     bool isAmbiguous;
2641     return isTypeIdInParens(isAmbiguous);
2642   }
2643 
2644   /// Checks whether the current tokens form a type-id or an expression for the
2645   /// purposes of use as the initial operand to a generic selection expression.
2646   /// This requires special handling in C++ because it accepts either a type or
2647   /// an expression, and we need to disambiguate which is which. However, we
2648   /// cannot use the same logic as we've used for sizeof expressions, because
2649   /// that logic relies on the operator only accepting a single argument,
2650   /// whereas _Generic accepts a list of arguments.
2651   bool isTypeIdForGenericSelection() {
2652     if (getLangOpts().CPlusPlus) {
2653       bool isAmbiguous;
2654       return isCXXTypeId(TypeIdAsGenericSelectionArgument, isAmbiguous);
2655     }
2656     return isTypeSpecifierQualifier();
2657   }
2658 
2659   /// Checks if the current tokens form type-id or expression.
2660   /// It is similar to isTypeIdInParens but does not suppose that type-id
2661   /// is in parenthesis.
2662   bool isTypeIdUnambiguously() {
2663     if (getLangOpts().CPlusPlus) {
2664       bool isAmbiguous;
2665       return isCXXTypeId(TypeIdUnambiguous, isAmbiguous);
2666     }
2667     return isTypeSpecifierQualifier();
2668   }
2669 
2670   /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2671   /// between a declaration or an expression statement, when parsing function
2672   /// bodies. Returns true for declaration, false for expression.
2673   bool isCXXDeclarationStatement(bool DisambiguatingWithExpression = false);
2674 
2675   /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2676   /// between a simple-declaration or an expression-statement.
2677   /// If during the disambiguation process a parsing error is encountered,
2678   /// the function returns true to let the declaration parsing code handle it.
2679   /// Returns false if the statement is disambiguated as expression.
2680   bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2681 
2682   /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2683   /// a constructor-style initializer, when parsing declaration statements.
2684   /// Returns true for function declarator and false for constructor-style
2685   /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2686   /// might be a constructor-style initializer.
2687   /// If during the disambiguation process a parsing error is encountered,
2688   /// the function returns true to let the declaration parsing code handle it.
2689   bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr,
2690                                ImplicitTypenameContext AllowImplicitTypename =
2691                                    ImplicitTypenameContext::No);
2692 
2693   struct ConditionDeclarationOrInitStatementState;
2694   enum class ConditionOrInitStatement {
2695     Expression,    ///< Disambiguated as an expression (either kind).
2696     ConditionDecl, ///< Disambiguated as the declaration form of condition.
2697     InitStmtDecl,  ///< Disambiguated as a simple-declaration init-statement.
2698     ForRangeDecl,  ///< Disambiguated as a for-range declaration.
2699     Error          ///< Can't be any of the above!
2700   };
2701   /// Disambiguates between the different kinds of things that can happen
2702   /// after 'if (' or 'switch ('. This could be one of two different kinds of
2703   /// declaration (depending on whether there is a ';' later) or an expression.
2704   ConditionOrInitStatement
2705   isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2706                                            bool CanBeForRangeDecl);
2707 
2708   bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2709   bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2710     bool isAmbiguous;
2711     return isCXXTypeId(Context, isAmbiguous);
2712   }
2713 
2714   /// TPResult - Used as the result value for functions whose purpose is to
2715   /// disambiguate C++ constructs by "tentatively parsing" them.
2716   enum class TPResult {
2717     True, False, Ambiguous, Error
2718   };
2719 
2720   /// Determine whether we could have an enum-base.
2721   ///
2722   /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
2723   /// only consider this to be an enum-base if the next token is a '{'.
2724   ///
2725   /// \return \c false if this cannot possibly be an enum base; \c true
2726   /// otherwise.
2727   bool isEnumBase(bool AllowSemi);
2728 
2729   /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2730   /// declaration specifier, TPResult::False if it is not,
2731   /// TPResult::Ambiguous if it could be either a decl-specifier or a
2732   /// function-style cast, and TPResult::Error if a parsing error was
2733   /// encountered. If it could be a braced C++11 function-style cast, returns
2734   /// BracedCastResult.
2735   /// Doesn't consume tokens.
2736   TPResult
2737   isCXXDeclarationSpecifier(ImplicitTypenameContext AllowImplicitTypename,
2738                             TPResult BracedCastResult = TPResult::False,
2739                             bool *InvalidAsDeclSpec = nullptr);
2740 
2741   /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2742   /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2743   /// a type-specifier other than a cv-qualifier.
2744   bool isCXXDeclarationSpecifierAType();
2745 
2746   /// Determine whether the current token sequence might be
2747   ///   '<' template-argument-list '>'
2748   /// rather than a less-than expression.
2749   TPResult isTemplateArgumentList(unsigned TokensToSkip);
2750 
2751   /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
2752   /// 'explicit(bool)' declaration, in earlier language modes where that is an
2753   /// extension.
2754   TPResult isExplicitBool();
2755 
2756   /// Determine whether an identifier has been tentatively declared as a
2757   /// non-type. Such tentative declarations should not be found to name a type
2758   /// during a tentative parse, but also should not be annotated as a non-type.
2759   bool isTentativelyDeclared(IdentifierInfo *II);
2760 
2761   // "Tentative parsing" functions, used for disambiguation. If a parsing error
2762   // is encountered they will return TPResult::Error.
2763   // Returning TPResult::True/False indicates that the ambiguity was
2764   // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2765   // that more tentative parsing is necessary for disambiguation.
2766   // They all consume tokens, so backtracking should be used after calling them.
2767 
2768   TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2769   TPResult TryParseTypeofSpecifier();
2770   TPResult TryParseProtocolQualifiers();
2771   TPResult TryParsePtrOperatorSeq();
2772   TPResult TryParseOperatorId();
2773   TPResult TryParseInitDeclaratorList(bool MayHaveTrailingReturnType = false);
2774   TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2775                               bool mayHaveDirectInit = false,
2776                               bool mayHaveTrailingReturnType = false);
2777   TPResult TryParseParameterDeclarationClause(
2778       bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false,
2779       ImplicitTypenameContext AllowImplicitTypename =
2780           ImplicitTypenameContext::No);
2781   TPResult TryParseFunctionDeclarator(bool MayHaveTrailingReturnType = false);
2782   bool NameAfterArrowIsNonType();
2783   TPResult TryParseBracketDeclarator();
2784   TPResult TryConsumeDeclarationSpecifier();
2785 
2786   /// Try to skip a possibly empty sequence of 'attribute-specifier's without
2787   /// full validation of the syntactic structure of attributes.
2788   bool TrySkipAttributes();
2789 
2790   /// Diagnoses use of _ExtInt as being deprecated, and diagnoses use of
2791   /// _BitInt as an extension when appropriate.
2792   void DiagnoseBitIntUse(const Token &Tok);
2793 
2794 public:
2795   TypeResult
2796   ParseTypeName(SourceRange *Range = nullptr,
2797                 DeclaratorContext Context = DeclaratorContext::TypeName,
2798                 AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
2799                 ParsedAttributes *Attrs = nullptr);
2800 
2801 private:
2802   void ParseBlockId(SourceLocation CaretLoc);
2803 
2804   /// Return true if the next token should be treated as a [[]] attribute,
2805   /// or as a keyword that behaves like one.  The former is only true if
2806   /// [[]] attributes are enabled, whereas the latter is true whenever
2807   /// such a keyword appears.  The arguments are as for
2808   /// isCXX11AttributeSpecifier.
2809   bool isAllowedCXX11AttributeSpecifier(bool Disambiguate = false,
2810                                         bool OuterMightBeMessageSend = false) {
2811     return (Tok.isRegularKeywordAttribute() ||
2812             isCXX11AttributeSpecifier(Disambiguate, OuterMightBeMessageSend));
2813   }
2814 
2815   // Check for the start of an attribute-specifier-seq in a context where an
2816   // attribute is not allowed.
2817   bool CheckProhibitedCXX11Attribute() {
2818     assert(Tok.is(tok::l_square));
2819     if (NextToken().isNot(tok::l_square))
2820       return false;
2821     return DiagnoseProhibitedCXX11Attribute();
2822   }
2823 
2824   bool DiagnoseProhibitedCXX11Attribute();
2825   void CheckMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2826                                     SourceLocation CorrectLocation) {
2827     if (!Tok.isRegularKeywordAttribute() &&
2828         (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2829         Tok.isNot(tok::kw_alignas))
2830       return;
2831     DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2832   }
2833   void DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
2834                                        SourceLocation CorrectLocation);
2835 
2836   void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
2837                                       TagUseKind TUK);
2838 
2839   // FixItLoc = possible correct location for the attributes
2840   void ProhibitAttributes(ParsedAttributes &Attrs,
2841                           SourceLocation FixItLoc = SourceLocation()) {
2842     if (Attrs.Range.isInvalid())
2843       return;
2844     DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2845     Attrs.clear();
2846   }
2847 
2848   void ProhibitAttributes(ParsedAttributesView &Attrs,
2849                           SourceLocation FixItLoc = SourceLocation()) {
2850     if (Attrs.Range.isInvalid())
2851       return;
2852     DiagnoseProhibitedAttributes(Attrs, FixItLoc);
2853     Attrs.clearListOnly();
2854   }
2855   void DiagnoseProhibitedAttributes(const ParsedAttributesView &Attrs,
2856                                     SourceLocation FixItLoc);
2857 
2858   // Forbid C++11 and C23 attributes that appear on certain syntactic locations
2859   // which standard permits but we don't supported yet, for example, attributes
2860   // appertain to decl specifiers.
2861   // For the most cases we don't want to warn on unknown type attributes, but
2862   // left them to later diagnoses. However, for a few cases like module
2863   // declarations and module import declarations, we should do it.
2864   void ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned AttrDiagID,
2865                                unsigned KeywordDiagId,
2866                                bool DiagnoseEmptyAttrs = false,
2867                                bool WarnOnUnknownAttrs = false);
2868 
2869   /// Skip C++11 and C23 attributes and return the end location of the
2870   /// last one.
2871   /// \returns SourceLocation() if there are no attributes.
2872   SourceLocation SkipCXX11Attributes();
2873 
2874   /// Diagnose and skip C++11 and C23 attributes that appear in syntactic
2875   /// locations where attributes are not allowed.
2876   void DiagnoseAndSkipCXX11Attributes();
2877 
2878   /// Emit warnings for C++11 and C23 attributes that are in a position that
2879   /// clang accepts as an extension.
2880   void DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs);
2881 
2882   ExprResult ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName);
2883 
2884   bool
2885   ParseAttributeArgumentList(const clang::IdentifierInfo &AttrName,
2886                              SmallVectorImpl<Expr *> &Exprs,
2887                              ParsedAttributeArgumentsProperties ArgsProperties);
2888 
2889   /// Parses syntax-generic attribute arguments for attributes which are
2890   /// known to the implementation, and adds them to the given ParsedAttributes
2891   /// list with the given attribute syntax. Returns the number of arguments
2892   /// parsed for the attribute.
2893   unsigned
2894   ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2895                            ParsedAttributes &Attrs, SourceLocation *EndLoc,
2896                            IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2897                            ParsedAttr::Form Form);
2898 
2899   enum ParseAttrKindMask {
2900     PAKM_GNU = 1 << 0,
2901     PAKM_Declspec = 1 << 1,
2902     PAKM_CXX11 = 1 << 2,
2903   };
2904 
2905   /// \brief Parse attributes based on what syntaxes are desired, allowing for
2906   /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2907   /// __attribute__((...)) __declspec(...) __attribute__((...)))
2908   /// Note that Microsoft attributes (spelled with single square brackets) are
2909   /// not supported by this because of parsing ambiguities with other
2910   /// constructs.
2911   ///
2912   /// There are some attribute parse orderings that should not be allowed in
2913   /// arbitrary order. e.g.,
2914   ///
2915   ///   [[]] __attribute__(()) int i; // OK
2916   ///   __attribute__(()) [[]] int i; // Not OK
2917   ///
2918   /// Such situations should use the specific attribute parsing functionality.
2919   void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2920                        LateParsedAttrList *LateAttrs = nullptr);
2921   /// \brief Possibly parse attributes based on what syntaxes are desired,
2922   /// allowing for the order to vary.
2923   bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2924                             LateParsedAttrList *LateAttrs = nullptr) {
2925     if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2926         isAllowedCXX11AttributeSpecifier()) {
2927       ParseAttributes(WhichAttrKinds, Attrs, LateAttrs);
2928       return true;
2929     }
2930     return false;
2931   }
2932 
2933   void MaybeParseGNUAttributes(Declarator &D,
2934                                LateParsedAttrList *LateAttrs = nullptr) {
2935     if (Tok.is(tok::kw___attribute)) {
2936       ParsedAttributes Attrs(AttrFactory);
2937       ParseGNUAttributes(Attrs, LateAttrs, &D);
2938       D.takeAttributes(Attrs);
2939     }
2940   }
2941 
2942   bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2943                                LateParsedAttrList *LateAttrs = nullptr) {
2944     if (Tok.is(tok::kw___attribute)) {
2945       ParseGNUAttributes(Attrs, LateAttrs);
2946       return true;
2947     }
2948     return false;
2949   }
2950 
2951   bool ParseSingleGNUAttribute(ParsedAttributes &Attrs, SourceLocation &EndLoc,
2952                                LateParsedAttrList *LateAttrs = nullptr,
2953                                Declarator *D = nullptr);
2954   void ParseGNUAttributes(ParsedAttributes &Attrs,
2955                           LateParsedAttrList *LateAttrs = nullptr,
2956                           Declarator *D = nullptr);
2957   void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2958                              SourceLocation AttrNameLoc,
2959                              ParsedAttributes &Attrs, SourceLocation *EndLoc,
2960                              IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2961                              ParsedAttr::Form Form, Declarator *D);
2962   IdentifierLoc *ParseIdentifierLoc();
2963 
2964   unsigned
2965   ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2966                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
2967                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2968                           ParsedAttr::Form Form);
2969 
2970   void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) {
2971     // If parsing the attributes found an OpenMP directive, emit those tokens
2972     // to the parse stream now.
2973     if (!OpenMPTokens.empty()) {
2974       PP.EnterToken(Tok, /*IsReinject*/ true);
2975       PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true,
2976                           /*IsReinject*/ true);
2977       ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true);
2978     }
2979   }
2980   void MaybeParseCXX11Attributes(Declarator &D) {
2981     if (isAllowedCXX11AttributeSpecifier()) {
2982       ParsedAttributes Attrs(AttrFactory);
2983       ParseCXX11Attributes(Attrs);
2984       D.takeAttributes(Attrs);
2985     }
2986   }
2987 
2988   bool MaybeParseCXX11Attributes(ParsedAttributes &Attrs,
2989                                  bool OuterMightBeMessageSend = false) {
2990     if (isAllowedCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2991       ParseCXX11Attributes(Attrs);
2992       return true;
2993     }
2994     return false;
2995   }
2996 
2997   void ParseOpenMPAttributeArgs(const IdentifierInfo *AttrName,
2998                                 CachedTokens &OpenMPTokens);
2999 
3000   void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
3001                                             CachedTokens &OpenMPTokens,
3002                                             SourceLocation *EndLoc = nullptr);
3003   void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs,
3004                                     SourceLocation *EndLoc = nullptr) {
3005     CachedTokens OpenMPTokens;
3006     ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc);
3007     ReplayOpenMPAttributeTokens(OpenMPTokens);
3008   }
3009   void ParseCXX11Attributes(ParsedAttributes &attrs);
3010   /// Parses a C++11 (or C23)-style attribute argument list. Returns true
3011   /// if this results in adding an attribute to the ParsedAttributes list.
3012   bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3013                                SourceLocation AttrNameLoc,
3014                                ParsedAttributes &Attrs, SourceLocation *EndLoc,
3015                                IdentifierInfo *ScopeName,
3016                                SourceLocation ScopeLoc,
3017                                CachedTokens &OpenMPTokens);
3018 
3019   /// Parse a C++23 assume() attribute. Returns true on error.
3020   bool ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs,
3021                                   IdentifierInfo *AttrName,
3022                                   SourceLocation AttrNameLoc,
3023                                   SourceLocation *EndLoc,
3024                                   ParsedAttr::Form Form);
3025 
3026   IdentifierInfo *TryParseCXX11AttributeIdentifier(
3027       SourceLocation &Loc,
3028       SemaCodeCompletion::AttributeCompletion Completion =
3029           SemaCodeCompletion::AttributeCompletion::None,
3030       const IdentifierInfo *EnclosingScope = nullptr);
3031 
3032   bool MaybeParseHLSLAnnotations(Declarator &D,
3033                                  SourceLocation *EndLoc = nullptr,
3034                                  bool CouldBeBitField = false) {
3035     assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3036     if (Tok.is(tok::colon)) {
3037       ParsedAttributes Attrs(AttrFactory);
3038       ParseHLSLAnnotations(Attrs, EndLoc, CouldBeBitField);
3039       D.takeAttributes(Attrs);
3040       return true;
3041     }
3042     return false;
3043   }
3044 
3045   void MaybeParseHLSLAnnotations(ParsedAttributes &Attrs,
3046                                  SourceLocation *EndLoc = nullptr) {
3047     assert(getLangOpts().HLSL && "MaybeParseHLSLAnnotations is for HLSL only");
3048     if (Tok.is(tok::colon))
3049       ParseHLSLAnnotations(Attrs, EndLoc);
3050   }
3051 
3052   void ParseHLSLAnnotations(ParsedAttributes &Attrs,
3053                             SourceLocation *EndLoc = nullptr,
3054                             bool CouldBeBitField = false);
3055   Decl *ParseHLSLBuffer(SourceLocation &DeclEnd);
3056 
3057   void MaybeParseMicrosoftAttributes(ParsedAttributes &Attrs) {
3058     if ((getLangOpts().MicrosoftExt || getLangOpts().HLSL) &&
3059         Tok.is(tok::l_square)) {
3060       ParsedAttributes AttrsWithRange(AttrFactory);
3061       ParseMicrosoftAttributes(AttrsWithRange);
3062       Attrs.takeAllFrom(AttrsWithRange);
3063     }
3064   }
3065   void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
3066   void ParseMicrosoftAttributes(ParsedAttributes &Attrs);
3067   bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
3068     if (getLangOpts().DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
3069       ParseMicrosoftDeclSpecs(Attrs);
3070       return true;
3071     }
3072     return false;
3073   }
3074   void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs);
3075   bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
3076                                   SourceLocation AttrNameLoc,
3077                                   ParsedAttributes &Attrs);
3078   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
3079   void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &Attrs);
3080   void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
3081   SourceLocation SkipExtendedMicrosoftTypeAttributes();
3082   void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
3083   void ParseNullabilityClassAttributes(ParsedAttributes &attrs);
3084   void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
3085   void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
3086   void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
3087   void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
3088   void ParseCUDAFunctionAttributes(ParsedAttributes &attrs);
3089   bool isHLSLQualifier(const Token &Tok) const;
3090   void ParseHLSLQualifiers(ParsedAttributes &Attrs);
3091 
3092   VersionTuple ParseVersionTuple(SourceRange &Range);
3093   void ParseAvailabilityAttribute(IdentifierInfo &Availability,
3094                                   SourceLocation AvailabilityLoc,
3095                                   ParsedAttributes &attrs,
3096                                   SourceLocation *endLoc,
3097                                   IdentifierInfo *ScopeName,
3098                                   SourceLocation ScopeLoc,
3099                                   ParsedAttr::Form Form);
3100 
3101   std::optional<AvailabilitySpec> ParseAvailabilitySpec();
3102   ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
3103 
3104   void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
3105                                           SourceLocation Loc,
3106                                           ParsedAttributes &Attrs,
3107                                           SourceLocation *EndLoc,
3108                                           IdentifierInfo *ScopeName,
3109                                           SourceLocation ScopeLoc,
3110                                           ParsedAttr::Form Form);
3111 
3112   void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
3113                                        SourceLocation ObjCBridgeRelatedLoc,
3114                                        ParsedAttributes &Attrs,
3115                                        SourceLocation *EndLoc,
3116                                        IdentifierInfo *ScopeName,
3117                                        SourceLocation ScopeLoc,
3118                                        ParsedAttr::Form Form);
3119 
3120   void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
3121                                   SourceLocation AttrNameLoc,
3122                                   ParsedAttributes &Attrs,
3123                                   SourceLocation *EndLoc,
3124                                   IdentifierInfo *ScopeName,
3125                                   SourceLocation ScopeLoc,
3126                                   ParsedAttr::Form Form);
3127 
3128   void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
3129                                         SourceLocation AttrNameLoc,
3130                                         ParsedAttributes &Attrs,
3131                                         SourceLocation *EndLoc,
3132                                         IdentifierInfo *ScopeName,
3133                                         SourceLocation ScopeLoc,
3134                                         ParsedAttr::Form Form);
3135 
3136   void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
3137                                  SourceLocation AttrNameLoc,
3138                                  ParsedAttributes &Attrs,
3139                                  IdentifierInfo *ScopeName,
3140                                  SourceLocation ScopeLoc,
3141                                  ParsedAttr::Form Form);
3142 
3143   void DistributeCLateParsedAttrs(Decl *Dcl, LateParsedAttrList *LateAttrs);
3144 
3145   void ParseBoundsAttribute(IdentifierInfo &AttrName,
3146                             SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
3147                             IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
3148                             ParsedAttr::Form Form);
3149 
3150   void ParseTypeofSpecifier(DeclSpec &DS);
3151   SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
3152   void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
3153                                          SourceLocation StartLoc,
3154                                          SourceLocation EndLoc);
3155   void ParseAtomicSpecifier(DeclSpec &DS);
3156 
3157   ExprResult ParseAlignArgument(StringRef KWName, SourceLocation Start,
3158                                 SourceLocation &EllipsisLoc, bool &IsType,
3159                                 ParsedType &Ty);
3160   void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3161                                SourceLocation *endLoc = nullptr);
3162   ExprResult ParseExtIntegerArgument();
3163 
3164   VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
3165   VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
3166     return isCXX11VirtSpecifier(Tok);
3167   }
3168   void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
3169                                           SourceLocation FriendLoc);
3170 
3171   bool isCXX11FinalKeyword() const;
3172   bool isClassCompatibleKeyword() const;
3173 
3174   /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
3175   /// enter a new C++ declarator scope and exit it when the function is
3176   /// finished.
3177   class DeclaratorScopeObj {
3178     Parser &P;
3179     CXXScopeSpec &SS;
3180     bool EnteredScope;
3181     bool CreatedScope;
3182   public:
3183     DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
3184       : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
3185 
3186     void EnterDeclaratorScope() {
3187       assert(!EnteredScope && "Already entered the scope!");
3188       assert(SS.isSet() && "C++ scope was not set!");
3189 
3190       CreatedScope = true;
3191       P.EnterScope(0); // Not a decl scope.
3192 
3193       if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
3194         EnteredScope = true;
3195     }
3196 
3197     ~DeclaratorScopeObj() {
3198       if (EnteredScope) {
3199         assert(SS.isSet() && "C++ scope was cleared ?");
3200         P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
3201       }
3202       if (CreatedScope)
3203         P.ExitScope();
3204     }
3205   };
3206 
3207   /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3208   void ParseDeclarator(Declarator &D);
3209   /// A function that parses a variant of direct-declarator.
3210   typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
3211   void ParseDeclaratorInternal(Declarator &D,
3212                                DirectDeclParseFunction DirectDeclParser);
3213 
3214   enum AttrRequirements {
3215     AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
3216     AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
3217     AR_GNUAttributesParsed = 1 << 1,
3218     AR_CXX11AttributesParsed = 1 << 2,
3219     AR_DeclspecAttributesParsed = 1 << 3,
3220     AR_AllAttributesParsed = AR_GNUAttributesParsed |
3221                              AR_CXX11AttributesParsed |
3222                              AR_DeclspecAttributesParsed,
3223     AR_VendorAttributesParsed = AR_GNUAttributesParsed |
3224                                 AR_DeclspecAttributesParsed
3225   };
3226 
3227   void ParseTypeQualifierListOpt(
3228       DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
3229       bool AtomicAllowed = true, bool IdentifierRequired = false,
3230       std::optional<llvm::function_ref<void()>> CodeCompletionHandler =
3231           std::nullopt);
3232   void ParseDirectDeclarator(Declarator &D);
3233   void ParseDecompositionDeclarator(Declarator &D);
3234   void ParseParenDeclarator(Declarator &D);
3235   void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs,
3236                                BalancedDelimiterTracker &Tracker,
3237                                bool IsAmbiguous, bool RequiresArg = false);
3238   void InitCXXThisScopeForDeclaratorIfRelevant(
3239       const Declarator &D, const DeclSpec &DS,
3240       std::optional<Sema::CXXThisScopeRAII> &ThisScope);
3241   bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
3242                          SourceLocation &RefQualifierLoc);
3243   bool isFunctionDeclaratorIdentifierList();
3244   void ParseFunctionDeclaratorIdentifierList(
3245          Declarator &D,
3246          SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
3247   void ParseParameterDeclarationClause(
3248       Declarator &D, ParsedAttributes &attrs,
3249       SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3250       SourceLocation &EllipsisLoc) {
3251     return ParseParameterDeclarationClause(
3252         D.getContext(), attrs, ParamInfo, EllipsisLoc,
3253         D.getCXXScopeSpec().isSet() &&
3254             D.isFunctionDeclaratorAFunctionDeclaration());
3255   }
3256   void ParseParameterDeclarationClause(
3257       DeclaratorContext DeclaratorContext, ParsedAttributes &attrs,
3258       SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
3259       SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration = false);
3260 
3261   void ParseBracketDeclarator(Declarator &D);
3262   void ParseMisplacedBracketDeclarator(Declarator &D);
3263   bool MaybeParseTypeTransformTypeSpecifier(DeclSpec &DS);
3264   DeclSpec::TST TypeTransformTokToDeclSpec();
3265 
3266   //===--------------------------------------------------------------------===//
3267   // C++ 7: Declarations [dcl.dcl]
3268 
3269   /// The kind of attribute specifier we have found.
3270   enum CXX11AttributeKind {
3271     /// This is not an attribute specifier.
3272     CAK_NotAttributeSpecifier,
3273     /// This should be treated as an attribute-specifier.
3274     CAK_AttributeSpecifier,
3275     /// The next tokens are '[[', but this is not an attribute-specifier. This
3276     /// is ill-formed by C++11 [dcl.attr.grammar]p6.
3277     CAK_InvalidAttributeSpecifier
3278   };
3279   CXX11AttributeKind
3280   isCXX11AttributeSpecifier(bool Disambiguate = false,
3281                             bool OuterMightBeMessageSend = false);
3282 
3283   void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3284 
3285   DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3286                                 SourceLocation &DeclEnd,
3287                                 SourceLocation InlineLoc = SourceLocation());
3288 
3289   struct InnerNamespaceInfo {
3290     SourceLocation NamespaceLoc;
3291     SourceLocation InlineLoc;
3292     SourceLocation IdentLoc;
3293     IdentifierInfo *Ident;
3294   };
3295   using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3296 
3297   void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3298                            unsigned int index, SourceLocation &InlineLoc,
3299                            ParsedAttributes &attrs,
3300                            BalancedDelimiterTracker &Tracker);
3301   Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3302   Decl *ParseExportDeclaration();
3303   DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3304       DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3305       SourceLocation &DeclEnd, ParsedAttributes &Attrs);
3306   Decl *ParseUsingDirective(DeclaratorContext Context,
3307                             SourceLocation UsingLoc,
3308                             SourceLocation &DeclEnd,
3309                             ParsedAttributes &attrs);
3310 
3311   struct UsingDeclarator {
3312     SourceLocation TypenameLoc;
3313     CXXScopeSpec SS;
3314     UnqualifiedId Name;
3315     SourceLocation EllipsisLoc;
3316 
3317     void clear() {
3318       TypenameLoc = EllipsisLoc = SourceLocation();
3319       SS.clear();
3320       Name.clear();
3321     }
3322   };
3323 
3324   bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3325   DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3326                                        const ParsedTemplateInfo &TemplateInfo,
3327                                        SourceLocation UsingLoc,
3328                                        SourceLocation &DeclEnd,
3329                                        ParsedAttributes &Attrs,
3330                                        AccessSpecifier AS = AS_none);
3331   Decl *ParseAliasDeclarationAfterDeclarator(
3332       const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3333       UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3334       ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3335 
3336   Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3337   Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3338                             SourceLocation AliasLoc, IdentifierInfo *Alias,
3339                             SourceLocation &DeclEnd);
3340 
3341   //===--------------------------------------------------------------------===//
3342   // C++ 9: classes [class] and C structs/unions.
3343   bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3344   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3345                            DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
3346                            AccessSpecifier AS, bool EnteringContext,
3347                            DeclSpecContext DSC, ParsedAttributes &Attributes);
3348   void SkipCXXMemberSpecification(SourceLocation StartLoc,
3349                                   SourceLocation AttrFixitLoc,
3350                                   unsigned TagType,
3351                                   Decl *TagDecl);
3352   void ParseCXXMemberSpecification(SourceLocation StartLoc,
3353                                    SourceLocation AttrFixitLoc,
3354                                    ParsedAttributes &Attrs, unsigned TagType,
3355                                    Decl *TagDecl);
3356   ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3357                                        SourceLocation &EqualLoc);
3358   bool
3359   ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3360                                             VirtSpecifiers &VS,
3361                                             ExprResult &BitfieldSize,
3362                                             LateParsedAttrList &LateAttrs);
3363   void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3364                                                                VirtSpecifiers &VS);
3365   DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3366       AccessSpecifier AS, ParsedAttributes &Attr,
3367       ParsedTemplateInfo &TemplateInfo,
3368       ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3369   DeclGroupPtrTy
3370   ParseCXXClassMemberDeclarationWithPragmas(AccessSpecifier &AS,
3371                                             ParsedAttributes &AccessAttrs,
3372                                             DeclSpec::TST TagType, Decl *Tag);
3373   void ParseConstructorInitializer(Decl *ConstructorDecl);
3374   MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3375   void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
3376                                       Decl *ThisDecl);
3377 
3378   //===--------------------------------------------------------------------===//
3379   // C++ 10: Derived classes [class.derived]
3380   TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3381                                     SourceLocation &EndLocation);
3382   void ParseBaseClause(Decl *ClassDecl);
3383   BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3384   AccessSpecifier getAccessSpecifierIfPresent() const;
3385 
3386   bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
3387                                     ParsedType ObjectType,
3388                                     bool ObjectHadErrors,
3389                                     SourceLocation TemplateKWLoc,
3390                                     IdentifierInfo *Name,
3391                                     SourceLocation NameLoc,
3392                                     bool EnteringContext,
3393                                     UnqualifiedId &Id,
3394                                     bool AssumeTemplateId);
3395   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
3396                                   ParsedType ObjectType,
3397                                   UnqualifiedId &Result);
3398 
3399   //===--------------------------------------------------------------------===//
3400   // OpenMP: Directives and clauses.
3401   /// Parse clauses for '#pragma omp declare simd'.
3402   DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
3403                                             CachedTokens &Toks,
3404                                             SourceLocation Loc);
3405 
3406   /// Parse a property kind into \p TIProperty for the selector set \p Set and
3407   /// selector \p Selector.
3408   void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
3409                                  llvm::omp::TraitSet Set,
3410                                  llvm::omp::TraitSelector Selector,
3411                                  llvm::StringMap<SourceLocation> &Seen);
3412 
3413   /// Parse a selector kind into \p TISelector for the selector set \p Set.
3414   void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
3415                                  llvm::omp::TraitSet Set,
3416                                  llvm::StringMap<SourceLocation> &Seen);
3417 
3418   /// Parse a selector set kind into \p TISet.
3419   void parseOMPTraitSetKind(OMPTraitSet &TISet,
3420                             llvm::StringMap<SourceLocation> &Seen);
3421 
3422   /// Parses an OpenMP context property.
3423   void parseOMPContextProperty(OMPTraitSelector &TISelector,
3424                                llvm::omp::TraitSet Set,
3425                                llvm::StringMap<SourceLocation> &Seen);
3426 
3427   /// Parses an OpenMP context selector.
3428   void parseOMPContextSelector(OMPTraitSelector &TISelector,
3429                                llvm::omp::TraitSet Set,
3430                                llvm::StringMap<SourceLocation> &SeenSelectors);
3431 
3432   /// Parses an OpenMP context selector set.
3433   void parseOMPContextSelectorSet(OMPTraitSet &TISet,
3434                                   llvm::StringMap<SourceLocation> &SeenSets);
3435 
3436   /// Parses OpenMP context selectors.
3437   bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
3438 
3439   /// Parse an 'append_args' clause for '#pragma omp declare variant'.
3440   bool parseOpenMPAppendArgs(SmallVectorImpl<OMPInteropInfo> &InteropInfos);
3441 
3442   /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
3443   /// if there was an error.
3444   bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
3445                                          OMPTraitInfo *ParentTI);
3446 
3447   /// Parse clauses for '#pragma omp declare variant'.
3448   void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
3449                                      SourceLocation Loc);
3450 
3451   /// Parse 'omp [begin] assume[s]' directive.
3452   void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
3453                                    SourceLocation Loc);
3454 
3455   /// Parse 'omp end assumes' directive.
3456   void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
3457 
3458   /// Parses clauses for directive.
3459   ///
3460   /// \param DKind Kind of current directive.
3461   /// \param clauses for current directive.
3462   /// \param start location for clauses of current directive
3463   void ParseOpenMPClauses(OpenMPDirectiveKind DKind,
3464                           SmallVectorImpl<clang::OMPClause *> &Clauses,
3465                           SourceLocation Loc);
3466 
3467   /// Parse clauses for '#pragma omp [begin] declare target'.
3468   void ParseOMPDeclareTargetClauses(SemaOpenMP::DeclareTargetContextInfo &DTCI);
3469 
3470   /// Parse '#pragma omp end declare target'.
3471   void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
3472                                          OpenMPDirectiveKind EndDKind,
3473                                          SourceLocation Loc);
3474 
3475   /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
3476   /// it is not the current token.
3477   void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
3478 
3479   /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
3480   /// that the "end" matching the "begin" directive of kind \p BeginKind was not
3481   /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
3482   /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
3483   void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
3484                             OpenMPDirectiveKind ExpectedKind,
3485                             OpenMPDirectiveKind FoundKind,
3486                             SourceLocation MatchingLoc,
3487                             SourceLocation FoundLoc,
3488                             bool SkipUntilOpenMPEnd);
3489 
3490   /// Parses declarative OpenMP directives.
3491   DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
3492       AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed = false,
3493       DeclSpec::TST TagType = DeclSpec::TST_unspecified,
3494       Decl *TagDecl = nullptr);
3495   /// Parse 'omp declare reduction' construct.
3496   DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
3497   /// Parses initializer for provided omp_priv declaration inside the reduction
3498   /// initializer.
3499   void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
3500 
3501   /// Parses 'omp declare mapper' directive.
3502   DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
3503   /// Parses variable declaration in 'omp declare mapper' directive.
3504   TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
3505                                              DeclarationName &Name,
3506                                              AccessSpecifier AS = AS_none);
3507 
3508   /// Tries to parse cast part of OpenMP array shaping operation:
3509   /// '[' expression ']' { '[' expression ']' } ')'.
3510   bool tryParseOpenMPArrayShapingCastPart();
3511 
3512   /// Parses simple list of variables.
3513   ///
3514   /// \param Kind Kind of the directive.
3515   /// \param Callback Callback function to be called for the list elements.
3516   /// \param AllowScopeSpecifier true, if the variables can have fully
3517   /// qualified names.
3518   ///
3519   bool ParseOpenMPSimpleVarList(
3520       OpenMPDirectiveKind Kind,
3521       const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
3522           Callback,
3523       bool AllowScopeSpecifier);
3524   /// Parses declarative or executable directive.
3525   ///
3526   /// \param StmtCtx The context in which we're parsing the directive.
3527   /// \param ReadDirectiveWithinMetadirective true if directive is within a
3528   /// metadirective and therefore ends on the closing paren.
3529   StmtResult ParseOpenMPDeclarativeOrExecutableDirective(
3530       ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective = false);
3531 
3532   /// Parses executable directive.
3533   ///
3534   /// \param StmtCtx The context in which we're parsing the directive.
3535   /// \param DKind The kind of the executable directive.
3536   /// \param Loc Source location of the beginning of the directive.
3537   /// \param ReadDirectiveWithinMetadirective true if directive is within a
3538   /// metadirective and therefore ends on the closing paren.
3539   StmtResult
3540   ParseOpenMPExecutableDirective(ParsedStmtContext StmtCtx,
3541                                  OpenMPDirectiveKind DKind, SourceLocation Loc,
3542                                  bool ReadDirectiveWithinMetadirective);
3543 
3544   /// Parses informational directive.
3545   ///
3546   /// \param StmtCtx The context in which we're parsing the directive.
3547   /// \param DKind The kind of the informational directive.
3548   /// \param Loc Source location of the beginning of the directive.
3549   /// \param ReadDirectiveWithinMetadirective true if directive is within a
3550   /// metadirective and therefore ends on the closing paren.
3551   StmtResult ParseOpenMPInformationalDirective(
3552       ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
3553       bool ReadDirectiveWithinMetadirective);
3554 
3555   /// Parses clause of kind \a CKind for directive of a kind \a Kind.
3556   ///
3557   /// \param DKind Kind of current directive.
3558   /// \param CKind Kind of current clause.
3559   /// \param FirstClause true, if this is the first clause of a kind \a CKind
3560   /// in current directive.
3561   ///
3562   OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
3563                                OpenMPClauseKind CKind, bool FirstClause);
3564   /// Parses clause with a single expression of a kind \a Kind.
3565   ///
3566   /// \param Kind Kind of current clause.
3567   /// \param ParseOnly true to skip the clause's semantic actions and return
3568   /// nullptr.
3569   ///
3570   OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3571                                          bool ParseOnly);
3572   /// Parses simple clause of a kind \a Kind.
3573   ///
3574   /// \param Kind Kind of current clause.
3575   /// \param ParseOnly true to skip the clause's semantic actions and return
3576   /// nullptr.
3577   ///
3578   OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
3579   /// Parses indirect clause
3580   /// \param ParseOnly true to skip the clause's semantic actions and return
3581   // false;
3582   bool ParseOpenMPIndirectClause(SemaOpenMP::DeclareTargetContextInfo &DTCI,
3583                                  bool ParseOnly);
3584   /// Parses clause with a single expression and an additional argument
3585   /// of a kind \a Kind.
3586   ///
3587   /// \param DKind Directive kind.
3588   /// \param Kind Kind of current clause.
3589   /// \param ParseOnly true to skip the clause's semantic actions and return
3590   /// nullptr.
3591   ///
3592   OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3593                                                 OpenMPClauseKind Kind,
3594                                                 bool ParseOnly);
3595 
3596   /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
3597   OMPClause *ParseOpenMPSizesClause();
3598 
3599   /// Parses the 'permutation' clause of a '#pragma omp interchange' directive.
3600   OMPClause *ParseOpenMPPermutationClause();
3601 
3602   /// Parses clause without any additional arguments.
3603   ///
3604   /// \param Kind Kind of current clause.
3605   /// \param ParseOnly true to skip the clause's semantic actions and return
3606   /// nullptr.
3607   ///
3608   OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
3609   /// Parses clause with the list of variables of a kind \a Kind.
3610   ///
3611   /// \param Kind Kind of current clause.
3612   /// \param ParseOnly true to skip the clause's semantic actions and return
3613   /// nullptr.
3614   ///
3615   OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3616                                       OpenMPClauseKind Kind, bool ParseOnly);
3617 
3618   /// Parses a clause consisting of a list of expressions.
3619   ///
3620   /// \param Kind          The clause to parse.
3621   /// \param ClauseNameLoc [out] The location of the clause name.
3622   /// \param OpenLoc       [out] The location of '('.
3623   /// \param CloseLoc      [out] The location of ')'.
3624   /// \param Exprs         [out] The parsed expressions.
3625   /// \param ReqIntConst   If true, each expression must be an integer constant.
3626   ///
3627   /// \return Whether the clause was parsed successfully.
3628   bool ParseOpenMPExprListClause(OpenMPClauseKind Kind,
3629                                  SourceLocation &ClauseNameLoc,
3630                                  SourceLocation &OpenLoc,
3631                                  SourceLocation &CloseLoc,
3632                                  SmallVectorImpl<Expr *> &Exprs,
3633                                  bool ReqIntConst = false);
3634 
3635   /// Parses and creates OpenMP 5.0 iterators expression:
3636   /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
3637   /// <range-specification> }+ ')'
3638   ExprResult ParseOpenMPIteratorsExpr();
3639 
3640   /// Parses allocators and traits in the context of the uses_allocator clause.
3641   /// Expected format:
3642   /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
3643   OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
3644 
3645   /// Parses the 'interop' parts of the 'append_args' and 'init' clauses.
3646   bool ParseOMPInteropInfo(OMPInteropInfo &InteropInfo, OpenMPClauseKind Kind);
3647 
3648   /// Parses clause with an interop variable of kind \a Kind.
3649   ///
3650   /// \param Kind Kind of current clause.
3651   /// \param ParseOnly true to skip the clause's semantic actions and return
3652   /// nullptr.
3653   //
3654   OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
3655 
3656   /// Parses a ompx_attribute clause
3657   ///
3658   /// \param ParseOnly true to skip the clause's semantic actions and return
3659   /// nullptr.
3660   //
3661   OMPClause *ParseOpenMPOMPXAttributesClause(bool ParseOnly);
3662 
3663 public:
3664   /// Parses simple expression in parens for single-expression clauses of OpenMP
3665   /// constructs.
3666   /// \param RLoc Returned location of right paren.
3667   ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
3668                                    bool IsAddressOfOperand = false);
3669 
3670   /// Parses a reserved locator like 'omp_all_memory'.
3671   bool ParseOpenMPReservedLocator(OpenMPClauseKind Kind,
3672                                   SemaOpenMP::OpenMPVarListDataTy &Data,
3673                                   const LangOptions &LangOpts);
3674   /// Parses clauses with list.
3675   bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
3676                           SmallVectorImpl<Expr *> &Vars,
3677                           SemaOpenMP::OpenMPVarListDataTy &Data);
3678   bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
3679                           bool ObjectHadErrors, bool EnteringContext,
3680                           bool AllowDestructorName, bool AllowConstructorName,
3681                           bool AllowDeductionGuide,
3682                           SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
3683 
3684   /// Parses the mapper modifier in map, to, and from clauses.
3685   bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data);
3686   /// Parses map-type-modifiers in map clause.
3687   /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3688   /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3689   bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data);
3690 
3691   //===--------------------------------------------------------------------===//
3692   // OpenACC Parsing.
3693 
3694   /// Placeholder for now, should just ignore the directives after emitting a
3695   /// diagnostic. Eventually will be split into a few functions to parse
3696   /// different situations.
3697 public:
3698   DeclGroupPtrTy ParseOpenACCDirectiveDecl();
3699   StmtResult ParseOpenACCDirectiveStmt();
3700 
3701 private:
3702   /// A struct to hold the information that got parsed by ParseOpenACCDirective,
3703   /// so that the callers of it can use that to construct the appropriate AST
3704   /// nodes.
3705   struct OpenACCDirectiveParseInfo {
3706     OpenACCDirectiveKind DirKind;
3707     SourceLocation StartLoc;
3708     SourceLocation DirLoc;
3709     SourceLocation LParenLoc;
3710     SourceLocation RParenLoc;
3711     SourceLocation EndLoc;
3712     SourceLocation MiscLoc;
3713     SmallVector<Expr *> Exprs;
3714     SmallVector<OpenACCClause *> Clauses;
3715     // TODO OpenACC: As we implement support for the Atomic, Routine, and Cache
3716     // constructs, we likely want to put that information in here as well.
3717   };
3718 
3719   struct OpenACCWaitParseInfo {
3720     bool Failed = false;
3721     Expr *DevNumExpr = nullptr;
3722     SourceLocation QueuesLoc;
3723     SmallVector<Expr *> QueueIdExprs;
3724 
3725     SmallVector<Expr *> getAllExprs() {
3726       SmallVector<Expr *> Out;
3727       Out.push_back(DevNumExpr);
3728       Out.insert(Out.end(), QueueIdExprs.begin(), QueueIdExprs.end());
3729       return Out;
3730     }
3731   };
3732 
3733   /// Represents the 'error' state of parsing an OpenACC Clause, and stores
3734   /// whether we can continue parsing, or should give up on the directive.
3735   enum class OpenACCParseCanContinue { Cannot = 0, Can = 1 };
3736 
3737   /// A type to represent the state of parsing an OpenACC Clause. Situations
3738   /// that result in an OpenACCClause pointer are a success and can continue
3739   /// parsing, however some other situations can also continue.
3740   /// FIXME: This is better represented as a std::expected when we get C++23.
3741   using OpenACCClauseParseResult =
3742       llvm::PointerIntPair<OpenACCClause *, 1, OpenACCParseCanContinue>;
3743 
3744   OpenACCClauseParseResult OpenACCCanContinue();
3745   OpenACCClauseParseResult OpenACCCannotContinue();
3746   OpenACCClauseParseResult OpenACCSuccess(OpenACCClause *Clause);
3747 
3748   /// Parses the OpenACC directive (the entire pragma) including the clause
3749   /// list, but does not produce the main AST node.
3750   OpenACCDirectiveParseInfo ParseOpenACCDirective();
3751   /// Helper that parses an ID Expression based on the language options.
3752   ExprResult ParseOpenACCIDExpression();
3753   /// Parses the variable list for the `cache` construct.
3754   void ParseOpenACCCacheVarList();
3755 
3756   using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
3757   /// Parses a single variable in a variable list for OpenACC.
3758   OpenACCVarParseResult ParseOpenACCVar(OpenACCClauseKind CK);
3759   /// Parses the variable list for the variety of places that take a var-list.
3760   llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCClauseKind CK);
3761   /// Parses any parameters for an OpenACC Clause, including required/optional
3762   /// parens.
3763   OpenACCClauseParseResult
3764   ParseOpenACCClauseParams(ArrayRef<const OpenACCClause *> ExistingClauses,
3765                            OpenACCDirectiveKind DirKind, OpenACCClauseKind Kind,
3766                            SourceLocation ClauseLoc);
3767   /// Parses a single clause in a clause-list for OpenACC. Returns nullptr on
3768   /// error.
3769   OpenACCClauseParseResult
3770   ParseOpenACCClause(ArrayRef<const OpenACCClause *> ExistingClauses,
3771                      OpenACCDirectiveKind DirKind);
3772   /// Parses the clause-list for an OpenACC directive.
3773   SmallVector<OpenACCClause *>
3774   ParseOpenACCClauseList(OpenACCDirectiveKind DirKind);
3775   OpenACCWaitParseInfo ParseOpenACCWaitArgument(SourceLocation Loc,
3776                                                 bool IsDirective);
3777   /// Parses the clause of the 'bind' argument, which can be a string literal or
3778   /// an ID expression.
3779   ExprResult ParseOpenACCBindClauseArgument();
3780 
3781   /// A type to represent the state of parsing after an attempt to parse an
3782   /// OpenACC int-expr. This is useful to determine whether an int-expr list can
3783   /// continue parsing after a failed int-expr.
3784   using OpenACCIntExprParseResult =
3785       std::pair<ExprResult, OpenACCParseCanContinue>;
3786   /// Parses the clause kind of 'int-expr', which can be any integral
3787   /// expression.
3788   OpenACCIntExprParseResult ParseOpenACCIntExpr(OpenACCDirectiveKind DK,
3789                                                 OpenACCClauseKind CK,
3790                                                 SourceLocation Loc);
3791   /// Parses the argument list for 'num_gangs', which allows up to 3
3792   /// 'int-expr's.
3793   bool ParseOpenACCIntExprList(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
3794                                SourceLocation Loc,
3795                                llvm::SmallVectorImpl<Expr *> &IntExprs);
3796   /// Parses the 'device-type-list', which is a list of identifiers.
3797   bool ParseOpenACCDeviceTypeList(
3798       llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>> &Archs);
3799   /// Parses the 'async-argument', which is an integral value with two
3800   /// 'special' values that are likely negative (but come from Macros).
3801   OpenACCIntExprParseResult ParseOpenACCAsyncArgument(OpenACCDirectiveKind DK,
3802                                                       OpenACCClauseKind CK,
3803                                                       SourceLocation Loc);
3804 
3805   /// Parses the 'size-expr', which is an integral value, or an asterisk.
3806   /// Asterisk is represented by a OpenACCAsteriskSizeExpr
3807   ExprResult ParseOpenACCSizeExpr(OpenACCClauseKind CK);
3808   /// Parses a comma delimited list of 'size-expr's.
3809   bool ParseOpenACCSizeExprList(OpenACCClauseKind CK,
3810                                 llvm::SmallVectorImpl<Expr *> &SizeExprs);
3811   /// Parses a 'gang-arg-list', used for the 'gang' clause.
3812   bool ParseOpenACCGangArgList(SourceLocation GangLoc,
3813                                llvm::SmallVectorImpl<OpenACCGangKind> &GKs,
3814                                llvm::SmallVectorImpl<Expr *> &IntExprs);
3815 
3816   using OpenACCGangArgRes = std::pair<OpenACCGangKind, ExprResult>;
3817   /// Parses a 'gang-arg', used for the 'gang' clause. Returns a pair of the
3818   /// ExprResult (which contains the validity of the expression), plus the gang
3819   /// kind for the current argument.
3820   OpenACCGangArgRes ParseOpenACCGangArg(SourceLocation GangLoc);
3821   /// Parses a 'condition' expr, ensuring it results in a
3822   ExprResult ParseOpenACCConditionExpr();
3823 
3824 private:
3825   //===--------------------------------------------------------------------===//
3826   // C++ 14: Templates [temp]
3827 
3828   // C++ 14.1: Template Parameters [temp.param]
3829   DeclGroupPtrTy
3830   ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
3831                                        SourceLocation &DeclEnd,
3832                                        ParsedAttributes &AccessAttrs);
3833   DeclGroupPtrTy ParseTemplateDeclarationOrSpecialization(
3834       DeclaratorContext Context, SourceLocation &DeclEnd,
3835       ParsedAttributes &AccessAttrs, AccessSpecifier AS);
3836   DeclGroupPtrTy ParseDeclarationAfterTemplate(
3837       DeclaratorContext Context, ParsedTemplateInfo &TemplateInfo,
3838       ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
3839       ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
3840   bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
3841                                SmallVectorImpl<NamedDecl *> &TemplateParams,
3842                                SourceLocation &LAngleLoc,
3843                                SourceLocation &RAngleLoc);
3844   bool ParseTemplateParameterList(unsigned Depth,
3845                                   SmallVectorImpl<NamedDecl*> &TemplateParams);
3846   TPResult isStartOfTemplateTypeParameter();
3847   NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
3848   NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
3849   NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
3850   NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
3851   bool isTypeConstraintAnnotation();
3852   bool TryAnnotateTypeConstraint();
3853   void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
3854                                  SourceLocation CorrectLoc,
3855                                  bool AlreadyHasEllipsis,
3856                                  bool IdentifierHasName);
3857   void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
3858                                              Declarator &D);
3859   // C++ 14.3: Template arguments [temp.arg]
3860   typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
3861 
3862   bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
3863                                       SourceLocation &RAngleLoc,
3864                                       bool ConsumeLastToken,
3865                                       bool ObjCGenericList);
3866   bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3867                                         SourceLocation &LAngleLoc,
3868                                         TemplateArgList &TemplateArgs,
3869                                         SourceLocation &RAngleLoc,
3870                                         TemplateTy NameHint = nullptr);
3871 
3872   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3873                                CXXScopeSpec &SS,
3874                                SourceLocation TemplateKWLoc,
3875                                UnqualifiedId &TemplateName,
3876                                bool AllowTypeAnnotation = true,
3877                                bool TypeConstraint = false);
3878   void
3879   AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
3880                                 ImplicitTypenameContext AllowImplicitTypename,
3881                                 bool IsClassName = false);
3882   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
3883                                  TemplateTy Template, SourceLocation OpenLoc);
3884   ParsedTemplateArgument ParseTemplateTemplateArgument();
3885   ParsedTemplateArgument ParseTemplateArgument();
3886   DeclGroupPtrTy ParseExplicitInstantiation(DeclaratorContext Context,
3887                                             SourceLocation ExternLoc,
3888                                             SourceLocation TemplateLoc,
3889                                             SourceLocation &DeclEnd,
3890                                             ParsedAttributes &AccessAttrs,
3891                                             AccessSpecifier AS = AS_none);
3892   // C++2a: Template, concept definition [temp]
3893   Decl *
3894   ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
3895                          SourceLocation &DeclEnd);
3896 
3897   /// Parse the given string as a type.
3898   ///
3899   /// This is a dangerous utility function currently employed only by API notes.
3900   /// It is not a general entry-point for safely parsing types from strings.
3901   ///
3902   /// \param TypeStr The string to be parsed as a type.
3903   /// \param Context The name of the context in which this string is being
3904   /// parsed, which will be used in diagnostics.
3905   /// \param IncludeLoc The location at which this parse was triggered.
3906   TypeResult ParseTypeFromString(StringRef TypeStr, StringRef Context,
3907                                  SourceLocation IncludeLoc);
3908 
3909   //===--------------------------------------------------------------------===//
3910   // Modules
3911   DeclGroupPtrTy ParseModuleDecl(Sema::ModuleImportState &ImportState);
3912   Decl *ParseModuleImport(SourceLocation AtLoc,
3913                           Sema::ModuleImportState &ImportState);
3914   bool parseMisplacedModuleImport();
3915   bool tryParseMisplacedModuleImport() {
3916     tok::TokenKind Kind = Tok.getKind();
3917     if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
3918         Kind == tok::annot_module_include)
3919       return parseMisplacedModuleImport();
3920     return false;
3921   }
3922 
3923   bool ParseModuleName(
3924       SourceLocation UseLoc,
3925       SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3926       bool IsImport);
3927 
3928   //===--------------------------------------------------------------------===//
3929   // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3930   ExprResult ParseTypeTrait();
3931 
3932   //===--------------------------------------------------------------------===//
3933   // Embarcadero: Arary and Expression Traits
3934   ExprResult ParseArrayTypeTrait();
3935   ExprResult ParseExpressionTrait();
3936 
3937   ExprResult ParseBuiltinPtrauthTypeDiscriminator();
3938 
3939   //===--------------------------------------------------------------------===//
3940   // Preprocessor code-completion pass-through
3941   void CodeCompleteDirective(bool InConditional) override;
3942   void CodeCompleteInConditionalExclusion() override;
3943   void CodeCompleteMacroName(bool IsDefinition) override;
3944   void CodeCompletePreprocessorExpression() override;
3945   void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3946                                  unsigned ArgumentIndex) override;
3947   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3948   void CodeCompleteNaturalLanguage() override;
3949 
3950   class GNUAsmQualifiers {
3951     unsigned Qualifiers = AQ_unspecified;
3952 
3953   public:
3954     enum AQ {
3955       AQ_unspecified = 0,
3956       AQ_volatile    = 1,
3957       AQ_inline      = 2,
3958       AQ_goto        = 4,
3959     };
3960     static const char *getQualifierName(AQ Qualifier);
3961     bool setAsmQualifier(AQ Qualifier);
3962     inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
3963     inline bool isInline() const { return Qualifiers & AQ_inline; };
3964     inline bool isGoto() const { return Qualifiers & AQ_goto; }
3965   };
3966   bool isGCCAsmStatement(const Token &TokAfterAsm) const;
3967   bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
3968   GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
3969   bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
3970 };
3971 
3972 }  // end namespace clang
3973 
3974 #endif
3975