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