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