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