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