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