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