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