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