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