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