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