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