Home | History | Annotate | Download | only in Parse
      1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the Parser interface.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_PARSE_PARSER_H
     15 #define LLVM_CLANG_PARSE_PARSER_H
     16 
     17 #include "clang/AST/Availability.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/LoopHint.h"
     25 #include "clang/Sema/Sema.h"
     26 #include "llvm/ADT/SmallVector.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   class Parser;
     41   class ParsingDeclRAIIObject;
     42   class ParsingDeclSpec;
     43   class ParsingDeclarator;
     44   class ParsingFieldDeclarator;
     45   class ColonProtectionRAIIObject;
     46   class InMessageExpressionRAIIObject;
     47   class PoisonSEHIdentifiersRAIIObject;
     48   class VersionTuple;
     49   class OMPClause;
     50   class ObjCTypeParamList;
     51   class ObjCTypeParameter;
     52 
     53 /// Parser - This implements a parser for the C family of languages.  After
     54 /// parsing units of the grammar, productions are invoked to handle whatever has
     55 /// been read.
     56 ///
     57 class Parser : public CodeCompletionHandler {
     58   friend class ColonProtectionRAIIObject;
     59   friend class InMessageExpressionRAIIObject;
     60   friend class PoisonSEHIdentifiersRAIIObject;
     61   friend class ObjCDeclContextSwitch;
     62   friend class ParenBraceBracketBalancer;
     63   friend class BalancedDelimiterTracker;
     64 
     65   Preprocessor &PP;
     66 
     67   /// Tok - The current token we are peeking ahead.  All parsing methods assume
     68   /// that this is valid.
     69   Token Tok;
     70 
     71   // PrevTokLocation - The location of the token we previously
     72   // consumed. This token is used for diagnostics where we expected to
     73   // see a token following another token (e.g., the ';' at the end of
     74   // a statement).
     75   SourceLocation PrevTokLocation;
     76 
     77   unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
     78   unsigned short MisplacedModuleBeginCount = 0;
     79 
     80   /// Actions - These are the callbacks we invoke as we parse various constructs
     81   /// in the file.
     82   Sema &Actions;
     83 
     84   DiagnosticsEngine &Diags;
     85 
     86   /// ScopeCache - Cache scopes to reduce malloc traffic.
     87   enum { ScopeCacheSize = 16 };
     88   unsigned NumCachedScopes;
     89   Scope *ScopeCache[ScopeCacheSize];
     90 
     91   /// Identifiers used for SEH handling in Borland. These are only
     92   /// allowed in particular circumstances
     93   // __except block
     94   IdentifierInfo *Ident__exception_code,
     95                  *Ident___exception_code,
     96                  *Ident_GetExceptionCode;
     97   // __except filter expression
     98   IdentifierInfo *Ident__exception_info,
     99                  *Ident___exception_info,
    100                  *Ident_GetExceptionInfo;
    101   // __finally
    102   IdentifierInfo *Ident__abnormal_termination,
    103                  *Ident___abnormal_termination,
    104                  *Ident_AbnormalTermination;
    105 
    106   /// Contextual keywords for Microsoft extensions.
    107   IdentifierInfo *Ident__except;
    108   mutable IdentifierInfo *Ident_sealed;
    109 
    110   /// Ident_super - IdentifierInfo for "super", to support fast
    111   /// comparison.
    112   IdentifierInfo *Ident_super;
    113   /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
    114   /// "bool" fast comparison.  Only present if AltiVec or ZVector are enabled.
    115   IdentifierInfo *Ident_vector;
    116   IdentifierInfo *Ident_bool;
    117   /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
    118   /// Only present if AltiVec enabled.
    119   IdentifierInfo *Ident_pixel;
    120 
    121   /// Objective-C contextual keywords.
    122   mutable IdentifierInfo *Ident_instancetype;
    123 
    124   /// \brief Identifier for "introduced".
    125   IdentifierInfo *Ident_introduced;
    126 
    127   /// \brief Identifier for "deprecated".
    128   IdentifierInfo *Ident_deprecated;
    129 
    130   /// \brief Identifier for "obsoleted".
    131   IdentifierInfo *Ident_obsoleted;
    132 
    133   /// \brief Identifier for "unavailable".
    134   IdentifierInfo *Ident_unavailable;
    135 
    136   /// \brief Identifier for "message".
    137   IdentifierInfo *Ident_message;
    138 
    139   /// \brief Identifier for "strict".
    140   IdentifierInfo *Ident_strict;
    141 
    142   /// \brief Identifier for "replacement".
    143   IdentifierInfo *Ident_replacement;
    144 
    145   /// Identifiers used by the 'external_source_symbol' attribute.
    146   IdentifierInfo *Ident_language, *Ident_defined_in,
    147       *Ident_generated_declaration;
    148 
    149   /// C++0x contextual keywords.
    150   mutable IdentifierInfo *Ident_final;
    151   mutable IdentifierInfo *Ident_GNU_final;
    152   mutable IdentifierInfo *Ident_override;
    153 
    154   // C++ type trait keywords that can be reverted to identifiers and still be
    155   // used as type traits.
    156   llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
    157 
    158   std::unique_ptr<PragmaHandler> AlignHandler;
    159   std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
    160   std::unique_ptr<PragmaHandler> OptionsHandler;
    161   std::unique_ptr<PragmaHandler> PackHandler;
    162   std::unique_ptr<PragmaHandler> MSStructHandler;
    163   std::unique_ptr<PragmaHandler> UnusedHandler;
    164   std::unique_ptr<PragmaHandler> WeakHandler;
    165   std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
    166   std::unique_ptr<PragmaHandler> FPContractHandler;
    167   std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
    168   std::unique_ptr<PragmaHandler> OpenMPHandler;
    169   std::unique_ptr<PragmaHandler> PCSectionHandler;
    170   std::unique_ptr<PragmaHandler> MSCommentHandler;
    171   std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
    172   std::unique_ptr<PragmaHandler> MSPointersToMembers;
    173   std::unique_ptr<PragmaHandler> MSVtorDisp;
    174   std::unique_ptr<PragmaHandler> MSInitSeg;
    175   std::unique_ptr<PragmaHandler> MSDataSeg;
    176   std::unique_ptr<PragmaHandler> MSBSSSeg;
    177   std::unique_ptr<PragmaHandler> MSConstSeg;
    178   std::unique_ptr<PragmaHandler> MSCodeSeg;
    179   std::unique_ptr<PragmaHandler> MSSection;
    180   std::unique_ptr<PragmaHandler> MSRuntimeChecks;
    181   std::unique_ptr<PragmaHandler> MSIntrinsic;
    182   std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
    183   std::unique_ptr<PragmaHandler> OptimizeHandler;
    184   std::unique_ptr<PragmaHandler> LoopHintHandler;
    185   std::unique_ptr<PragmaHandler> UnrollHintHandler;
    186   std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
    187   std::unique_ptr<PragmaHandler> FPHandler;
    188   std::unique_ptr<PragmaHandler> AttributePragmaHandler;
    189 
    190   std::unique_ptr<CommentHandler> CommentSemaHandler;
    191 
    192   /// Whether the '>' token acts as an operator or not. This will be
    193   /// true except when we are parsing an expression within a C++
    194   /// template argument list, where the '>' closes the template
    195   /// argument list.
    196   bool GreaterThanIsOperator;
    197 
    198   /// ColonIsSacred - When this is false, we aggressively try to recover from
    199   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
    200   /// safe in case statements and a few other things.  This is managed by the
    201   /// ColonProtectionRAIIObject RAII object.
    202   bool ColonIsSacred;
    203 
    204   /// \brief When true, we are directly inside an Objective-C message
    205   /// send expression.
    206   ///
    207   /// This is managed by the \c InMessageExpressionRAIIObject class, and
    208   /// should not be set directly.
    209   bool InMessageExpression;
    210 
    211   /// The "depth" of the template parameters currently being parsed.
    212   unsigned TemplateParameterDepth;
    213 
    214   /// \brief RAII class that manages the template parameter depth.
    215   class TemplateParameterDepthRAII {
    216     unsigned &Depth;
    217     unsigned AddedLevels;
    218   public:
    219     explicit TemplateParameterDepthRAII(unsigned &Depth)
    220       : Depth(Depth), AddedLevels(0) {}
    221 
    222     ~TemplateParameterDepthRAII() {
    223       Depth -= AddedLevels;
    224     }
    225 
    226     void operator++() {
    227       ++Depth;
    228       ++AddedLevels;
    229     }
    230     void addDepth(unsigned D) {
    231       Depth += D;
    232       AddedLevels += D;
    233     }
    234     unsigned getDepth() const { return Depth; }
    235   };
    236 
    237   /// Factory object for creating AttributeList objects.
    238   AttributeFactory AttrFactory;
    239 
    240   /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
    241   /// top-level declaration is finished.
    242   SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
    243 
    244   /// \brief Identifiers which have been declared within a tentative parse.
    245   SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
    246 
    247   IdentifierInfo *getSEHExceptKeyword();
    248 
    249   /// True if we are within an Objective-C container while parsing C-like decls.
    250   ///
    251   /// This is necessary because Sema thinks we have left the container
    252   /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
    253   /// be NULL.
    254   bool ParsingInObjCContainer;
    255 
    256   bool SkipFunctionBodies;
    257 
    258   /// The location of the expression statement that is being parsed right now.
    259   /// Used to determine if an expression that is being parsed is a statement or
    260   /// just a regular sub-expression.
    261   SourceLocation ExprStatementTokLoc;
    262 
    263 public:
    264   Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
    265   ~Parser() override;
    266 
    267   const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
    268   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
    269   Preprocessor &getPreprocessor() const { return PP; }
    270   Sema &getActions() const { return Actions; }
    271   AttributeFactory &getAttrFactory() { return AttrFactory; }
    272 
    273   const Token &getCurToken() const { return Tok; }
    274   Scope *getCurScope() const { return Actions.getCurScope(); }
    275   void incrementMSManglingNumber() const {
    276     return Actions.incrementMSManglingNumber();
    277   }
    278 
    279   Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
    280 
    281   // Type forwarding.  All of these are statically 'void*', but they may all be
    282   // different actual classes based on the actions in place.
    283   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
    284   typedef OpaquePtr<TemplateName> TemplateTy;
    285 
    286   typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
    287 
    288   typedef Sema::FullExprArg FullExprArg;
    289 
    290   // Parsing methods.
    291 
    292   /// Initialize - Warm up the parser.
    293   ///
    294   void Initialize();
    295 
    296   /// Parse the first top-level declaration in a translation unit.
    297   bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
    298 
    299   /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
    300   /// the EOF was encountered.
    301   bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
    302   bool ParseTopLevelDecl() {
    303     DeclGroupPtrTy Result;
    304     return ParseTopLevelDecl(Result);
    305   }
    306 
    307   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
    308   /// This does not work with special tokens: string literals, code completion,
    309   /// annotation tokens and balanced tokens must be handled using the specific
    310   /// consume methods.
    311   /// Returns the location of the consumed token.
    312   SourceLocation ConsumeToken() {
    313     assert(!isTokenSpecial() &&
    314            "Should consume special tokens with Consume*Token");
    315     PrevTokLocation = Tok.getLocation();
    316     PP.Lex(Tok);
    317     return PrevTokLocation;
    318   }
    319 
    320   bool TryConsumeToken(tok::TokenKind Expected) {
    321     if (Tok.isNot(Expected))
    322       return false;
    323     assert(!isTokenSpecial() &&
    324            "Should consume special tokens with Consume*Token");
    325     PrevTokLocation = Tok.getLocation();
    326     PP.Lex(Tok);
    327     return true;
    328   }
    329 
    330   bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
    331     if (!TryConsumeToken(Expected))
    332       return false;
    333     Loc = PrevTokLocation;
    334     return true;
    335   }
    336 
    337   SourceLocation getEndOfPreviousToken() {
    338     return PP.getLocForEndOfToken(PrevTokLocation);
    339   }
    340 
    341   /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
    342   /// to the given nullability kind.
    343   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
    344     return Actions.getNullabilityKeyword(nullability);
    345   }
    346 
    347 private:
    348   //===--------------------------------------------------------------------===//
    349   // Low-Level token peeking and consumption methods.
    350   //
    351 
    352   /// isTokenParen - Return true if the cur token is '(' or ')'.
    353   bool isTokenParen() const {
    354     return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
    355   }
    356   /// isTokenBracket - Return true if the cur token is '[' or ']'.
    357   bool isTokenBracket() const {
    358     return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
    359   }
    360   /// isTokenBrace - Return true if the cur token is '{' or '}'.
    361   bool isTokenBrace() const {
    362     return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
    363   }
    364   /// isTokenStringLiteral - True if this token is a string-literal.
    365   bool isTokenStringLiteral() const {
    366     return tok::isStringLiteral(Tok.getKind());
    367   }
    368   /// isTokenSpecial - True if this token requires special consumption methods.
    369   bool isTokenSpecial() const {
    370     return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
    371            isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
    372   }
    373 
    374   /// \brief Returns true if the current token is '=' or is a type of '='.
    375   /// For typos, give a fixit to '='
    376   bool isTokenEqualOrEqualTypo();
    377 
    378   /// \brief Return the current token to the token stream and make the given
    379   /// token the current token.
    380   void UnconsumeToken(Token &Consumed) {
    381       Token Next = Tok;
    382       PP.EnterToken(Consumed);
    383       PP.Lex(Tok);
    384       PP.EnterToken(Next);
    385   }
    386 
    387   /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
    388   /// current token type.  This should only be used in cases where the type of
    389   /// the token really isn't known, e.g. in error recovery.
    390   SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
    391     if (isTokenParen())
    392       return ConsumeParen();
    393     if (isTokenBracket())
    394       return ConsumeBracket();
    395     if (isTokenBrace())
    396       return ConsumeBrace();
    397     if (isTokenStringLiteral())
    398       return ConsumeStringToken();
    399     if (Tok.is(tok::code_completion))
    400       return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
    401                                       : handleUnexpectedCodeCompletionToken();
    402     if (Tok.isAnnotation())
    403       return ConsumeAnnotationToken();
    404     return ConsumeToken();
    405   }
    406 
    407   SourceLocation ConsumeAnnotationToken() {
    408     assert(Tok.isAnnotation() && "wrong consume method");
    409     SourceLocation Loc = Tok.getLocation();
    410     PrevTokLocation = Tok.getAnnotationEndLoc();
    411     PP.Lex(Tok);
    412     return Loc;
    413   }
    414 
    415   /// ConsumeParen - This consume method keeps the paren count up-to-date.
    416   ///
    417   SourceLocation ConsumeParen() {
    418     assert(isTokenParen() && "wrong consume method");
    419     if (Tok.getKind() == tok::l_paren)
    420       ++ParenCount;
    421     else if (ParenCount)
    422       --ParenCount;       // Don't let unbalanced )'s drive the count negative.
    423     PrevTokLocation = Tok.getLocation();
    424     PP.Lex(Tok);
    425     return PrevTokLocation;
    426   }
    427 
    428   /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
    429   ///
    430   SourceLocation ConsumeBracket() {
    431     assert(isTokenBracket() && "wrong consume method");
    432     if (Tok.getKind() == tok::l_square)
    433       ++BracketCount;
    434     else if (BracketCount)
    435       --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
    436 
    437     PrevTokLocation = Tok.getLocation();
    438     PP.Lex(Tok);
    439     return PrevTokLocation;
    440   }
    441 
    442   /// ConsumeBrace - This consume method keeps the brace count up-to-date.
    443   ///
    444   SourceLocation ConsumeBrace() {
    445     assert(isTokenBrace() && "wrong consume method");
    446     if (Tok.getKind() == tok::l_brace)
    447       ++BraceCount;
    448     else if (BraceCount)
    449       --BraceCount;     // Don't let unbalanced }'s drive the count negative.
    450 
    451     PrevTokLocation = Tok.getLocation();
    452     PP.Lex(Tok);
    453     return PrevTokLocation;
    454   }
    455 
    456   /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
    457   /// and returning the token kind.  This method is specific to strings, as it
    458   /// handles string literal concatenation, as per C99 5.1.1.2, translation
    459   /// phase #6.
    460   SourceLocation ConsumeStringToken() {
    461     assert(isTokenStringLiteral() &&
    462            "Should only consume string literals with this method");
    463     PrevTokLocation = Tok.getLocation();
    464     PP.Lex(Tok);
    465     return PrevTokLocation;
    466   }
    467 
    468   /// \brief Consume the current code-completion token.
    469   ///
    470   /// This routine can be called to consume the code-completion token and
    471   /// continue processing in special cases where \c cutOffParsing() isn't
    472   /// desired, such as token caching or completion with lookahead.
    473   SourceLocation ConsumeCodeCompletionToken() {
    474     assert(Tok.is(tok::code_completion));
    475     PrevTokLocation = Tok.getLocation();
    476     PP.Lex(Tok);
    477     return PrevTokLocation;
    478   }
    479 
    480   ///\ brief When we are consuming a code-completion token without having
    481   /// matched specific position in the grammar, provide code-completion results
    482   /// based on context.
    483   ///
    484   /// \returns the source location of the code-completion token.
    485   SourceLocation handleUnexpectedCodeCompletionToken();
    486 
    487   /// \brief Abruptly cut off parsing; mainly used when we have reached the
    488   /// code-completion point.
    489   void cutOffParsing() {
    490     if (PP.isCodeCompletionEnabled())
    491       PP.setCodeCompletionReached();
    492     // Cut off parsing by acting as if we reached the end-of-file.
    493     Tok.setKind(tok::eof);
    494   }
    495 
    496   /// \brief Determine if we're at the end of the file or at a transition
    497   /// between modules.
    498   bool isEofOrEom() {
    499     tok::TokenKind Kind = Tok.getKind();
    500     return Kind == tok::eof || Kind == tok::annot_module_begin ||
    501            Kind == tok::annot_module_end || Kind == tok::annot_module_include;
    502   }
    503 
    504   /// \brief Initialize all pragma handlers.
    505   void initializePragmaHandlers();
    506 
    507   /// \brief Destroy and reset all pragma handlers.
    508   void resetPragmaHandlers();
    509 
    510   /// \brief Handle the annotation token produced for #pragma unused(...)
    511   void HandlePragmaUnused();
    512 
    513   /// \brief Handle the annotation token produced for
    514   /// #pragma GCC visibility...
    515   void HandlePragmaVisibility();
    516 
    517   /// \brief Handle the annotation token produced for
    518   /// #pragma pack...
    519   void HandlePragmaPack();
    520 
    521   /// \brief Handle the annotation token produced for
    522   /// #pragma ms_struct...
    523   void HandlePragmaMSStruct();
    524 
    525   /// \brief Handle the annotation token produced for
    526   /// #pragma comment...
    527   void HandlePragmaMSComment();
    528 
    529   void HandlePragmaMSPointersToMembers();
    530 
    531   void HandlePragmaMSVtorDisp();
    532 
    533   void HandlePragmaMSPragma();
    534   bool HandlePragmaMSSection(StringRef PragmaName,
    535                              SourceLocation PragmaLocation);
    536   bool HandlePragmaMSSegment(StringRef PragmaName,
    537                              SourceLocation PragmaLocation);
    538   bool HandlePragmaMSInitSeg(StringRef PragmaName,
    539                              SourceLocation PragmaLocation);
    540 
    541   /// \brief Handle the annotation token produced for
    542   /// #pragma align...
    543   void HandlePragmaAlign();
    544 
    545   /// \brief Handle the annotation token produced for
    546   /// #pragma clang __debug dump...
    547   void HandlePragmaDump();
    548 
    549   /// \brief Handle the annotation token produced for
    550   /// #pragma weak id...
    551   void HandlePragmaWeak();
    552 
    553   /// \brief Handle the annotation token produced for
    554   /// #pragma weak id = id...
    555   void HandlePragmaWeakAlias();
    556 
    557   /// \brief Handle the annotation token produced for
    558   /// #pragma redefine_extname...
    559   void HandlePragmaRedefineExtname();
    560 
    561   /// \brief Handle the annotation token produced for
    562   /// #pragma STDC FP_CONTRACT...
    563   void HandlePragmaFPContract();
    564 
    565   /// \brief Handle the annotation token produced for
    566   /// #pragma clang fp ...
    567   void HandlePragmaFP();
    568 
    569   /// \brief Handle the annotation token produced for
    570   /// #pragma OPENCL EXTENSION...
    571   void HandlePragmaOpenCLExtension();
    572 
    573   /// \brief Handle the annotation token produced for
    574   /// #pragma clang __debug captured
    575   StmtResult HandlePragmaCaptured();
    576 
    577   /// \brief Handle the annotation token produced for
    578   /// #pragma clang loop and #pragma unroll.
    579   bool HandlePragmaLoopHint(LoopHint &Hint);
    580 
    581   bool ParsePragmaAttributeSubjectMatchRuleSet(
    582       attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
    583       SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
    584 
    585   void HandlePragmaAttribute();
    586 
    587   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
    588   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
    589   /// returns the token after Tok, etc.
    590   ///
    591   /// Note that this differs from the Preprocessor's LookAhead method, because
    592   /// the Parser always has one token lexed that the preprocessor doesn't.
    593   ///
    594   const Token &GetLookAheadToken(unsigned N) {
    595     if (N == 0 || Tok.is(tok::eof)) return Tok;
    596     return PP.LookAhead(N-1);
    597   }
    598 
    599 public:
    600   /// NextToken - This peeks ahead one token and returns it without
    601   /// consuming it.
    602   const Token &NextToken() {
    603     return PP.LookAhead(0);
    604   }
    605 
    606   /// getTypeAnnotation - Read a parsed type out of an annotation token.
    607   static ParsedType getTypeAnnotation(Token &Tok) {
    608     return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
    609   }
    610 
    611 private:
    612   static void setTypeAnnotation(Token &Tok, ParsedType T) {
    613     Tok.setAnnotationValue(T.getAsOpaquePtr());
    614   }
    615 
    616   /// \brief Read an already-translated primary expression out of an annotation
    617   /// token.
    618   static ExprResult getExprAnnotation(Token &Tok) {
    619     return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
    620   }
    621 
    622   /// \brief Set the primary expression corresponding to the given annotation
    623   /// token.
    624   static void setExprAnnotation(Token &Tok, ExprResult ER) {
    625     Tok.setAnnotationValue(ER.getAsOpaquePointer());
    626   }
    627 
    628 public:
    629   // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
    630   // find a type name by attempting typo correction.
    631   bool TryAnnotateTypeOrScopeToken();
    632   bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
    633                                                  bool IsNewScope);
    634   bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
    635 
    636 private:
    637   enum AnnotatedNameKind {
    638     /// Annotation has failed and emitted an error.
    639     ANK_Error,
    640     /// The identifier is a tentatively-declared name.
    641     ANK_TentativeDecl,
    642     /// The identifier is a template name. FIXME: Add an annotation for that.
    643     ANK_TemplateName,
    644     /// The identifier can't be resolved.
    645     ANK_Unresolved,
    646     /// Annotation was successful.
    647     ANK_Success
    648   };
    649   AnnotatedNameKind
    650   TryAnnotateName(bool IsAddressOfOperand,
    651                   std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
    652 
    653   /// Push a tok::annot_cxxscope token onto the token stream.
    654   void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
    655 
    656   /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
    657   /// replacing them with the non-context-sensitive keywords.  This returns
    658   /// true if the token was replaced.
    659   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
    660                        const char *&PrevSpec, unsigned &DiagID,
    661                        bool &isInvalid) {
    662     if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
    663       return false;
    664 
    665     if (Tok.getIdentifierInfo() != Ident_vector &&
    666         Tok.getIdentifierInfo() != Ident_bool &&
    667         (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
    668       return false;
    669 
    670     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
    671   }
    672 
    673   /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
    674   /// identifier token, replacing it with the non-context-sensitive __vector.
    675   /// This returns true if the token was replaced.
    676   bool TryAltiVecVectorToken() {
    677     if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
    678         Tok.getIdentifierInfo() != Ident_vector) return false;
    679     return TryAltiVecVectorTokenOutOfLine();
    680   }
    681 
    682   bool TryAltiVecVectorTokenOutOfLine();
    683   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
    684                                 const char *&PrevSpec, unsigned &DiagID,
    685                                 bool &isInvalid);
    686 
    687   /// Returns true if the current token is the identifier 'instancetype'.
    688   ///
    689   /// Should only be used in Objective-C language modes.
    690   bool isObjCInstancetype() {
    691     assert(getLangOpts().ObjC1);
    692     if (Tok.isAnnotation())
    693       return false;
    694     if (!Ident_instancetype)
    695       Ident_instancetype = PP.getIdentifierInfo("instancetype");
    696     return Tok.getIdentifierInfo() == Ident_instancetype;
    697   }
    698 
    699   /// TryKeywordIdentFallback - For compatibility with system headers using
    700   /// keywords as identifiers, attempt to convert the current token to an
    701   /// identifier and optionally disable the keyword for the remainder of the
    702   /// translation unit. This returns false if the token was not replaced,
    703   /// otherwise emits a diagnostic and returns true.
    704   bool TryKeywordIdentFallback(bool DisableKeyword);
    705 
    706   /// \brief Get the TemplateIdAnnotation from the token.
    707   TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
    708 
    709   /// TentativeParsingAction - An object that is used as a kind of "tentative
    710   /// parsing transaction". It gets instantiated to mark the token position and
    711   /// after the token consumption is done, Commit() or Revert() is called to
    712   /// either "commit the consumed tokens" or revert to the previously marked
    713   /// token position. Example:
    714   ///
    715   ///   TentativeParsingAction TPA(*this);
    716   ///   ConsumeToken();
    717   ///   ....
    718   ///   TPA.Revert();
    719   ///
    720   class TentativeParsingAction {
    721     Parser &P;
    722     Token PrevTok;
    723     size_t PrevTentativelyDeclaredIdentifierCount;
    724     unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
    725     bool isActive;
    726 
    727   public:
    728     explicit TentativeParsingAction(Parser& p) : P(p) {
    729       PrevTok = P.Tok;
    730       PrevTentativelyDeclaredIdentifierCount =
    731           P.TentativelyDeclaredIdentifiers.size();
    732       PrevParenCount = P.ParenCount;
    733       PrevBracketCount = P.BracketCount;
    734       PrevBraceCount = P.BraceCount;
    735       P.PP.EnableBacktrackAtThisPos();
    736       isActive = true;
    737     }
    738     void Commit() {
    739       assert(isActive && "Parsing action was finished!");
    740       P.TentativelyDeclaredIdentifiers.resize(
    741           PrevTentativelyDeclaredIdentifierCount);
    742       P.PP.CommitBacktrackedTokens();
    743       isActive = false;
    744     }
    745     void Revert() {
    746       assert(isActive && "Parsing action was finished!");
    747       P.PP.Backtrack();
    748       P.Tok = PrevTok;
    749       P.TentativelyDeclaredIdentifiers.resize(
    750           PrevTentativelyDeclaredIdentifierCount);
    751       P.ParenCount = PrevParenCount;
    752       P.BracketCount = PrevBracketCount;
    753       P.BraceCount = PrevBraceCount;
    754       isActive = false;
    755     }
    756     ~TentativeParsingAction() {
    757       assert(!isActive && "Forgot to call Commit or Revert!");
    758     }
    759   };
    760   /// A TentativeParsingAction that automatically reverts in its destructor.
    761   /// Useful for disambiguation parses that will always be reverted.
    762   class RevertingTentativeParsingAction
    763       : private Parser::TentativeParsingAction {
    764   public:
    765     RevertingTentativeParsingAction(Parser &P)
    766         : Parser::TentativeParsingAction(P) {}
    767     ~RevertingTentativeParsingAction() { Revert(); }
    768   };
    769 
    770   class UnannotatedTentativeParsingAction;
    771 
    772   /// ObjCDeclContextSwitch - An object used to switch context from
    773   /// an objective-c decl context to its enclosing decl context and
    774   /// back.
    775   class ObjCDeclContextSwitch {
    776     Parser &P;
    777     Decl *DC;
    778     SaveAndRestore<bool> WithinObjCContainer;
    779   public:
    780     explicit ObjCDeclContextSwitch(Parser &p)
    781       : P(p), DC(p.getObjCDeclContext()),
    782         WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
    783       if (DC)
    784         P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
    785     }
    786     ~ObjCDeclContextSwitch() {
    787       if (DC)
    788         P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
    789     }
    790   };
    791 
    792   /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
    793   /// input.  If so, it is consumed and false is returned.
    794   ///
    795   /// If a trivial punctuator misspelling is encountered, a FixIt error
    796   /// diagnostic is issued and false is returned after recovery.
    797   ///
    798   /// If the input is malformed, this emits the specified diagnostic and true is
    799   /// returned.
    800   bool ExpectAndConsume(tok::TokenKind ExpectedTok,
    801                         unsigned Diag = diag::err_expected,
    802                         StringRef DiagMsg = "");
    803 
    804   /// \brief The parser expects a semicolon and, if present, will consume it.
    805   ///
    806   /// If the next token is not a semicolon, this emits the specified diagnostic,
    807   /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
    808   /// to the semicolon, consumes that extra token.
    809   bool ExpectAndConsumeSemi(unsigned DiagID);
    810 
    811   /// \brief The kind of extra semi diagnostic to emit.
    812   enum ExtraSemiKind {
    813     OutsideFunction = 0,
    814     InsideStruct = 1,
    815     InstanceVariableList = 2,
    816     AfterMemberFunctionDefinition = 3
    817   };
    818 
    819   /// \brief Consume any extra semi-colons until the end of the line.
    820   void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
    821 
    822   /// Return false if the next token is an identifier. An 'expected identifier'
    823   /// error is emitted otherwise.
    824   ///
    825   /// The parser tries to recover from the error by checking if the next token
    826   /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
    827   /// was successful.
    828   bool expectIdentifier();
    829 
    830 public:
    831   //===--------------------------------------------------------------------===//
    832   // Scope manipulation
    833 
    834   /// ParseScope - Introduces a new scope for parsing. The kind of
    835   /// scope is determined by ScopeFlags. Objects of this type should
    836   /// be created on the stack to coincide with the position where the
    837   /// parser enters the new scope, and this object's constructor will
    838   /// create that new scope. Similarly, once the object is destroyed
    839   /// the parser will exit the scope.
    840   class ParseScope {
    841     Parser *Self;
    842     ParseScope(const ParseScope &) = delete;
    843     void operator=(const ParseScope &) = delete;
    844 
    845   public:
    846     // ParseScope - Construct a new object to manage a scope in the
    847     // parser Self where the new Scope is created with the flags
    848     // ScopeFlags, but only when we aren't about to enter a compound statement.
    849     ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
    850                bool BeforeCompoundStmt = false)
    851       : Self(Self) {
    852       if (EnteredScope && !BeforeCompoundStmt)
    853         Self->EnterScope(ScopeFlags);
    854       else {
    855         if (BeforeCompoundStmt)
    856           Self->incrementMSManglingNumber();
    857 
    858         this->Self = nullptr;
    859       }
    860     }
    861 
    862     // Exit - Exit the scope associated with this object now, rather
    863     // than waiting until the object is destroyed.
    864     void Exit() {
    865       if (Self) {
    866         Self->ExitScope();
    867         Self = nullptr;
    868       }
    869     }
    870 
    871     ~ParseScope() {
    872       Exit();
    873     }
    874   };
    875 
    876   /// EnterScope - Start a new scope.
    877   void EnterScope(unsigned ScopeFlags);
    878 
    879   /// ExitScope - Pop a scope off the scope stack.
    880   void ExitScope();
    881 
    882 private:
    883   /// \brief RAII object used to modify the scope flags for the current scope.
    884   class ParseScopeFlags {
    885     Scope *CurScope;
    886     unsigned OldFlags;
    887     ParseScopeFlags(const ParseScopeFlags &) = delete;
    888     void operator=(const ParseScopeFlags &) = delete;
    889 
    890   public:
    891     ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
    892     ~ParseScopeFlags();
    893   };
    894 
    895   //===--------------------------------------------------------------------===//
    896   // Diagnostic Emission and Error recovery.
    897 
    898 public:
    899   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
    900   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
    901   DiagnosticBuilder Diag(unsigned DiagID) {
    902     return Diag(Tok, DiagID);
    903   }
    904 
    905 private:
    906   void SuggestParentheses(SourceLocation Loc, unsigned DK,
    907                           SourceRange ParenRange);
    908   void CheckNestedObjCContexts(SourceLocation AtLoc);
    909 
    910 public:
    911 
    912   /// \brief Control flags for SkipUntil functions.
    913   enum SkipUntilFlags {
    914     StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
    915     /// \brief Stop skipping at specified token, but don't skip the token itself
    916     StopBeforeMatch = 1 << 1,
    917     StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
    918   };
    919 
    920   friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
    921                                             SkipUntilFlags R) {
    922     return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
    923                                        static_cast<unsigned>(R));
    924   }
    925 
    926   /// SkipUntil - Read tokens until we get to the specified token, then consume
    927   /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
    928   /// that the token will ever occur, this skips to the next token, or to some
    929   /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
    930   /// stop at a ';' character.
    931   ///
    932   /// If SkipUntil finds the specified token, it returns true, otherwise it
    933   /// returns false.
    934   bool SkipUntil(tok::TokenKind T,
    935                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
    936     return SkipUntil(llvm::makeArrayRef(T), Flags);
    937   }
    938   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
    939                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
    940     tok::TokenKind TokArray[] = {T1, T2};
    941     return SkipUntil(TokArray, Flags);
    942   }
    943   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
    944                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
    945     tok::TokenKind TokArray[] = {T1, T2, T3};
    946     return SkipUntil(TokArray, Flags);
    947   }
    948   bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
    949                  SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
    950 
    951   /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
    952   /// point for skipping past a simple-declaration.
    953   void SkipMalformedDecl();
    954 
    955 private:
    956   //===--------------------------------------------------------------------===//
    957   // Lexing and parsing of C++ inline methods.
    958 
    959   struct ParsingClass;
    960 
    961   /// [class.mem]p1: "... the class is regarded as complete within
    962   /// - function bodies
    963   /// - default arguments
    964   /// - exception-specifications (TODO: C++0x)
    965   /// - and brace-or-equal-initializers for non-static data members
    966   /// (including such things in nested classes)."
    967   /// LateParsedDeclarations build the tree of those elements so they can
    968   /// be parsed after parsing the top-level class.
    969   class LateParsedDeclaration {
    970   public:
    971     virtual ~LateParsedDeclaration();
    972 
    973     virtual void ParseLexedMethodDeclarations();
    974     virtual void ParseLexedMemberInitializers();
    975     virtual void ParseLexedMethodDefs();
    976     virtual void ParseLexedAttributes();
    977   };
    978 
    979   /// Inner node of the LateParsedDeclaration tree that parses
    980   /// all its members recursively.
    981   class LateParsedClass : public LateParsedDeclaration {
    982   public:
    983     LateParsedClass(Parser *P, ParsingClass *C);
    984     ~LateParsedClass() override;
    985 
    986     void ParseLexedMethodDeclarations() override;
    987     void ParseLexedMemberInitializers() override;
    988     void ParseLexedMethodDefs() override;
    989     void ParseLexedAttributes() override;
    990 
    991   private:
    992     Parser *Self;
    993     ParsingClass *Class;
    994   };
    995 
    996   /// Contains the lexed tokens of an attribute with arguments that
    997   /// may reference member variables and so need to be parsed at the
    998   /// end of the class declaration after parsing all other member
    999   /// member declarations.
   1000   /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
   1001   /// LateParsedTokens.
   1002   struct LateParsedAttribute : public LateParsedDeclaration {
   1003     Parser *Self;
   1004     CachedTokens Toks;
   1005     IdentifierInfo &AttrName;
   1006     SourceLocation AttrNameLoc;
   1007     SmallVector<Decl*, 2> Decls;
   1008 
   1009     explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
   1010                                  SourceLocation Loc)
   1011       : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
   1012 
   1013     void ParseLexedAttributes() override;
   1014 
   1015     void addDecl(Decl *D) { Decls.push_back(D); }
   1016   };
   1017 
   1018   // A list of late-parsed attributes.  Used by ParseGNUAttributes.
   1019   class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
   1020   public:
   1021     LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
   1022 
   1023     bool parseSoon() { return ParseSoon; }
   1024 
   1025   private:
   1026     bool ParseSoon;  // Are we planning to parse these shortly after creation?
   1027   };
   1028 
   1029   /// Contains the lexed tokens of a member function definition
   1030   /// which needs to be parsed at the end of the class declaration
   1031   /// after parsing all other member declarations.
   1032   struct LexedMethod : public LateParsedDeclaration {
   1033     Parser *Self;
   1034     Decl *D;
   1035     CachedTokens Toks;
   1036 
   1037     /// \brief Whether this member function had an associated template
   1038     /// scope. When true, D is a template declaration.
   1039     /// otherwise, it is a member function declaration.
   1040     bool TemplateScope;
   1041 
   1042     explicit LexedMethod(Parser* P, Decl *MD)
   1043       : Self(P), D(MD), TemplateScope(false) {}
   1044 
   1045     void ParseLexedMethodDefs() override;
   1046   };
   1047 
   1048   /// LateParsedDefaultArgument - Keeps track of a parameter that may
   1049   /// have a default argument that cannot be parsed yet because it
   1050   /// occurs within a member function declaration inside the class
   1051   /// (C++ [class.mem]p2).
   1052   struct LateParsedDefaultArgument {
   1053     explicit LateParsedDefaultArgument(Decl *P,
   1054                                        std::unique_ptr<CachedTokens> Toks = nullptr)
   1055       : Param(P), Toks(std::move(Toks)) { }
   1056 
   1057     /// Param - The parameter declaration for this parameter.
   1058     Decl *Param;
   1059 
   1060     /// Toks - The sequence of tokens that comprises the default
   1061     /// argument expression, not including the '=' or the terminating
   1062     /// ')' or ','. This will be NULL for parameters that have no
   1063     /// default argument.
   1064     std::unique_ptr<CachedTokens> Toks;
   1065   };
   1066 
   1067   /// LateParsedMethodDeclaration - A method declaration inside a class that
   1068   /// contains at least one entity whose parsing needs to be delayed
   1069   /// until the class itself is completely-defined, such as a default
   1070   /// argument (C++ [class.mem]p2).
   1071   struct LateParsedMethodDeclaration : public LateParsedDeclaration {
   1072     explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
   1073       : Self(P), Method(M), TemplateScope(false),
   1074         ExceptionSpecTokens(nullptr) {}
   1075 
   1076     void ParseLexedMethodDeclarations() override;
   1077 
   1078     Parser* Self;
   1079 
   1080     /// Method - The method declaration.
   1081     Decl *Method;
   1082 
   1083     /// \brief Whether this member function had an associated template
   1084     /// scope. When true, D is a template declaration.
   1085     /// othewise, it is a member function declaration.
   1086     bool TemplateScope;
   1087 
   1088     /// DefaultArgs - Contains the parameters of the function and
   1089     /// their default arguments. At least one of the parameters will
   1090     /// have a default argument, but all of the parameters of the
   1091     /// method will be stored so that they can be reintroduced into
   1092     /// scope at the appropriate times.
   1093     SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
   1094 
   1095     /// \brief The set of tokens that make up an exception-specification that
   1096     /// has not yet been parsed.
   1097     CachedTokens *ExceptionSpecTokens;
   1098   };
   1099 
   1100   /// LateParsedMemberInitializer - An initializer for a non-static class data
   1101   /// member whose parsing must to be delayed until the class is completely
   1102   /// defined (C++11 [class.mem]p2).
   1103   struct LateParsedMemberInitializer : public LateParsedDeclaration {
   1104     LateParsedMemberInitializer(Parser *P, Decl *FD)
   1105       : Self(P), Field(FD) { }
   1106 
   1107     void ParseLexedMemberInitializers() override;
   1108 
   1109     Parser *Self;
   1110 
   1111     /// Field - The field declaration.
   1112     Decl *Field;
   1113 
   1114     /// CachedTokens - The sequence of tokens that comprises the initializer,
   1115     /// including any leading '='.
   1116     CachedTokens Toks;
   1117   };
   1118 
   1119   /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
   1120   /// C++ class, its method declarations that contain parts that won't be
   1121   /// parsed until after the definition is completed (C++ [class.mem]p2),
   1122   /// the method declarations and possibly attached inline definitions
   1123   /// will be stored here with the tokens that will be parsed to create those
   1124   /// entities.
   1125   typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
   1126 
   1127   /// \brief Representation of a class that has been parsed, including
   1128   /// any member function declarations or definitions that need to be
   1129   /// parsed after the corresponding top-level class is complete.
   1130   struct ParsingClass {
   1131     ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
   1132       : TopLevelClass(TopLevelClass), TemplateScope(false),
   1133         IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
   1134 
   1135     /// \brief Whether this is a "top-level" class, meaning that it is
   1136     /// not nested within another class.
   1137     bool TopLevelClass : 1;
   1138 
   1139     /// \brief Whether this class had an associated template
   1140     /// scope. When true, TagOrTemplate is a template declaration;
   1141     /// othewise, it is a tag declaration.
   1142     bool TemplateScope : 1;
   1143 
   1144     /// \brief Whether this class is an __interface.
   1145     bool IsInterface : 1;
   1146 
   1147     /// \brief The class or class template whose definition we are parsing.
   1148     Decl *TagOrTemplate;
   1149 
   1150     /// LateParsedDeclarations - Method declarations, inline definitions and
   1151     /// nested classes that contain pieces whose parsing will be delayed until
   1152     /// the top-level class is fully defined.
   1153     LateParsedDeclarationsContainer LateParsedDeclarations;
   1154   };
   1155 
   1156   /// \brief The stack of classes that is currently being
   1157   /// parsed. Nested and local classes will be pushed onto this stack
   1158   /// when they are parsed, and removed afterward.
   1159   std::stack<ParsingClass *> ClassStack;
   1160 
   1161   ParsingClass &getCurrentClass() {
   1162     assert(!ClassStack.empty() && "No lexed method stacks!");
   1163     return *ClassStack.top();
   1164   }
   1165 
   1166   /// \brief RAII object used to manage the parsing of a class definition.
   1167   class ParsingClassDefinition {
   1168     Parser &P;
   1169     bool Popped;
   1170     Sema::ParsingClassState State;
   1171 
   1172   public:
   1173     ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
   1174                            bool IsInterface)
   1175       : P(P), Popped(false),
   1176         State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
   1177     }
   1178 
   1179     /// \brief Pop this class of the stack.
   1180     void Pop() {
   1181       assert(!Popped && "Nested class has already been popped");
   1182       Popped = true;
   1183       P.PopParsingClass(State);
   1184     }
   1185 
   1186     ~ParsingClassDefinition() {
   1187       if (!Popped)
   1188         P.PopParsingClass(State);
   1189     }
   1190   };
   1191 
   1192   /// \brief Contains information about any template-specific
   1193   /// information that has been parsed prior to parsing declaration
   1194   /// specifiers.
   1195   struct ParsedTemplateInfo {
   1196     ParsedTemplateInfo()
   1197       : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
   1198 
   1199     ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
   1200                        bool isSpecialization,
   1201                        bool lastParameterListWasEmpty = false)
   1202       : Kind(isSpecialization? ExplicitSpecialization : Template),
   1203         TemplateParams(TemplateParams),
   1204         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
   1205 
   1206     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
   1207                                 SourceLocation TemplateLoc)
   1208       : Kind(ExplicitInstantiation), TemplateParams(nullptr),
   1209         ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
   1210         LastParameterListWasEmpty(false){ }
   1211 
   1212     /// \brief The kind of template we are parsing.
   1213     enum {
   1214       /// \brief We are not parsing a template at all.
   1215       NonTemplate = 0,
   1216       /// \brief We are parsing a template declaration.
   1217       Template,
   1218       /// \brief We are parsing an explicit specialization.
   1219       ExplicitSpecialization,
   1220       /// \brief We are parsing an explicit instantiation.
   1221       ExplicitInstantiation
   1222     } Kind;
   1223 
   1224     /// \brief The template parameter lists, for template declarations
   1225     /// and explicit specializations.
   1226     TemplateParameterLists *TemplateParams;
   1227 
   1228     /// \brief The location of the 'extern' keyword, if any, for an explicit
   1229     /// instantiation
   1230     SourceLocation ExternLoc;
   1231 
   1232     /// \brief The location of the 'template' keyword, for an explicit
   1233     /// instantiation.
   1234     SourceLocation TemplateLoc;
   1235 
   1236     /// \brief Whether the last template parameter list was empty.
   1237     bool LastParameterListWasEmpty;
   1238 
   1239     SourceRange getSourceRange() const LLVM_READONLY;
   1240   };
   1241 
   1242   void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
   1243   void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
   1244 
   1245   static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
   1246   static void LateTemplateParserCleanupCallback(void *P);
   1247 
   1248   Sema::ParsingClassState
   1249   PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
   1250   void DeallocateParsedClasses(ParsingClass *Class);
   1251   void PopParsingClass(Sema::ParsingClassState);
   1252 
   1253   enum CachedInitKind {
   1254     CIK_DefaultArgument,
   1255     CIK_DefaultInitializer
   1256   };
   1257 
   1258   NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
   1259                                 AttributeList *AccessAttrs,
   1260                                 ParsingDeclarator &D,
   1261                                 const ParsedTemplateInfo &TemplateInfo,
   1262                                 const VirtSpecifiers& VS,
   1263                                 SourceLocation PureSpecLoc);
   1264   void ParseCXXNonStaticMemberInitializer(Decl *VarD);
   1265   void ParseLexedAttributes(ParsingClass &Class);
   1266   void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
   1267                                bool EnterScope, bool OnDefinition);
   1268   void ParseLexedAttribute(LateParsedAttribute &LA,
   1269                            bool EnterScope, bool OnDefinition);
   1270   void ParseLexedMethodDeclarations(ParsingClass &Class);
   1271   void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
   1272   void ParseLexedMethodDefs(ParsingClass &Class);
   1273   void ParseLexedMethodDef(LexedMethod &LM);
   1274   void ParseLexedMemberInitializers(ParsingClass &Class);
   1275   void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
   1276   void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
   1277   bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
   1278   bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
   1279   bool ConsumeAndStoreConditional(CachedTokens &Toks);
   1280   bool ConsumeAndStoreUntil(tok::TokenKind T1,
   1281                             CachedTokens &Toks,
   1282                             bool StopAtSemi = true,
   1283                             bool ConsumeFinalToken = true) {
   1284     return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
   1285   }
   1286   bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
   1287                             CachedTokens &Toks,
   1288                             bool StopAtSemi = true,
   1289                             bool ConsumeFinalToken = true);
   1290 
   1291   //===--------------------------------------------------------------------===//
   1292   // C99 6.9: External Definitions.
   1293   struct ParsedAttributesWithRange : ParsedAttributes {
   1294     ParsedAttributesWithRange(AttributeFactory &factory)
   1295       : ParsedAttributes(factory) {}
   1296 
   1297     void clear() {
   1298       ParsedAttributes::clear();
   1299       Range = SourceRange();
   1300     }
   1301 
   1302     SourceRange Range;
   1303   };
   1304 
   1305   DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
   1306                                           ParsingDeclSpec *DS = nullptr);
   1307   bool isDeclarationAfterDeclarator();
   1308   bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
   1309   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
   1310                                                   ParsedAttributesWithRange &attrs,
   1311                                                   ParsingDeclSpec *DS = nullptr,
   1312                                                   AccessSpecifier AS = AS_none);
   1313   DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
   1314                                                 ParsingDeclSpec &DS,
   1315                                                 AccessSpecifier AS);
   1316 
   1317   void SkipFunctionBody();
   1318   Decl *ParseFunctionDefinition(ParsingDeclarator &D,
   1319                  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   1320                  LateParsedAttrList *LateParsedAttrs = nullptr);
   1321   void ParseKNRParamDeclarations(Declarator &D);
   1322   // EndLoc, if non-NULL, is filled with the location of the last token of
   1323   // the simple-asm.
   1324   ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
   1325   ExprResult ParseAsmStringLiteral();
   1326 
   1327   // Objective-C External Declarations
   1328   void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
   1329   DeclGroupPtrTy ParseObjCAtDirectives();
   1330   DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
   1331   Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
   1332                                         ParsedAttributes &prefixAttrs);
   1333   class ObjCTypeParamListScope;
   1334   ObjCTypeParamList *parseObjCTypeParamList();
   1335   ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
   1336       ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
   1337       SmallVectorImpl<IdentifierLocPair> &protocolIdents,
   1338       SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
   1339 
   1340   void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
   1341                                         BalancedDelimiterTracker &T,
   1342                                         SmallVectorImpl<Decl *> &AllIvarDecls,
   1343                                         bool RBraceMissing);
   1344   void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
   1345                                        tok::ObjCKeywordKind visibility,
   1346                                        SourceLocation atLoc);
   1347   bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
   1348                                    SmallVectorImpl<SourceLocation> &PLocs,
   1349                                    bool WarnOnDeclarations,
   1350                                    bool ForObjCContainer,
   1351                                    SourceLocation &LAngleLoc,
   1352                                    SourceLocation &EndProtoLoc,
   1353                                    bool consumeLastToken);
   1354 
   1355   /// Parse the first angle-bracket-delimited clause for an
   1356   /// Objective-C object or object pointer type, which may be either
   1357   /// type arguments or protocol qualifiers.
   1358   void parseObjCTypeArgsOrProtocolQualifiers(
   1359          ParsedType baseType,
   1360          SourceLocation &typeArgsLAngleLoc,
   1361          SmallVectorImpl<ParsedType> &typeArgs,
   1362          SourceLocation &typeArgsRAngleLoc,
   1363          SourceLocation &protocolLAngleLoc,
   1364          SmallVectorImpl<Decl *> &protocols,
   1365          SmallVectorImpl<SourceLocation> &protocolLocs,
   1366          SourceLocation &protocolRAngleLoc,
   1367          bool consumeLastToken,
   1368          bool warnOnIncompleteProtocols);
   1369 
   1370   /// Parse either Objective-C type arguments or protocol qualifiers; if the
   1371   /// former, also parse protocol qualifiers afterward.
   1372   void parseObjCTypeArgsAndProtocolQualifiers(
   1373          ParsedType baseType,
   1374          SourceLocation &typeArgsLAngleLoc,
   1375          SmallVectorImpl<ParsedType> &typeArgs,
   1376          SourceLocation &typeArgsRAngleLoc,
   1377          SourceLocation &protocolLAngleLoc,
   1378          SmallVectorImpl<Decl *> &protocols,
   1379          SmallVectorImpl<SourceLocation> &protocolLocs,
   1380          SourceLocation &protocolRAngleLoc,
   1381          bool consumeLastToken);
   1382 
   1383   /// Parse a protocol qualifier type such as '<NSCopying>', which is
   1384   /// an anachronistic way of writing 'id<NSCopying>'.
   1385   TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
   1386 
   1387   /// Parse Objective-C type arguments and protocol qualifiers, extending the
   1388   /// current type with the parsed result.
   1389   TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
   1390                                                     ParsedType type,
   1391                                                     bool consumeLastToken,
   1392                                                     SourceLocation &endLoc);
   1393 
   1394   void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
   1395                                   Decl *CDecl);
   1396   DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
   1397                                                 ParsedAttributes &prefixAttrs);
   1398 
   1399   struct ObjCImplParsingDataRAII {
   1400     Parser &P;
   1401     Decl *Dcl;
   1402     bool HasCFunction;
   1403     typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
   1404     LateParsedObjCMethodContainer LateParsedObjCMethods;
   1405 
   1406     ObjCImplParsingDataRAII(Parser &parser, Decl *D)
   1407       : P(parser), Dcl(D), HasCFunction(false) {
   1408       P.CurParsedObjCImpl = this;
   1409       Finished = false;
   1410     }
   1411     ~ObjCImplParsingDataRAII();
   1412 
   1413     void finish(SourceRange AtEnd);
   1414     bool isFinished() const { return Finished; }
   1415 
   1416   private:
   1417     bool Finished;
   1418   };
   1419   ObjCImplParsingDataRAII *CurParsedObjCImpl;
   1420   void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
   1421 
   1422   DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
   1423   DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
   1424   Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
   1425   Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
   1426   Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
   1427 
   1428   IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
   1429   // Definitions for Objective-c context sensitive keywords recognition.
   1430   enum ObjCTypeQual {
   1431     objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
   1432     objc_nonnull, objc_nullable, objc_null_unspecified,
   1433     objc_NumQuals
   1434   };
   1435   IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
   1436 
   1437   bool isTokIdentifier_in() const;
   1438 
   1439   ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
   1440                                ParsedAttributes *ParamAttrs);
   1441   void ParseObjCMethodRequirement();
   1442   Decl *ParseObjCMethodPrototype(
   1443             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
   1444             bool MethodDefinition = true);
   1445   Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
   1446             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
   1447             bool MethodDefinition=true);
   1448   void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
   1449 
   1450   Decl *ParseObjCMethodDefinition();
   1451 
   1452 public:
   1453   //===--------------------------------------------------------------------===//
   1454   // C99 6.5: Expressions.
   1455 
   1456   /// TypeCastState - State whether an expression is or may be a type cast.
   1457   enum TypeCastState {
   1458     NotTypeCast = 0,
   1459     MaybeTypeCast,
   1460     IsTypeCast
   1461   };
   1462 
   1463   ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
   1464   ExprResult ParseConstantExpressionInExprEvalContext(
   1465       TypeCastState isTypeCast = NotTypeCast);
   1466   ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
   1467   ExprResult ParseConstraintExpression();
   1468   // Expr that doesn't include commas.
   1469   ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
   1470 
   1471   ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
   1472                                   unsigned &NumLineToksConsumed,
   1473                                   void *Info,
   1474                                   bool IsUnevaluated);
   1475 
   1476 private:
   1477   ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
   1478 
   1479   ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
   1480 
   1481   ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
   1482                                         prec::Level MinPrec);
   1483   ExprResult ParseCastExpression(bool isUnaryExpression,
   1484                                  bool isAddressOfOperand,
   1485                                  bool &NotCastExpr,
   1486                                  TypeCastState isTypeCast,
   1487                                  bool isVectorLiteral = false);
   1488   ExprResult ParseCastExpression(bool isUnaryExpression,
   1489                                  bool isAddressOfOperand = false,
   1490                                  TypeCastState isTypeCast = NotTypeCast,
   1491                                  bool isVectorLiteral = false);
   1492 
   1493   /// Returns true if the next token cannot start an expression.
   1494   bool isNotExpressionStart();
   1495 
   1496   /// Returns true if the next token would start a postfix-expression
   1497   /// suffix.
   1498   bool isPostfixExpressionSuffixStart() {
   1499     tok::TokenKind K = Tok.getKind();
   1500     return (K == tok::l_square || K == tok::l_paren ||
   1501             K == tok::period || K == tok::arrow ||
   1502             K == tok::plusplus || K == tok::minusminus);
   1503   }
   1504 
   1505   bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
   1506 
   1507   ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
   1508   ExprResult ParseUnaryExprOrTypeTraitExpression();
   1509   ExprResult ParseBuiltinPrimaryExpression();
   1510 
   1511   ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
   1512                                                      bool &isCastExpr,
   1513                                                      ParsedType &CastTy,
   1514                                                      SourceRange &CastRange);
   1515 
   1516   typedef SmallVector<Expr*, 20> ExprListTy;
   1517   typedef SmallVector<SourceLocation, 20> CommaLocsTy;
   1518 
   1519   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
   1520   bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
   1521                            SmallVectorImpl<SourceLocation> &CommaLocs,
   1522                            std::function<void()> Completer = nullptr);
   1523 
   1524   /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
   1525   /// used for misc language extensions.
   1526   bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
   1527                                  SmallVectorImpl<SourceLocation> &CommaLocs);
   1528 
   1529 
   1530   /// ParenParseOption - Control what ParseParenExpression will parse.
   1531   enum ParenParseOption {
   1532     SimpleExpr,      // Only parse '(' expression ')'
   1533     CompoundStmt,    // Also allow '(' compound-statement ')'
   1534     CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
   1535     CastExpr         // Also allow '(' type-name ')' <anything>
   1536   };
   1537   ExprResult ParseParenExpression(ParenParseOption &ExprType,
   1538                                         bool stopIfCastExpr,
   1539                                         bool isTypeCast,
   1540                                         ParsedType &CastTy,
   1541                                         SourceLocation &RParenLoc);
   1542 
   1543   ExprResult ParseCXXAmbiguousParenExpression(
   1544       ParenParseOption &ExprType, ParsedType &CastTy,
   1545       BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
   1546   ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
   1547                                                   SourceLocation LParenLoc,
   1548                                                   SourceLocation RParenLoc);
   1549 
   1550   ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
   1551 
   1552   ExprResult ParseGenericSelectionExpression();
   1553 
   1554   ExprResult ParseObjCBoolLiteral();
   1555 
   1556   ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
   1557 
   1558   //===--------------------------------------------------------------------===//
   1559   // C++ Expressions
   1560   ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
   1561                                      Token &Replacement);
   1562   ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
   1563 
   1564   bool areTokensAdjacent(const Token &A, const Token &B);
   1565 
   1566   void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
   1567                                   bool EnteringContext, IdentifierInfo &II,
   1568                                   CXXScopeSpec &SS);
   1569 
   1570   bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
   1571                                       ParsedType ObjectType,
   1572                                       bool EnteringContext,
   1573                                       bool *MayBePseudoDestructor = nullptr,
   1574                                       bool IsTypename = false,
   1575                                       IdentifierInfo **LastII = nullptr,
   1576                                       bool OnlyNamespace = false);
   1577 
   1578   //===--------------------------------------------------------------------===//
   1579   // C++0x 5.1.2: Lambda expressions
   1580 
   1581   // [...] () -> type {...}
   1582   ExprResult ParseLambdaExpression();
   1583   ExprResult TryParseLambdaExpression();
   1584   Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
   1585                                            bool *SkippedInits = nullptr);
   1586   bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
   1587   ExprResult ParseLambdaExpressionAfterIntroducer(
   1588                LambdaIntroducer &Intro);
   1589 
   1590   //===--------------------------------------------------------------------===//
   1591   // C++ 5.2p1: C++ Casts
   1592   ExprResult ParseCXXCasts();
   1593 
   1594   //===--------------------------------------------------------------------===//
   1595   // C++ 5.2p1: C++ Type Identification
   1596   ExprResult ParseCXXTypeid();
   1597 
   1598   //===--------------------------------------------------------------------===//
   1599   //  C++ : Microsoft __uuidof Expression
   1600   ExprResult ParseCXXUuidof();
   1601 
   1602   //===--------------------------------------------------------------------===//
   1603   // C++ 5.2.4: C++ Pseudo-Destructor Expressions
   1604   ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
   1605                                             tok::TokenKind OpKind,
   1606                                             CXXScopeSpec &SS,
   1607                                             ParsedType ObjectType);
   1608 
   1609   //===--------------------------------------------------------------------===//
   1610   // C++ 9.3.2: C++ 'this' pointer
   1611   ExprResult ParseCXXThis();
   1612 
   1613   //===--------------------------------------------------------------------===//
   1614   // C++ 15: C++ Throw Expression
   1615   ExprResult ParseThrowExpression();
   1616 
   1617   ExceptionSpecificationType tryParseExceptionSpecification(
   1618                     bool Delayed,
   1619                     SourceRange &SpecificationRange,
   1620                     SmallVectorImpl<ParsedType> &DynamicExceptions,
   1621                     SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
   1622                     ExprResult &NoexceptExpr,
   1623                     CachedTokens *&ExceptionSpecTokens);
   1624 
   1625   // EndLoc is filled with the location of the last token of the specification.
   1626   ExceptionSpecificationType ParseDynamicExceptionSpecification(
   1627                                   SourceRange &SpecificationRange,
   1628                                   SmallVectorImpl<ParsedType> &Exceptions,
   1629                                   SmallVectorImpl<SourceRange> &Ranges);
   1630 
   1631   //===--------------------------------------------------------------------===//
   1632   // C++0x 8: Function declaration trailing-return-type
   1633   TypeResult ParseTrailingReturnType(SourceRange &Range);
   1634 
   1635   //===--------------------------------------------------------------------===//
   1636   // C++ 2.13.5: C++ Boolean Literals
   1637   ExprResult ParseCXXBoolLiteral();
   1638 
   1639   //===--------------------------------------------------------------------===//
   1640   // C++ 5.2.3: Explicit type conversion (functional notation)
   1641   ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
   1642 
   1643   /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
   1644   /// This should only be called when the current token is known to be part of
   1645   /// simple-type-specifier.
   1646   void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
   1647 
   1648   bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
   1649 
   1650   //===--------------------------------------------------------------------===//
   1651   // C++ 5.3.4 and 5.3.5: C++ new and delete
   1652   bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
   1653                                    Declarator &D);
   1654   void ParseDirectNewDeclarator(Declarator &D);
   1655   ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
   1656   ExprResult ParseCXXDeleteExpression(bool UseGlobal,
   1657                                             SourceLocation Start);
   1658 
   1659   //===--------------------------------------------------------------------===//
   1660   // C++ if/switch/while condition expression.
   1661   Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
   1662                                           SourceLocation Loc,
   1663                                           Sema::ConditionKind CK);
   1664 
   1665   //===--------------------------------------------------------------------===//
   1666   // C++ Coroutines
   1667 
   1668   ExprResult ParseCoyieldExpression();
   1669 
   1670   //===--------------------------------------------------------------------===//
   1671   // C99 6.7.8: Initialization.
   1672 
   1673   /// ParseInitializer
   1674   ///       initializer: [C99 6.7.8]
   1675   ///         assignment-expression
   1676   ///         '{' ...
   1677   ExprResult ParseInitializer() {
   1678     if (Tok.isNot(tok::l_brace))
   1679       return ParseAssignmentExpression();
   1680     return ParseBraceInitializer();
   1681   }
   1682   bool MayBeDesignationStart();
   1683   ExprResult ParseBraceInitializer();
   1684   ExprResult ParseInitializerWithPotentialDesignator();
   1685 
   1686   //===--------------------------------------------------------------------===//
   1687   // clang Expressions
   1688 
   1689   ExprResult ParseBlockLiteralExpression();  // ^{...}
   1690 
   1691   //===--------------------------------------------------------------------===//
   1692   // Objective-C Expressions
   1693   ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
   1694   ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
   1695   ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
   1696   ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
   1697   ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
   1698   ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
   1699   ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
   1700   ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
   1701   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
   1702   ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
   1703   ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
   1704   bool isSimpleObjCMessageExpression();
   1705   ExprResult ParseObjCMessageExpression();
   1706   ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
   1707                                             SourceLocation SuperLoc,
   1708                                             ParsedType ReceiverType,
   1709                                             Expr *ReceiverExpr);
   1710   ExprResult ParseAssignmentExprWithObjCMessageExprStart(
   1711       SourceLocation LBracloc, SourceLocation SuperLoc,
   1712       ParsedType ReceiverType, Expr *ReceiverExpr);
   1713   bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
   1714 
   1715   //===--------------------------------------------------------------------===//
   1716   // C99 6.8: Statements and Blocks.
   1717 
   1718   /// A SmallVector of statements, with stack size 32 (as that is the only one
   1719   /// used.)
   1720   typedef SmallVector<Stmt*, 32> StmtVector;
   1721   /// A SmallVector of expressions, with stack size 12 (the maximum used.)
   1722   typedef SmallVector<Expr*, 12> ExprVector;
   1723   /// A SmallVector of types.
   1724   typedef SmallVector<ParsedType, 12> TypeVector;
   1725 
   1726   StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
   1727                             bool AllowOpenMPStandalone = false);
   1728   enum AllowedConstructsKind {
   1729     /// \brief Allow any declarations, statements, OpenMP directives.
   1730     ACK_Any,
   1731     /// \brief Allow only statements and non-standalone OpenMP directives.
   1732     ACK_StatementsOpenMPNonStandalone,
   1733     /// \brief Allow statements and all executable OpenMP directives
   1734     ACK_StatementsOpenMPAnyExecutable
   1735   };
   1736   StmtResult
   1737   ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
   1738                               SourceLocation *TrailingElseLoc = nullptr);
   1739   StmtResult ParseStatementOrDeclarationAfterAttributes(
   1740                                          StmtVector &Stmts,
   1741                                          AllowedConstructsKind Allowed,
   1742                                          SourceLocation *TrailingElseLoc,
   1743                                          ParsedAttributesWithRange &Attrs);
   1744   StmtResult ParseExprStatement();
   1745   StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
   1746   StmtResult ParseCaseStatement(bool MissingCase = false,
   1747                                 ExprResult Expr = ExprResult());
   1748   StmtResult ParseDefaultStatement();
   1749   StmtResult ParseCompoundStatement(bool isStmtExpr = false);
   1750   StmtResult ParseCompoundStatement(bool isStmtExpr,
   1751                                     unsigned ScopeFlags);
   1752   void ParseCompoundStatementLeadingPragmas();
   1753   StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
   1754   bool ParseParenExprOrCondition(StmtResult *InitStmt,
   1755                                  Sema::ConditionResult &CondResult,
   1756                                  SourceLocation Loc,
   1757                                  Sema::ConditionKind CK);
   1758   StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
   1759   StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
   1760   StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
   1761   StmtResult ParseDoStatement();
   1762   StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
   1763   StmtResult ParseGotoStatement();
   1764   StmtResult ParseContinueStatement();
   1765   StmtResult ParseBreakStatement();
   1766   StmtResult ParseReturnStatement();
   1767   StmtResult ParseAsmStatement(bool &msAsm);
   1768   StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
   1769   StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
   1770                                  AllowedConstructsKind Allowed,
   1771                                  SourceLocation *TrailingElseLoc,
   1772                                  ParsedAttributesWithRange &Attrs);
   1773 
   1774   /// \brief Describes the behavior that should be taken for an __if_exists
   1775   /// block.
   1776   enum IfExistsBehavior {
   1777     /// \brief Parse the block; this code is always used.
   1778     IEB_Parse,
   1779     /// \brief Skip the block entirely; this code is never used.
   1780     IEB_Skip,
   1781     /// \brief Parse the block as a dependent block, which may be used in
   1782     /// some template instantiations but not others.
   1783     IEB_Dependent
   1784   };
   1785 
   1786   /// \brief Describes the condition of a Microsoft __if_exists or
   1787   /// __if_not_exists block.
   1788   struct IfExistsCondition {
   1789     /// \brief The location of the initial keyword.
   1790     SourceLocation KeywordLoc;
   1791     /// \brief Whether this is an __if_exists block (rather than an
   1792     /// __if_not_exists block).
   1793     bool IsIfExists;
   1794 
   1795     /// \brief Nested-name-specifier preceding the name.
   1796     CXXScopeSpec SS;
   1797 
   1798     /// \brief The name we're looking for.
   1799     UnqualifiedId Name;
   1800 
   1801     /// \brief The behavior of this __if_exists or __if_not_exists block
   1802     /// should.
   1803     IfExistsBehavior Behavior;
   1804   };
   1805 
   1806   bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
   1807   void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
   1808   void ParseMicrosoftIfExistsExternalDeclaration();
   1809   void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
   1810                                               AccessSpecifier& CurAS);
   1811   bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
   1812                                               bool &InitExprsOk);
   1813   bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
   1814                            SmallVectorImpl<Expr *> &Constraints,
   1815                            SmallVectorImpl<Expr *> &Exprs);
   1816 
   1817   //===--------------------------------------------------------------------===//
   1818   // C++ 6: Statements and Blocks
   1819 
   1820   StmtResult ParseCXXTryBlock();
   1821   StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
   1822   StmtResult ParseCXXCatchBlock(bool FnCatch = false);
   1823 
   1824   //===--------------------------------------------------------------------===//
   1825   // MS: SEH Statements and Blocks
   1826 
   1827   StmtResult ParseSEHTryBlock();
   1828   StmtResult ParseSEHExceptBlock(SourceLocation Loc);
   1829   StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
   1830   StmtResult ParseSEHLeaveStatement();
   1831 
   1832   //===--------------------------------------------------------------------===//
   1833   // Objective-C Statements
   1834 
   1835   StmtResult ParseObjCAtStatement(SourceLocation atLoc);
   1836   StmtResult ParseObjCTryStmt(SourceLocation atLoc);
   1837   StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
   1838   StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
   1839   StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
   1840 
   1841 
   1842   //===--------------------------------------------------------------------===//
   1843   // C99 6.7: Declarations.
   1844 
   1845   /// A context for parsing declaration specifiers.  TODO: flesh this
   1846   /// out, there are other significant restrictions on specifiers than
   1847   /// would be best implemented in the parser.
   1848   enum DeclSpecContext {
   1849     DSC_normal, // normal context
   1850     DSC_class,  // class context, enables 'friend'
   1851     DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
   1852     DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
   1853     DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
   1854     DSC_top_level, // top-level/namespace declaration context
   1855     DSC_template_type_arg, // template type argument context
   1856     DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
   1857     DSC_condition // condition declaration context
   1858   };
   1859 
   1860   /// Is this a context in which we are parsing just a type-specifier (or
   1861   /// trailing-type-specifier)?
   1862   static bool isTypeSpecifier(DeclSpecContext DSC) {
   1863     switch (DSC) {
   1864     case DSC_normal:
   1865     case DSC_class:
   1866     case DSC_top_level:
   1867     case DSC_objc_method_result:
   1868     case DSC_condition:
   1869       return false;
   1870 
   1871     case DSC_template_type_arg:
   1872     case DSC_type_specifier:
   1873     case DSC_trailing:
   1874     case DSC_alias_declaration:
   1875       return true;
   1876     }
   1877     llvm_unreachable("Missing DeclSpecContext case");
   1878   }
   1879 
   1880   /// Is this a context in which we can perform class template argument
   1881   /// deduction?
   1882   static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
   1883     switch (DSC) {
   1884     case DSC_normal:
   1885     case DSC_class:
   1886     case DSC_top_level:
   1887     case DSC_condition:
   1888     case DSC_type_specifier:
   1889       return true;
   1890 
   1891     case DSC_objc_method_result:
   1892     case DSC_template_type_arg:
   1893     case DSC_trailing:
   1894     case DSC_alias_declaration:
   1895       return false;
   1896     }
   1897     llvm_unreachable("Missing DeclSpecContext case");
   1898   }
   1899 
   1900   /// Information on a C++0x for-range-initializer found while parsing a
   1901   /// declaration which turns out to be a for-range-declaration.
   1902   struct ForRangeInit {
   1903     SourceLocation ColonLoc;
   1904     ExprResult RangeExpr;
   1905 
   1906     bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   1907   };
   1908 
   1909   DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
   1910                                   ParsedAttributesWithRange &attrs);
   1911   DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
   1912                                         SourceLocation &DeclEnd,
   1913                                         ParsedAttributesWithRange &attrs,
   1914                                         bool RequireSemi,
   1915                                         ForRangeInit *FRI = nullptr);
   1916   bool MightBeDeclarator(unsigned Context);
   1917   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
   1918                                 SourceLocation *DeclEnd = nullptr,
   1919                                 ForRangeInit *FRI = nullptr);
   1920   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
   1921                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
   1922   bool ParseAsmAttributesAfterDeclarator(Declarator &D);
   1923   Decl *ParseDeclarationAfterDeclaratorAndAttributes(
   1924       Declarator &D,
   1925       const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   1926       ForRangeInit *FRI = nullptr);
   1927   Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
   1928   Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
   1929 
   1930   /// \brief When in code-completion, skip parsing of the function/method body
   1931   /// unless the body contains the code-completion point.
   1932   ///
   1933   /// \returns true if the function body was skipped.
   1934   bool trySkippingFunctionBody();
   1935 
   1936   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
   1937                         const ParsedTemplateInfo &TemplateInfo,
   1938                         AccessSpecifier AS, DeclSpecContext DSC,
   1939                         ParsedAttributesWithRange &Attrs);
   1940   DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
   1941   void ParseDeclarationSpecifiers(DeclSpec &DS,
   1942                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   1943                                   AccessSpecifier AS = AS_none,
   1944                                   DeclSpecContext DSC = DSC_normal,
   1945                                   LateParsedAttrList *LateAttrs = nullptr);
   1946   bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
   1947                                        DeclSpecContext DSContext,
   1948                                        LateParsedAttrList *LateAttrs = nullptr);
   1949 
   1950   void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
   1951                                    DeclSpecContext DSC = DSC_normal);
   1952 
   1953   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
   1954                                   Declarator::TheContext Context);
   1955 
   1956   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
   1957                           const ParsedTemplateInfo &TemplateInfo,
   1958                           AccessSpecifier AS, DeclSpecContext DSC);
   1959   void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
   1960   void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
   1961                             Decl *TagDecl);
   1962 
   1963   void ParseStructDeclaration(
   1964       ParsingDeclSpec &DS,
   1965       llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
   1966 
   1967   bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
   1968   bool isTypeSpecifierQualifier();
   1969 
   1970   /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
   1971   /// is definitely a type-specifier.  Return false if it isn't part of a type
   1972   /// specifier or if we're not sure.
   1973   bool isKnownToBeTypeSpecifier(const Token &Tok) const;
   1974 
   1975   /// \brief Return true if we know that we are definitely looking at a
   1976   /// decl-specifier, and isn't part of an expression such as a function-style
   1977   /// cast. Return false if it's no a decl-specifier, or we're not sure.
   1978   bool isKnownToBeDeclarationSpecifier() {
   1979     if (getLangOpts().CPlusPlus)
   1980       return isCXXDeclarationSpecifier() == TPResult::True;
   1981     return isDeclarationSpecifier(true);
   1982   }
   1983 
   1984   /// isDeclarationStatement - Disambiguates between a declaration or an
   1985   /// expression statement, when parsing function bodies.
   1986   /// Returns true for declaration, false for expression.
   1987   bool isDeclarationStatement() {
   1988     if (getLangOpts().CPlusPlus)
   1989       return isCXXDeclarationStatement();
   1990     return isDeclarationSpecifier(true);
   1991   }
   1992 
   1993   /// isForInitDeclaration - Disambiguates between a declaration or an
   1994   /// expression in the context of the C 'clause-1' or the C++
   1995   // 'for-init-statement' part of a 'for' statement.
   1996   /// Returns true for declaration, false for expression.
   1997   bool isForInitDeclaration() {
   1998     if (getLangOpts().CPlusPlus)
   1999       return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
   2000     return isDeclarationSpecifier(true);
   2001   }
   2002 
   2003   /// \brief Determine whether this is a C++1z for-range-identifier.
   2004   bool isForRangeIdentifier();
   2005 
   2006   /// \brief Determine whether we are currently at the start of an Objective-C
   2007   /// class message that appears to be missing the open bracket '['.
   2008   bool isStartOfObjCClassMessageMissingOpenBracket();
   2009 
   2010   /// \brief Starting with a scope specifier, identifier, or
   2011   /// template-id that refers to the current class, determine whether
   2012   /// this is a constructor declarator.
   2013   bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
   2014 
   2015   /// \brief Specifies the context in which type-id/expression
   2016   /// disambiguation will occur.
   2017   enum TentativeCXXTypeIdContext {
   2018     TypeIdInParens,
   2019     TypeIdUnambiguous,
   2020     TypeIdAsTemplateArgument
   2021   };
   2022 
   2023 
   2024   /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
   2025   /// whether the parens contain an expression or a type-id.
   2026   /// Returns true for a type-id and false for an expression.
   2027   bool isTypeIdInParens(bool &isAmbiguous) {
   2028     if (getLangOpts().CPlusPlus)
   2029       return isCXXTypeId(TypeIdInParens, isAmbiguous);
   2030     isAmbiguous = false;
   2031     return isTypeSpecifierQualifier();
   2032   }
   2033   bool isTypeIdInParens() {
   2034     bool isAmbiguous;
   2035     return isTypeIdInParens(isAmbiguous);
   2036   }
   2037 
   2038   /// \brief Checks if the current tokens form type-id or expression.
   2039   /// It is similar to isTypeIdInParens but does not suppose that type-id
   2040   /// is in parenthesis.
   2041   bool isTypeIdUnambiguously() {
   2042     bool IsAmbiguous;
   2043     if (getLangOpts().CPlusPlus)
   2044       return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
   2045     return isTypeSpecifierQualifier();
   2046   }
   2047 
   2048   /// isCXXDeclarationStatement - C++-specialized function that disambiguates
   2049   /// between a declaration or an expression statement, when parsing function
   2050   /// bodies. Returns true for declaration, false for expression.
   2051   bool isCXXDeclarationStatement();
   2052 
   2053   /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
   2054   /// between a simple-declaration or an expression-statement.
   2055   /// If during the disambiguation process a parsing error is encountered,
   2056   /// the function returns true to let the declaration parsing code handle it.
   2057   /// Returns false if the statement is disambiguated as expression.
   2058   bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
   2059 
   2060   /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
   2061   /// a constructor-style initializer, when parsing declaration statements.
   2062   /// Returns true for function declarator and false for constructor-style
   2063   /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
   2064   /// might be a constructor-style initializer.
   2065   /// If during the disambiguation process a parsing error is encountered,
   2066   /// the function returns true to let the declaration parsing code handle it.
   2067   bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
   2068 
   2069   struct ConditionDeclarationOrInitStatementState;
   2070   enum class ConditionOrInitStatement {
   2071     Expression,    ///< Disambiguated as an expression (either kind).
   2072     ConditionDecl, ///< Disambiguated as the declaration form of condition.
   2073     InitStmtDecl,  ///< Disambiguated as a simple-declaration init-statement.
   2074     Error          ///< Can't be any of the above!
   2075   };
   2076   /// \brief Disambiguates between the different kinds of things that can happen
   2077   /// after 'if (' or 'switch ('. This could be one of two different kinds of
   2078   /// declaration (depending on whether there is a ';' later) or an expression.
   2079   ConditionOrInitStatement
   2080   isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt);
   2081 
   2082   bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
   2083   bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
   2084     bool isAmbiguous;
   2085     return isCXXTypeId(Context, isAmbiguous);
   2086   }
   2087 
   2088   /// TPResult - Used as the result value for functions whose purpose is to
   2089   /// disambiguate C++ constructs by "tentatively parsing" them.
   2090   enum class TPResult {
   2091     True, False, Ambiguous, Error
   2092   };
   2093 
   2094   /// \brief Based only on the given token kind, determine whether we know that
   2095   /// we're at the start of an expression or a type-specifier-seq (which may
   2096   /// be an expression, in C++).
   2097   ///
   2098   /// This routine does not attempt to resolve any of the trick cases, e.g.,
   2099   /// those involving lookup of identifiers.
   2100   ///
   2101   /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
   2102   /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
   2103   /// tell.
   2104   TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
   2105 
   2106   /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
   2107   /// declaration specifier, TPResult::False if it is not,
   2108   /// TPResult::Ambiguous if it could be either a decl-specifier or a
   2109   /// function-style cast, and TPResult::Error if a parsing error was
   2110   /// encountered. If it could be a braced C++11 function-style cast, returns
   2111   /// BracedCastResult.
   2112   /// Doesn't consume tokens.
   2113   TPResult
   2114   isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
   2115                             bool *HasMissingTypename = nullptr);
   2116 
   2117   /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
   2118   /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
   2119   /// a type-specifier other than a cv-qualifier.
   2120   bool isCXXDeclarationSpecifierAType();
   2121 
   2122   /// \brief Determine whether an identifier has been tentatively declared as a
   2123   /// non-type. Such tentative declarations should not be found to name a type
   2124   /// during a tentative parse, but also should not be annotated as a non-type.
   2125   bool isTentativelyDeclared(IdentifierInfo *II);
   2126 
   2127   // "Tentative parsing" functions, used for disambiguation. If a parsing error
   2128   // is encountered they will return TPResult::Error.
   2129   // Returning TPResult::True/False indicates that the ambiguity was
   2130   // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
   2131   // that more tentative parsing is necessary for disambiguation.
   2132   // They all consume tokens, so backtracking should be used after calling them.
   2133 
   2134   TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
   2135   TPResult TryParseTypeofSpecifier();
   2136   TPResult TryParseProtocolQualifiers();
   2137   TPResult TryParsePtrOperatorSeq();
   2138   TPResult TryParseOperatorId();
   2139   TPResult TryParseInitDeclaratorList();
   2140   TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
   2141   TPResult
   2142   TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
   2143                                      bool VersusTemplateArg = false);
   2144   TPResult TryParseFunctionDeclarator();
   2145   TPResult TryParseBracketDeclarator();
   2146   TPResult TryConsumeDeclarationSpecifier();
   2147 
   2148 public:
   2149   TypeResult ParseTypeName(SourceRange *Range = nullptr,
   2150                            Declarator::TheContext Context
   2151                              = Declarator::TypeNameContext,
   2152                            AccessSpecifier AS = AS_none,
   2153                            Decl **OwnedType = nullptr,
   2154                            ParsedAttributes *Attrs = nullptr);
   2155 
   2156 private:
   2157   void ParseBlockId(SourceLocation CaretLoc);
   2158 
   2159   // Check for the start of a C++11 attribute-specifier-seq in a context where
   2160   // an attribute is not allowed.
   2161   bool CheckProhibitedCXX11Attribute() {
   2162     assert(Tok.is(tok::l_square));
   2163     if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
   2164       return false;
   2165     return DiagnoseProhibitedCXX11Attribute();
   2166   }
   2167   bool DiagnoseProhibitedCXX11Attribute();
   2168   void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
   2169                                     SourceLocation CorrectLocation) {
   2170     if (!getLangOpts().CPlusPlus11)
   2171       return;
   2172     if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
   2173         Tok.isNot(tok::kw_alignas))
   2174       return;
   2175     DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
   2176   }
   2177   void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
   2178                                        SourceLocation CorrectLocation);
   2179 
   2180   void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
   2181                                       DeclSpec &DS, Sema::TagUseKind TUK);
   2182 
   2183   void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
   2184     if (!attrs.Range.isValid()) return;
   2185     DiagnoseProhibitedAttributes(attrs);
   2186     attrs.clear();
   2187   }
   2188   void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
   2189 
   2190   // Forbid C++11 attributes that appear on certain syntactic
   2191   // locations which standard permits but we don't supported yet,
   2192   // for example, attributes appertain to decl specifiers.
   2193   void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
   2194                                unsigned DiagID);
   2195 
   2196   /// \brief Skip C++11 attributes and return the end location of the last one.
   2197   /// \returns SourceLocation() if there are no attributes.
   2198   SourceLocation SkipCXX11Attributes();
   2199 
   2200   /// \brief Diagnose and skip C++11 attributes that appear in syntactic
   2201   /// locations where attributes are not allowed.
   2202   void DiagnoseAndSkipCXX11Attributes();
   2203 
   2204   /// \brief Parses syntax-generic attribute arguments for attributes which are
   2205   /// known to the implementation, and adds them to the given ParsedAttributes
   2206   /// list with the given attribute syntax. Returns the number of arguments
   2207   /// parsed for the attribute.
   2208   unsigned
   2209   ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
   2210                            ParsedAttributes &Attrs, SourceLocation *EndLoc,
   2211                            IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
   2212                            AttributeList::Syntax Syntax);
   2213 
   2214   void MaybeParseGNUAttributes(Declarator &D,
   2215                                LateParsedAttrList *LateAttrs = nullptr) {
   2216     if (Tok.is(tok::kw___attribute)) {
   2217       ParsedAttributes attrs(AttrFactory);
   2218       SourceLocation endLoc;
   2219       ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
   2220       D.takeAttributes(attrs, endLoc);
   2221     }
   2222   }
   2223   void MaybeParseGNUAttributes(ParsedAttributes &attrs,
   2224                                SourceLocation *endLoc = nullptr,
   2225                                LateParsedAttrList *LateAttrs = nullptr) {
   2226     if (Tok.is(tok::kw___attribute))
   2227       ParseGNUAttributes(attrs, endLoc, LateAttrs);
   2228   }
   2229   void ParseGNUAttributes(ParsedAttributes &attrs,
   2230                           SourceLocation *endLoc = nullptr,
   2231                           LateParsedAttrList *LateAttrs = nullptr,
   2232                           Declarator *D = nullptr);
   2233   void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
   2234                              SourceLocation AttrNameLoc,
   2235                              ParsedAttributes &Attrs,
   2236                              SourceLocation *EndLoc,
   2237                              IdentifierInfo *ScopeName,
   2238                              SourceLocation ScopeLoc,
   2239                              AttributeList::Syntax Syntax,
   2240                              Declarator *D);
   2241   IdentifierLoc *ParseIdentifierLoc();
   2242 
   2243   unsigned
   2244   ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
   2245                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
   2246                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
   2247                           AttributeList::Syntax Syntax);
   2248 
   2249   void MaybeParseCXX11Attributes(Declarator &D) {
   2250     if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
   2251       ParsedAttributesWithRange attrs(AttrFactory);
   2252       SourceLocation endLoc;
   2253       ParseCXX11Attributes(attrs, &endLoc);
   2254       D.takeAttributes(attrs, endLoc);
   2255     }
   2256   }
   2257   void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
   2258                                  SourceLocation *endLoc = nullptr) {
   2259     if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
   2260       ParsedAttributesWithRange attrsWithRange(AttrFactory);
   2261       ParseCXX11Attributes(attrsWithRange, endLoc);
   2262       attrs.takeAllFrom(attrsWithRange);
   2263     }
   2264   }
   2265   void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
   2266                                  SourceLocation *endLoc = nullptr,
   2267                                  bool OuterMightBeMessageSend = false) {
   2268     if (getLangOpts().CPlusPlus11 &&
   2269         isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
   2270       ParseCXX11Attributes(attrs, endLoc);
   2271   }
   2272 
   2273   void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
   2274                                     SourceLocation *EndLoc = nullptr);
   2275   void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
   2276                             SourceLocation *EndLoc = nullptr);
   2277   /// \brief Parses a C++-style attribute argument list. Returns true if this
   2278   /// results in adding an attribute to the ParsedAttributes list.
   2279   bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
   2280                                SourceLocation AttrNameLoc,
   2281                                ParsedAttributes &Attrs, SourceLocation *EndLoc,
   2282                                IdentifierInfo *ScopeName,
   2283                                SourceLocation ScopeLoc);
   2284 
   2285   IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
   2286 
   2287   void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
   2288                                      SourceLocation *endLoc = nullptr) {
   2289     if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
   2290       ParseMicrosoftAttributes(attrs, endLoc);
   2291   }
   2292   void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
   2293   void ParseMicrosoftAttributes(ParsedAttributes &attrs,
   2294                                 SourceLocation *endLoc = nullptr);
   2295   void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
   2296                                     SourceLocation *End = nullptr) {
   2297     const auto &LO = getLangOpts();
   2298     if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
   2299       ParseMicrosoftDeclSpecs(Attrs, End);
   2300   }
   2301   void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
   2302                                SourceLocation *End = nullptr);
   2303   bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
   2304                                   SourceLocation AttrNameLoc,
   2305                                   ParsedAttributes &Attrs);
   2306   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
   2307   void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
   2308   SourceLocation SkipExtendedMicrosoftTypeAttributes();
   2309   void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
   2310   void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
   2311   void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
   2312   void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
   2313   /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0
   2314   /// or higher.
   2315   /// \return false if error happens.
   2316   bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
   2317     if (getLangOpts().OpenCL)
   2318       return ParseOpenCLUnrollHintAttribute(Attrs);
   2319     return true;
   2320   }
   2321   /// \brief Parses opencl_unroll_hint attribute.
   2322   /// \return false if error happens.
   2323   bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
   2324   void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
   2325 
   2326   VersionTuple ParseVersionTuple(SourceRange &Range);
   2327   void ParseAvailabilityAttribute(IdentifierInfo &Availability,
   2328                                   SourceLocation AvailabilityLoc,
   2329                                   ParsedAttributes &attrs,
   2330                                   SourceLocation *endLoc,
   2331                                   IdentifierInfo *ScopeName,
   2332                                   SourceLocation ScopeLoc,
   2333                                   AttributeList::Syntax Syntax);
   2334 
   2335   Optional<AvailabilitySpec> ParseAvailabilitySpec();
   2336   ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
   2337 
   2338   void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
   2339                                           SourceLocation Loc,
   2340                                           ParsedAttributes &Attrs,
   2341                                           SourceLocation *EndLoc,
   2342                                           IdentifierInfo *ScopeName,
   2343                                           SourceLocation ScopeLoc,
   2344                                           AttributeList::Syntax Syntax);
   2345 
   2346   void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
   2347                                        SourceLocation ObjCBridgeRelatedLoc,
   2348                                        ParsedAttributes &attrs,
   2349                                        SourceLocation *endLoc,
   2350                                        IdentifierInfo *ScopeName,
   2351                                        SourceLocation ScopeLoc,
   2352                                        AttributeList::Syntax Syntax);
   2353 
   2354   void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
   2355                                         SourceLocation AttrNameLoc,
   2356                                         ParsedAttributes &Attrs,
   2357                                         SourceLocation *EndLoc,
   2358                                         IdentifierInfo *ScopeName,
   2359                                         SourceLocation ScopeLoc,
   2360                                         AttributeList::Syntax Syntax);
   2361 
   2362   void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
   2363                                  SourceLocation AttrNameLoc,
   2364                                  ParsedAttributes &Attrs,
   2365                                  SourceLocation *EndLoc,
   2366                                  IdentifierInfo *ScopeName,
   2367                                  SourceLocation ScopeLoc,
   2368                                  AttributeList::Syntax Syntax);
   2369 
   2370   void ParseTypeofSpecifier(DeclSpec &DS);
   2371   SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
   2372   void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
   2373                                          SourceLocation StartLoc,
   2374                                          SourceLocation EndLoc);
   2375   void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
   2376   void ParseAtomicSpecifier(DeclSpec &DS);
   2377 
   2378   ExprResult ParseAlignArgument(SourceLocation Start,
   2379                                 SourceLocation &EllipsisLoc);
   2380   void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
   2381                                SourceLocation *endLoc = nullptr);
   2382 
   2383   VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
   2384   VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
   2385     return isCXX11VirtSpecifier(Tok);
   2386   }
   2387   void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
   2388                                           SourceLocation FriendLoc);
   2389 
   2390   bool isCXX11FinalKeyword() const;
   2391 
   2392   /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
   2393   /// enter a new C++ declarator scope and exit it when the function is
   2394   /// finished.
   2395   class DeclaratorScopeObj {
   2396     Parser &P;
   2397     CXXScopeSpec &SS;
   2398     bool EnteredScope;
   2399     bool CreatedScope;
   2400   public:
   2401     DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
   2402       : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
   2403 
   2404     void EnterDeclaratorScope() {
   2405       assert(!EnteredScope && "Already entered the scope!");
   2406       assert(SS.isSet() && "C++ scope was not set!");
   2407 
   2408       CreatedScope = true;
   2409       P.EnterScope(0); // Not a decl scope.
   2410 
   2411       if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
   2412         EnteredScope = true;
   2413     }
   2414 
   2415     ~DeclaratorScopeObj() {
   2416       if (EnteredScope) {
   2417         assert(SS.isSet() && "C++ scope was cleared ?");
   2418         P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
   2419       }
   2420       if (CreatedScope)
   2421         P.ExitScope();
   2422     }
   2423   };
   2424 
   2425   /// ParseDeclarator - Parse and verify a newly-initialized declarator.
   2426   void ParseDeclarator(Declarator &D);
   2427   /// A function that parses a variant of direct-declarator.
   2428   typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
   2429   void ParseDeclaratorInternal(Declarator &D,
   2430                                DirectDeclParseFunction DirectDeclParser);
   2431 
   2432   enum AttrRequirements {
   2433     AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
   2434     AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
   2435     AR_GNUAttributesParsed = 1 << 1,
   2436     AR_CXX11AttributesParsed = 1 << 2,
   2437     AR_DeclspecAttributesParsed = 1 << 3,
   2438     AR_AllAttributesParsed = AR_GNUAttributesParsed |
   2439                              AR_CXX11AttributesParsed |
   2440                              AR_DeclspecAttributesParsed,
   2441     AR_VendorAttributesParsed = AR_GNUAttributesParsed |
   2442                                 AR_DeclspecAttributesParsed
   2443   };
   2444 
   2445   void ParseTypeQualifierListOpt(
   2446       DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
   2447       bool AtomicAllowed = true, bool IdentifierRequired = false,
   2448       Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
   2449   void ParseDirectDeclarator(Declarator &D);
   2450   void ParseDecompositionDeclarator(Declarator &D);
   2451   void ParseParenDeclarator(Declarator &D);
   2452   void ParseFunctionDeclarator(Declarator &D,
   2453                                ParsedAttributes &attrs,
   2454                                BalancedDelimiterTracker &Tracker,
   2455                                bool IsAmbiguous,
   2456                                bool RequiresArg = false);
   2457   bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
   2458                          SourceLocation &RefQualifierLoc);
   2459   bool isFunctionDeclaratorIdentifierList();
   2460   void ParseFunctionDeclaratorIdentifierList(
   2461          Declarator &D,
   2462          SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
   2463   void ParseParameterDeclarationClause(
   2464          Declarator &D,
   2465          ParsedAttributes &attrs,
   2466          SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
   2467          SourceLocation &EllipsisLoc);
   2468   void ParseBracketDeclarator(Declarator &D);
   2469   void ParseMisplacedBracketDeclarator(Declarator &D);
   2470 
   2471   //===--------------------------------------------------------------------===//
   2472   // C++ 7: Declarations [dcl.dcl]
   2473 
   2474   /// The kind of attribute specifier we have found.
   2475   enum CXX11AttributeKind {
   2476     /// This is not an attribute specifier.
   2477     CAK_NotAttributeSpecifier,
   2478     /// This should be treated as an attribute-specifier.
   2479     CAK_AttributeSpecifier,
   2480     /// The next tokens are '[[', but this is not an attribute-specifier. This
   2481     /// is ill-formed by C++11 [dcl.attr.grammar]p6.
   2482     CAK_InvalidAttributeSpecifier
   2483   };
   2484   CXX11AttributeKind
   2485   isCXX11AttributeSpecifier(bool Disambiguate = false,
   2486                             bool OuterMightBeMessageSend = false);
   2487 
   2488   void DiagnoseUnexpectedNamespace(NamedDecl *Context);
   2489 
   2490   DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
   2491                                 SourceLocation InlineLoc = SourceLocation());
   2492   void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
   2493                            std::vector<IdentifierInfo*>& Ident,
   2494                            std::vector<SourceLocation>& NamespaceLoc,
   2495                            unsigned int index, SourceLocation& InlineLoc,
   2496                            ParsedAttributes& attrs,
   2497                            BalancedDelimiterTracker &Tracker);
   2498   Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
   2499   Decl *ParseExportDeclaration();
   2500   DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
   2501       unsigned Context, const ParsedTemplateInfo &TemplateInfo,
   2502       SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
   2503   Decl *ParseUsingDirective(unsigned Context,
   2504                             SourceLocation UsingLoc,
   2505                             SourceLocation &DeclEnd,
   2506                             ParsedAttributes &attrs);
   2507 
   2508   struct UsingDeclarator {
   2509     SourceLocation TypenameLoc;
   2510     CXXScopeSpec SS;
   2511     SourceLocation TemplateKWLoc;
   2512     UnqualifiedId Name;
   2513     SourceLocation EllipsisLoc;
   2514 
   2515     void clear() {
   2516       TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation();
   2517       SS.clear();
   2518       Name.clear();
   2519     }
   2520   };
   2521 
   2522   bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D);
   2523   DeclGroupPtrTy ParseUsingDeclaration(unsigned Context,
   2524                                        const ParsedTemplateInfo &TemplateInfo,
   2525                                        SourceLocation UsingLoc,
   2526                                        SourceLocation &DeclEnd,
   2527                                        AccessSpecifier AS = AS_none);
   2528   Decl *ParseAliasDeclarationAfterDeclarator(
   2529       const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
   2530       UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
   2531       ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
   2532 
   2533   Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
   2534   Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
   2535                             SourceLocation AliasLoc, IdentifierInfo *Alias,
   2536                             SourceLocation &DeclEnd);
   2537 
   2538   //===--------------------------------------------------------------------===//
   2539   // C++ 9: classes [class] and C structs/unions.
   2540   bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
   2541   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
   2542                            DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
   2543                            AccessSpecifier AS, bool EnteringContext,
   2544                            DeclSpecContext DSC,
   2545                            ParsedAttributesWithRange &Attributes);
   2546   void SkipCXXMemberSpecification(SourceLocation StartLoc,
   2547                                   SourceLocation AttrFixitLoc,
   2548                                   unsigned TagType,
   2549                                   Decl *TagDecl);
   2550   void ParseCXXMemberSpecification(SourceLocation StartLoc,
   2551                                    SourceLocation AttrFixitLoc,
   2552                                    ParsedAttributesWithRange &Attrs,
   2553                                    unsigned TagType,
   2554                                    Decl *TagDecl);
   2555   ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
   2556                                        SourceLocation &EqualLoc);
   2557   bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
   2558                                                  VirtSpecifiers &VS,
   2559                                                  ExprResult &BitfieldSize,
   2560                                                  LateParsedAttrList &LateAttrs);
   2561   void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
   2562                                                                VirtSpecifiers &VS);
   2563   DeclGroupPtrTy ParseCXXClassMemberDeclaration(
   2564       AccessSpecifier AS, AttributeList *Attr,
   2565       const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   2566       ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
   2567   DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
   2568       AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
   2569       DeclSpec::TST TagType, Decl *Tag);
   2570   void ParseConstructorInitializer(Decl *ConstructorDecl);
   2571   MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
   2572   void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
   2573                                       Decl *ThisDecl);
   2574 
   2575   //===--------------------------------------------------------------------===//
   2576   // C++ 10: Derived classes [class.derived]
   2577   TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
   2578                                     SourceLocation &EndLocation);
   2579   void ParseBaseClause(Decl *ClassDecl);
   2580   BaseResult ParseBaseSpecifier(Decl *ClassDecl);
   2581   AccessSpecifier getAccessSpecifierIfPresent() const;
   2582 
   2583   bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
   2584                                     SourceLocation TemplateKWLoc,
   2585                                     IdentifierInfo *Name,
   2586                                     SourceLocation NameLoc,
   2587                                     bool EnteringContext,
   2588                                     ParsedType ObjectType,
   2589                                     UnqualifiedId &Id,
   2590                                     bool AssumeTemplateId);
   2591   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
   2592                                   ParsedType ObjectType,
   2593                                   UnqualifiedId &Result);
   2594 
   2595   //===--------------------------------------------------------------------===//
   2596   // OpenMP: Directives and clauses.
   2597   /// Parse clauses for '#pragma omp declare simd'.
   2598   DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
   2599                                             CachedTokens &Toks,
   2600                                             SourceLocation Loc);
   2601   /// \brief Parses declarative OpenMP directives.
   2602   DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
   2603       AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
   2604       DeclSpec::TST TagType = DeclSpec::TST_unspecified,
   2605       Decl *TagDecl = nullptr);
   2606   /// \brief Parse 'omp declare reduction' construct.
   2607   DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
   2608 
   2609   /// \brief Parses simple list of variables.
   2610   ///
   2611   /// \param Kind Kind of the directive.
   2612   /// \param Callback Callback function to be called for the list elements.
   2613   /// \param AllowScopeSpecifier true, if the variables can have fully
   2614   /// qualified names.
   2615   ///
   2616   bool ParseOpenMPSimpleVarList(
   2617       OpenMPDirectiveKind Kind,
   2618       const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
   2619           Callback,
   2620       bool AllowScopeSpecifier);
   2621   /// \brief Parses declarative or executable directive.
   2622   ///
   2623   /// \param Allowed ACK_Any, if any directives are allowed,
   2624   /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
   2625   /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
   2626   /// executable directives are allowed.
   2627   ///
   2628   StmtResult
   2629   ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
   2630   /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
   2631   ///
   2632   /// \param DKind Kind of current directive.
   2633   /// \param CKind Kind of current clause.
   2634   /// \param FirstClause true, if this is the first clause of a kind \a CKind
   2635   /// in current directive.
   2636   ///
   2637   OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
   2638                                OpenMPClauseKind CKind, bool FirstClause);
   2639   /// \brief Parses clause with a single expression of a kind \a Kind.
   2640   ///
   2641   /// \param Kind Kind of current clause.
   2642   ///
   2643   OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
   2644   /// \brief Parses simple clause of a kind \a Kind.
   2645   ///
   2646   /// \param Kind Kind of current clause.
   2647   ///
   2648   OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
   2649   /// \brief Parses clause with a single expression and an additional argument
   2650   /// of a kind \a Kind.
   2651   ///
   2652   /// \param Kind Kind of current clause.
   2653   ///
   2654   OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
   2655   /// \brief Parses clause without any additional arguments.
   2656   ///
   2657   /// \param Kind Kind of current clause.
   2658   ///
   2659   OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
   2660   /// \brief Parses clause with the list of variables of a kind \a Kind.
   2661   ///
   2662   /// \param Kind Kind of current clause.
   2663   ///
   2664   OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
   2665                                       OpenMPClauseKind Kind);
   2666 
   2667 public:
   2668   /// Parses simple expression in parens for single-expression clauses of OpenMP
   2669   /// constructs.
   2670   /// \param RLoc Returned location of right paren.
   2671   ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
   2672 
   2673   /// Data used for parsing list of variables in OpenMP clauses.
   2674   struct OpenMPVarListDataTy {
   2675     Expr *TailExpr = nullptr;
   2676     SourceLocation ColonLoc;
   2677     CXXScopeSpec ReductionIdScopeSpec;
   2678     DeclarationNameInfo ReductionId;
   2679     OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
   2680     OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
   2681     OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
   2682     OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
   2683     bool IsMapTypeImplicit = false;
   2684     SourceLocation DepLinMapLoc;
   2685   };
   2686 
   2687   /// Parses clauses with list.
   2688   bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
   2689                           SmallVectorImpl<Expr *> &Vars,
   2690                           OpenMPVarListDataTy &Data);
   2691   bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
   2692                           bool AllowDestructorName,
   2693                           bool AllowConstructorName,
   2694                           bool AllowDeductionGuide,
   2695                           ParsedType ObjectType,
   2696                           SourceLocation& TemplateKWLoc,
   2697                           UnqualifiedId &Result);
   2698 
   2699 private:
   2700   //===--------------------------------------------------------------------===//
   2701   // C++ 14: Templates [temp]
   2702 
   2703   // C++ 14.1: Template Parameters [temp.param]
   2704   Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
   2705                                           SourceLocation &DeclEnd,
   2706                                           AccessSpecifier AS = AS_none,
   2707                                           AttributeList *AccessAttrs = nullptr);
   2708   Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
   2709                                                  SourceLocation &DeclEnd,
   2710                                                  AccessSpecifier AS,
   2711                                                  AttributeList *AccessAttrs);
   2712   Decl *ParseSingleDeclarationAfterTemplate(
   2713                                        unsigned Context,
   2714                                        const ParsedTemplateInfo &TemplateInfo,
   2715                                        ParsingDeclRAIIObject &DiagsFromParams,
   2716                                        SourceLocation &DeclEnd,
   2717                                        AccessSpecifier AS=AS_none,
   2718                                        AttributeList *AccessAttrs = nullptr);
   2719   bool ParseTemplateParameters(unsigned Depth,
   2720                                SmallVectorImpl<Decl*> &TemplateParams,
   2721                                SourceLocation &LAngleLoc,
   2722                                SourceLocation &RAngleLoc);
   2723   bool ParseTemplateParameterList(unsigned Depth,
   2724                                   SmallVectorImpl<Decl*> &TemplateParams);
   2725   bool isStartOfTemplateTypeParameter();
   2726   Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
   2727   Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
   2728   Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
   2729   Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
   2730   void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
   2731                                  SourceLocation CorrectLoc,
   2732                                  bool AlreadyHasEllipsis,
   2733                                  bool IdentifierHasName);
   2734   void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
   2735                                              Declarator &D);
   2736   // C++ 14.3: Template arguments [temp.arg]
   2737   typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
   2738 
   2739   bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
   2740                                       bool ConsumeLastToken,
   2741                                       bool ObjCGenericList);
   2742   bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
   2743                                         SourceLocation &LAngleLoc,
   2744                                         TemplateArgList &TemplateArgs,
   2745                                         SourceLocation &RAngleLoc);
   2746 
   2747   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
   2748                                CXXScopeSpec &SS,
   2749                                SourceLocation TemplateKWLoc,
   2750                                UnqualifiedId &TemplateName,
   2751                                bool AllowTypeAnnotation = true);
   2752   void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
   2753   bool IsTemplateArgumentList(unsigned Skip = 0);
   2754   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
   2755   ParsedTemplateArgument ParseTemplateTemplateArgument();
   2756   ParsedTemplateArgument ParseTemplateArgument();
   2757   Decl *ParseExplicitInstantiation(unsigned Context,
   2758                                    SourceLocation ExternLoc,
   2759                                    SourceLocation TemplateLoc,
   2760                                    SourceLocation &DeclEnd,
   2761                                    AccessSpecifier AS = AS_none);
   2762 
   2763   //===--------------------------------------------------------------------===//
   2764   // Modules
   2765   DeclGroupPtrTy ParseModuleDecl();
   2766   DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
   2767   bool parseMisplacedModuleImport();
   2768   bool tryParseMisplacedModuleImport() {
   2769     tok::TokenKind Kind = Tok.getKind();
   2770     if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
   2771         Kind == tok::annot_module_include)
   2772       return parseMisplacedModuleImport();
   2773     return false;
   2774   }
   2775 
   2776   bool ParseModuleName(
   2777       SourceLocation UseLoc,
   2778       SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
   2779       bool IsImport);
   2780 
   2781   //===--------------------------------------------------------------------===//
   2782   // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
   2783   ExprResult ParseTypeTrait();
   2784 
   2785   //===--------------------------------------------------------------------===//
   2786   // Embarcadero: Arary and Expression Traits
   2787   ExprResult ParseArrayTypeTrait();
   2788   ExprResult ParseExpressionTrait();
   2789 
   2790   //===--------------------------------------------------------------------===//
   2791   // Preprocessor code-completion pass-through
   2792   void CodeCompleteDirective(bool InConditional) override;
   2793   void CodeCompleteInConditionalExclusion() override;
   2794   void CodeCompleteMacroName(bool IsDefinition) override;
   2795   void CodeCompletePreprocessorExpression() override;
   2796   void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
   2797                                  unsigned ArgumentIndex) override;
   2798   void CodeCompleteNaturalLanguage() override;
   2799 };
   2800 
   2801 }  // end namespace clang
   2802 
   2803 #endif
   2804