11558Srgrimes//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
292058Sobrien//
392058Sobrien// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
492058Sobrien// See https://llvm.org/LICENSE.txt for license information.
51558Srgrimes// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61558Srgrimes//
71558Srgrimes//===----------------------------------------------------------------------===//
81558Srgrimes//
91558Srgrimes//  This file defines the Parser interface.
101558Srgrimes//
111558Srgrimes//===----------------------------------------------------------------------===//
121558Srgrimes
131558Srgrimes#ifndef LLVM_CLANG_PARSE_PARSER_H
141558Srgrimes#define LLVM_CLANG_PARSE_PARSER_H
151558Srgrimes
161558Srgrimes#include "clang/AST/Availability.h"
171558Srgrimes#include "clang/Basic/BitmaskEnum.h"
181558Srgrimes#include "clang/Basic/OpenMPKinds.h"
191558Srgrimes#include "clang/Basic/OperatorPrecedence.h"
201558Srgrimes#include "clang/Basic/Specifiers.h"
211558Srgrimes#include "clang/Lex/CodeCompletionHandler.h"
221558Srgrimes#include "clang/Lex/Preprocessor.h"
2392058Sobrien#include "clang/Sema/DeclSpec.h"
241558Srgrimes#include "clang/Sema/Sema.h"
251558Srgrimes#include "llvm/ADT/SmallVector.h"
261558Srgrimes#include "llvm/Frontend/OpenMP/OMPContext.h"
271558Srgrimes#include "llvm/Support/Compiler.h"
281558Srgrimes#include "llvm/Support/PrettyStackTrace.h"
291558Srgrimes#include "llvm/Support/SaveAndRestore.h"
301558Srgrimes#include <memory>
311558Srgrimes#include <stack>
321558Srgrimes
331558Srgrimesnamespace clang {
341558Srgrimes  class PragmaHandler;
351558Srgrimes  class Scope;
361558Srgrimes  class BalancedDelimiterTracker;
371558Srgrimes  class CorrectionCandidateCallback;
381558Srgrimes  class DeclGroupRef;
3992058Sobrien  class DiagnosticBuilder;
4092058Sobrien  struct LoopHint;
411558Srgrimes  class Parser;
421558Srgrimes  class ParsingDeclRAIIObject;
431558Srgrimes  class ParsingDeclSpec;
4436632Scharnier  class ParsingDeclarator;
451558Srgrimes  class ParsingFieldDeclarator;
461558Srgrimes  class ColonProtectionRAIIObject;
471558Srgrimes  class InMessageExpressionRAIIObject;
481558Srgrimes  class PoisonSEHIdentifiersRAIIObject;
491558Srgrimes  class OMPClause;
5036632Scharnier  class ObjCTypeParamList;
511558Srgrimes  struct OMPTraitProperty;
521558Srgrimes  struct OMPTraitSelector;
5336632Scharnier  struct OMPTraitSet;
541558Srgrimes  class OMPTraitInfo;
551558Srgrimes
5699365Smarkm/// Parser - This implements a parser for the C family of languages.  After
5799365Smarkm/// parsing units of the grammar, productions are invoked to handle whatever has
5899365Smarkm/// been read.
591558Srgrimes///
601558Srgrimesclass Parser : public CodeCompletionHandler {
611558Srgrimes  friend class ColonProtectionRAIIObject;
6213544Sjoerg  friend class ParsingOpenMPDirectiveRAII;
63103669Sphk  friend class InMessageExpressionRAIIObject;
641558Srgrimes  friend class PoisonSEHIdentifiersRAIIObject;
65101994Sbmilekic  friend class ObjCDeclContextSwitch;
661558Srgrimes  friend class ParenBraceBracketBalancer;
67104674Snyan  friend class BalancedDelimiterTracker;
68104674Snyan
69104674Snyan  Preprocessor &PP;
70104272Sphk
71104674Snyan  /// Tok - The current token we are peeking ahead.  All parsing methods assume
7292058Sobrien  /// that this is valid.
7392058Sobrien  Token Tok;
7492058Sobrien
7599365Smarkm  // PrevTokLocation - The location of the token we previously
761558Srgrimes  // consumed. This token is used for diagnostics where we expected to
771558Srgrimes  // see a token following another token (e.g., the ';' at the end of
781558Srgrimes  // a statement).
7913544Sjoerg  SourceLocation PrevTokLocation;
8013544Sjoerg
8113544Sjoerg  /// Tracks an expected type for the current token when parsing an expression.
821558Srgrimes  /// Used by code completion for ranking.
8326542Scharnier  PreferredTypeBuilder PreferredType;
8459216Simp
8599365Smarkm  unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0;
861558Srgrimes  unsigned short MisplacedModuleBeginCount = 0;
871558Srgrimes
881558Srgrimes  /// Actions - These are the callbacks we invoke as we parse various constructs
891558Srgrimes  /// in the file.
901558Srgrimes  Sema &Actions;
911558Srgrimes
921558Srgrimes  DiagnosticsEngine &Diags;
931558Srgrimes
941558Srgrimes  /// ScopeCache - Cache scopes to reduce malloc traffic.
951558Srgrimes  enum { ScopeCacheSize = 16 };
961558Srgrimes  unsigned NumCachedScopes;
971558Srgrimes  Scope *ScopeCache[ScopeCacheSize];
981558Srgrimes
991558Srgrimes  /// Identifiers used for SEH handling in Borland. These are only
1001558Srgrimes  /// allowed in particular circumstances
10173034Sjwd  // __except block
10273034Sjwd  IdentifierInfo *Ident__exception_code,
10373034Sjwd                 *Ident___exception_code,
10473034Sjwd                 *Ident_GetExceptionCode;
10573034Sjwd  // __except filter expression
10673034Sjwd  IdentifierInfo *Ident__exception_info,
10797535Siedowse                 *Ident___exception_info,
10873034Sjwd                 *Ident_GetExceptionInfo;
10973034Sjwd  // __finally
11092057Sobrien  IdentifierInfo *Ident__abnormal_termination,
11192057Sobrien                 *Ident___abnormal_termination,
11297047Sbenno                 *Ident_AbnormalTermination;
1131558Srgrimes
1141558Srgrimes  /// Contextual keywords for Microsoft extensions.
11592057Sobrien  IdentifierInfo *Ident__except;
1161558Srgrimes  mutable IdentifierInfo *Ident_sealed;
1171558Srgrimes
11892541Simp  /// Ident_super - IdentifierInfo for "super", to support fast
11992541Simp  /// comparison.
12092541Simp  IdentifierInfo *Ident_super;
12192541Simp  /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector"
12292541Simp  /// and "bool" fast comparison.  Only present if AltiVec or ZVector are
12392541Simp  /// enabled.
12492541Simp  IdentifierInfo *Ident_vector;
12592541Simp  IdentifierInfo *Ident_bool;
12692541Simp  IdentifierInfo *Ident_Bool;
12792541Simp  /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
12892541Simp  /// Only present if AltiVec enabled.
12997534Siedowse  IdentifierInfo *Ident_pixel;
13092541Simp
13192541Simp  /// Objective-C contextual keywords.
13292541Simp  IdentifierInfo *Ident_instancetype;
13392541Simp
13492541Simp  /// Identifier for "introduced".
13513544Sjoerg  IdentifierInfo *Ident_introduced;
1361558Srgrimes
1371558Srgrimes  /// Identifier for "deprecated".
1381558Srgrimes  IdentifierInfo *Ident_deprecated;
1391558Srgrimes
1401558Srgrimes  /// Identifier for "obsoleted".
14155742Skris  IdentifierInfo *Ident_obsoleted;
1421558Srgrimes
1431558Srgrimes  /// Identifier for "unavailable".
1441558Srgrimes  IdentifierInfo *Ident_unavailable;
1451558Srgrimes
14699365Smarkm  /// Identifier for "message".
14799365Smarkm  IdentifierInfo *Ident_message;
1481558Srgrimes
14973034Sjwd  /// Identifier for "strict".
15073034Sjwd  IdentifierInfo *Ident_strict;
15173034Sjwd
15273034Sjwd  /// Identifier for "replacement".
15373034Sjwd  IdentifierInfo *Ident_replacement;
15473034Sjwd
1551558Srgrimes  /// Identifiers used by the 'external_source_symbol' attribute.
1561558Srgrimes  IdentifierInfo *Ident_language, *Ident_defined_in,
1571558Srgrimes      *Ident_generated_declaration;
1581558Srgrimes
1591558Srgrimes  /// C++11 contextual keywords.
1601558Srgrimes  mutable IdentifierInfo *Ident_final;
1611558Srgrimes  mutable IdentifierInfo *Ident_GNU_final;
1621558Srgrimes  mutable IdentifierInfo *Ident_override;
1631558Srgrimes
1641558Srgrimes  // C++2a contextual keywords.
1651558Srgrimes  mutable IdentifierInfo *Ident_import;
1661558Srgrimes  mutable IdentifierInfo *Ident_module;
1671558Srgrimes
1681558Srgrimes  // C++ type trait keywords that can be reverted to identifiers and still be
1691558Srgrimes  // used as type traits.
17073034Sjwd  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
1711558Srgrimes
17273034Sjwd  std::unique_ptr<PragmaHandler> AlignHandler;
1731558Srgrimes  std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
17413544Sjoerg  std::unique_ptr<PragmaHandler> OptionsHandler;
17592541Simp  std::unique_ptr<PragmaHandler> PackHandler;
1761558Srgrimes  std::unique_ptr<PragmaHandler> MSStructHandler;
17792715Simp  std::unique_ptr<PragmaHandler> UnusedHandler;
1781558Srgrimes  std::unique_ptr<PragmaHandler> WeakHandler;
17948957Sbillf  std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
1801558Srgrimes  std::unique_ptr<PragmaHandler> FPContractHandler;
1811558Srgrimes  std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
18224359Simp  std::unique_ptr<PragmaHandler> OpenMPHandler;
1831558Srgrimes  std::unique_ptr<PragmaHandler> PCSectionHandler;
1841558Srgrimes  std::unique_ptr<PragmaHandler> MSCommentHandler;
1851558Srgrimes  std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
1861558Srgrimes  std::unique_ptr<PragmaHandler> FloatControlHandler;
1871558Srgrimes  std::unique_ptr<PragmaHandler> MSPointersToMembers;
1881558Srgrimes  std::unique_ptr<PragmaHandler> MSVtorDisp;
1891558Srgrimes  std::unique_ptr<PragmaHandler> MSInitSeg;
1901558Srgrimes  std::unique_ptr<PragmaHandler> MSDataSeg;
1911558Srgrimes  std::unique_ptr<PragmaHandler> MSBSSSeg;
1921558Srgrimes  std::unique_ptr<PragmaHandler> MSConstSeg;
1931558Srgrimes  std::unique_ptr<PragmaHandler> MSCodeSeg;
1941558Srgrimes  std::unique_ptr<PragmaHandler> MSSection;
1951558Srgrimes  std::unique_ptr<PragmaHandler> MSRuntimeChecks;
1961558Srgrimes  std::unique_ptr<PragmaHandler> MSIntrinsic;
1971558Srgrimes  std::unique_ptr<PragmaHandler> MSOptimize;
1981558Srgrimes  std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
1991558Srgrimes  std::unique_ptr<PragmaHandler> OptimizeHandler;
2001558Srgrimes  std::unique_ptr<PragmaHandler> LoopHintHandler;
2011558Srgrimes  std::unique_ptr<PragmaHandler> UnrollHintHandler;
20273034Sjwd  std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
20373034Sjwd  std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
20473034Sjwd  std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
2051558Srgrimes  std::unique_ptr<PragmaHandler> FPHandler;
2061558Srgrimes  std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
2071558Srgrimes  std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
2081558Srgrimes  std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
2091558Srgrimes  std::unique_ptr<PragmaHandler> STDCUnknownHandler;
2101558Srgrimes  std::unique_ptr<PragmaHandler> AttributePragmaHandler;
2111558Srgrimes  std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
2121558Srgrimes  std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
2131558Srgrimes
2141558Srgrimes  std::unique_ptr<CommentHandler> CommentSemaHandler;
2151558Srgrimes
2161558Srgrimes  /// Whether the '>' token acts as an operator or not. This will be
2171558Srgrimes  /// true except when we are parsing an expression within a C++
2181558Srgrimes  /// template argument list, where the '>' closes the template
2191558Srgrimes  /// argument list.
2201558Srgrimes  bool GreaterThanIsOperator;
2211558Srgrimes
2221558Srgrimes  /// ColonIsSacred - When this is false, we aggressively try to recover from
2231558Srgrimes  /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
2241558Srgrimes  /// safe in case statements and a few other things.  This is managed by the
2251558Srgrimes  /// ColonProtectionRAIIObject RAII object.
2261558Srgrimes  bool ColonIsSacred;
2271558Srgrimes
2281558Srgrimes  /// Parsing OpenMP directive mode.
2291558Srgrimes  bool OpenMPDirectiveParsing = false;
2301558Srgrimes
2311558Srgrimes  /// When true, we are directly inside an Objective-C message
2321558Srgrimes  /// send expression.
2331558Srgrimes  ///
2341558Srgrimes  /// This is managed by the \c InMessageExpressionRAIIObject class, and
2351558Srgrimes  /// should not be set directly.
2361558Srgrimes  bool InMessageExpression;
2371558Srgrimes
2381558Srgrimes  /// Gets set to true after calling ProduceSignatureHelp, it is for a
2391558Srgrimes  /// workaround to make sure ProduceSignatureHelp is only called at the deepest
2401558Srgrimes  /// function call.
2411558Srgrimes  bool CalledSignatureHelp = false;
2421558Srgrimes
2431558Srgrimes  /// The "depth" of the template parameters currently being parsed.
2441558Srgrimes  unsigned TemplateParameterDepth;
2451558Srgrimes
2461558Srgrimes  /// Current kind of OpenMP clause
2471558Srgrimes  OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
2481558Srgrimes
2491558Srgrimes  /// RAII class that manages the template parameter depth.
2501558Srgrimes  class TemplateParameterDepthRAII {
2511558Srgrimes    unsigned &Depth;
2521558Srgrimes    unsigned AddedLevels;
25359114Sobrien  public:
2541558Srgrimes    explicit TemplateParameterDepthRAII(unsigned &Depth)
2551558Srgrimes      : Depth(Depth), AddedLevels(0) {}
2561558Srgrimes
2571558Srgrimes    ~TemplateParameterDepthRAII() {
2581558Srgrimes      Depth -= AddedLevels;
2591558Srgrimes    }
26059429Sobrien
2611558Srgrimes    void operator++() {
2621558Srgrimes      ++Depth;
2631558Srgrimes      ++AddedLevels;
2641558Srgrimes    }
26526542Scharnier    void addDepth(unsigned D) {
2661558Srgrimes      Depth += D;
2671558Srgrimes      AddedLevels += D;
2681558Srgrimes    }
26948957Sbillf    void setAddedDepth(unsigned D) {
27048957Sbillf      Depth = Depth - AddedLevels + D;
27148957Sbillf      AddedLevels = D;
2721558Srgrimes    }
2731558Srgrimes
2741558Srgrimes    unsigned getDepth() const { return Depth; }
2751558Srgrimes    unsigned getOriginalDepth() const { return Depth - AddedLevels; }
2761558Srgrimes  };
2771558Srgrimes
2781558Srgrimes  /// Factory object for creating ParsedAttr objects.
2791558Srgrimes  AttributeFactory AttrFactory;
2801558Srgrimes
2811558Srgrimes  /// Gathers and cleans up TemplateIdAnnotations when parsing of a
28226542Scharnier  /// top-level declaration is finished.
2831558Srgrimes  SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
2841558Srgrimes
2851558Srgrimes  void MaybeDestroyTemplateIds() {
2861558Srgrimes    if (!TemplateIds.empty() &&
2871558Srgrimes        (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
2881558Srgrimes      DestroyTemplateIds();
2891558Srgrimes  }
2901558Srgrimes  void DestroyTemplateIds();
2911558Srgrimes
2921558Srgrimes  /// RAII object to destroy TemplateIdAnnotations where possible, from a
2931558Srgrimes  /// likely-good position during parsing.
2941558Srgrimes  struct DestroyTemplateIdAnnotationsRAIIObj {
2951558Srgrimes    Parser &Self;
2961558Srgrimes
2971558Srgrimes    DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
29837865Sbde    ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
29937865Sbde  };
30037865Sbde
30137865Sbde  /// Identifiers which have been declared within a tentative parse.
30237865Sbde  SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
30337865Sbde
30437865Sbde  /// Tracker for '<' tokens that might have been intended to be treated as an
30537865Sbde  /// angle bracket instead of a less-than comparison.
3061558Srgrimes  ///
3071558Srgrimes  /// This happens when the user intends to form a template-id, but typoes the
3081558Srgrimes  /// template-name or forgets a 'template' keyword for a dependent template
3091558Srgrimes  /// name.
3101558Srgrimes  ///
31126542Scharnier  /// We track these locations from the point where we see a '<' with a
31237865Sbde  /// name-like expression on its left until we see a '>' or '>>' that might
31337865Sbde  /// match it.
31437865Sbde  struct AngleBracketTracker {
31537865Sbde    /// Flags used to rank candidate template names when there is more than one
31637865Sbde    /// '<' in a scope.
3171558Srgrimes    enum Priority : unsigned short {
3181558Srgrimes      /// A non-dependent name that is a potential typo for a template name.
3191558Srgrimes      PotentialTypo = 0x0,
3201558Srgrimes      /// A dependent name that might instantiate to a template-name.
3211558Srgrimes      DependentName = 0x2,
3221558Srgrimes
3231558Srgrimes      /// A space appears before the '<' token.
3241558Srgrimes      SpaceBeforeLess = 0x0,
3251558Srgrimes      /// No space before the '<' token
3261558Srgrimes      NoSpaceBeforeLess = 0x1,
3271558Srgrimes
3281558Srgrimes      LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName)
3291558Srgrimes    };
3301558Srgrimes
3311558Srgrimes    struct Loc {
3321558Srgrimes      Expr *TemplateName;
3331558Srgrimes      SourceLocation LessLoc;
3341558Srgrimes      AngleBracketTracker::Priority Priority;
3351558Srgrimes      unsigned short ParenCount, BracketCount, BraceCount;
33626542Scharnier
3371558Srgrimes      bool isActive(Parser &P) const {
3381558Srgrimes        return P.ParenCount == ParenCount && P.BracketCount == BracketCount &&
3391558Srgrimes               P.BraceCount == BraceCount;
3401558Srgrimes      }
3411558Srgrimes
3421558Srgrimes      bool isActiveOrNested(Parser &P) const {
3431558Srgrimes        return isActive(P) || P.ParenCount > ParenCount ||
3441558Srgrimes               P.BracketCount > BracketCount || P.BraceCount > BraceCount;
3451558Srgrimes      }
3461558Srgrimes    };
3471558Srgrimes
3481558Srgrimes    SmallVector<Loc, 8> Locs;
3491558Srgrimes
3501558Srgrimes    /// Add an expression that might have been intended to be a template name.
3511558Srgrimes    /// In the case of ambiguity, we arbitrarily select the innermost such
3521558Srgrimes    /// expression, for example in 'foo < bar < baz', 'bar' is the current
3531558Srgrimes    /// candidate. No attempt is made to track that 'foo' is also a candidate
3541558Srgrimes    /// for the case where we see a second suspicious '>' token.
3551558Srgrimes    void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc,
3561558Srgrimes             Priority Prio) {
3571558Srgrimes      if (!Locs.empty() && Locs.back().isActive(P)) {
3581558Srgrimes        if (Locs.back().Priority <= Prio) {
3591558Srgrimes          Locs.back().TemplateName = TemplateName;
3601558Srgrimes          Locs.back().LessLoc = LessLoc;
3611558Srgrimes          Locs.back().Priority = Prio;
3621558Srgrimes        }
3631558Srgrimes      } else {
36413544Sjoerg        Locs.push_back({TemplateName, LessLoc, Prio,
36592541Simp                        P.ParenCount, P.BracketCount, P.BraceCount});
3661558Srgrimes      }
36792541Simp    }
36813550Sjoerg
36913550Sjoerg    /// Mark the current potential missing template location as having been
37013550Sjoerg    /// handled (this happens if we pass a "corresponding" '>' or '>>' token
37113550Sjoerg    /// or leave a bracket scope).
37213544Sjoerg    void clear(Parser &P) {
37336632Scharnier      while (!Locs.empty() && Locs.back().isActiveOrNested(P))
37436632Scharnier        Locs.pop_back();
3751558Srgrimes    }
3761558Srgrimes
3771558Srgrimes    /// Get the current enclosing expression that might hve been intended to be
3781558Srgrimes    /// a template name.
3791558Srgrimes    Loc *getCurrent(Parser &P) {
3801558Srgrimes      if (!Locs.empty() && Locs.back().isActive(P))
38113544Sjoerg        return &Locs.back();
38292541Simp      return nullptr;
3831558Srgrimes    }
3841558Srgrimes  };
38538384Sdfr
38638384Sdfr  AngleBracketTracker AngleBrackets;
38738384Sdfr
38838384Sdfr  IdentifierInfo *getSEHExceptKeyword();
38992058Sobrien
39092058Sobrien  /// True if we are within an Objective-C container while parsing C-like decls.
39192058Sobrien  ///
39292058Sobrien  /// This is necessary because Sema thinks we have left the container
39392058Sobrien  /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
39492058Sobrien  /// be NULL.
39538411Sbde  bool ParsingInObjCContainer;
39638384Sdfr
39773034Sjwd  /// Whether to skip parsing of function bodies.
39873034Sjwd  ///
39973034Sjwd  /// This option can be used, for example, to speed up searches for
40073034Sjwd  /// declarations/definitions when indexing.
40173034Sjwd  bool SkipFunctionBodies;
40273034Sjwd
40373034Sjwd  /// The location of the expression statement that is being parsed right now.
40473034Sjwd  /// Used to determine if an expression that is being parsed is a statement or
40573034Sjwd  /// just a regular sub-expression.
40673034Sjwd  SourceLocation ExprStatementTokLoc;
40773034Sjwd
40873034Sjwd  /// Flags describing a context in which we're parsing a statement.
40973034Sjwd  enum class ParsedStmtContext {
41073034Sjwd    /// This context permits declarations in language modes where declarations
41173034Sjwd    /// are not statements.
41273034Sjwd    AllowDeclarationsInC = 0x1,
41373034Sjwd    /// This context permits standalone OpenMP directives.
41473034Sjwd    AllowStandaloneOpenMPDirectives = 0x2,
41573034Sjwd    /// This context is at the top level of a GNU statement expression.
41673034Sjwd    InStmtExpr = 0x4,
41773034Sjwd
41873034Sjwd    /// The context of a regular substatement.
41973034Sjwd    SubStmt = 0,
42073034Sjwd    /// The context of a compound-statement.
42173034Sjwd    Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives,
42273034Sjwd
42338411Sbde    LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr)
42473034Sjwd  };
42573034Sjwd
42673034Sjwd  /// Act on an expression statement that might be the last statement in a
42773034Sjwd  /// GNU statement expression. Checks whether we are actually at the end of
42873034Sjwd  /// a statement expression and builds a suitable expression statement.
42973034Sjwd  StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx);
43038384Sdfr
43192058Sobrienpublic:
43273034Sjwd  Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
43392058Sobrien  ~Parser() override;
43492058Sobrien
43592058Sobrien  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
43692058Sobrien  const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
43792058Sobrien  Preprocessor &getPreprocessor() const { return PP; }
43892058Sobrien  Sema &getActions() const { return Actions; }
43992058Sobrien  AttributeFactory &getAttrFactory() { return AttrFactory; }
44092058Sobrien
44192058Sobrien  const Token &getCurToken() const { return Tok; }
44292058Sobrien  Scope *getCurScope() const { return Actions.getCurScope(); }
44392058Sobrien  void incrementMSManglingNumber() const {
44492058Sobrien    return Actions.incrementMSManglingNumber();
44592058Sobrien  }
44692058Sobrien
44792058Sobrien  Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
44892058Sobrien
44992058Sobrien  // Type forwarding.  All of these are statically 'void*', but they may all be
45092058Sobrien  // different actual classes based on the actions in place.
45192058Sobrien  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
45292058Sobrien  typedef OpaquePtr<TemplateName> TemplateTy;
45392058Sobrien
45492058Sobrien  typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
45592058Sobrien
45692058Sobrien  typedef Sema::FullExprArg FullExprArg;
45792058Sobrien
45892058Sobrien  // Parsing methods.
45992058Sobrien
46092058Sobrien  /// Initialize - Warm up the parser.
46192058Sobrien  ///
46292058Sobrien  void Initialize();
46392058Sobrien
46492058Sobrien  /// Parse the first top-level declaration in a translation unit.
46592058Sobrien  bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result);
46692058Sobrien
46792058Sobrien  /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
46892058Sobrien  /// the EOF was encountered.
46992058Sobrien  bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false);
47092058Sobrien  bool ParseTopLevelDecl() {
47173034Sjwd    DeclGroupPtrTy Result;
47273034Sjwd    return ParseTopLevelDecl(Result);
47373034Sjwd  }
47473034Sjwd
475104543Sphk  /// ConsumeToken - Consume the current 'peek token' and lex the next one.
47699365Smarkm  /// This does not work with special tokens: string literals, code completion,
47773034Sjwd  /// annotation tokens and balanced tokens must be handled using the specific
47873034Sjwd  /// consume methods.
47973034Sjwd  /// Returns the location of the consumed token.
48073034Sjwd  SourceLocation ConsumeToken() {
48173034Sjwd    assert(!isTokenSpecial() &&
48273034Sjwd           "Should consume special tokens with Consume*Token");
48373034Sjwd    PrevTokLocation = Tok.getLocation();
48473034Sjwd    PP.Lex(Tok);
48573034Sjwd    return PrevTokLocation;
48673034Sjwd  }
48773034Sjwd
48873034Sjwd  bool TryConsumeToken(tok::TokenKind Expected) {
48973034Sjwd    if (Tok.isNot(Expected))
49073034Sjwd      return false;
49173034Sjwd    assert(!isTokenSpecial() &&
49273034Sjwd           "Should consume special tokens with Consume*Token");
4931558Srgrimes    PrevTokLocation = Tok.getLocation();
4941558Srgrimes    PP.Lex(Tok);
4951558Srgrimes    return true;
4961558Srgrimes  }
4971558Srgrimes
4981558Srgrimes  bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
49913544Sjoerg    if (!TryConsumeToken(Expected))
50092541Simp      return false;
5011558Srgrimes    Loc = PrevTokLocation;
50236632Scharnier    return true;
5031558Srgrimes  }
5041558Srgrimes
50536756Scharnier  /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
50675915Simp  /// current token type.  This should only be used in cases where the type of
5071558Srgrimes  /// the token really isn't known, e.g. in error recovery.
5081558Srgrimes  SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
5091558Srgrimes    if (isTokenParen())
51036756Scharnier      return ConsumeParen();
51136756Scharnier    if (isTokenBracket())
5121558Srgrimes      return ConsumeBracket();
5131558Srgrimes    if (isTokenBrace())
5141558Srgrimes      return ConsumeBrace();
51536632Scharnier    if (isTokenStringLiteral())
5161558Srgrimes      return ConsumeStringToken();
5171558Srgrimes    if (Tok.is(tok::code_completion))
5181558Srgrimes      return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
51940475Sbde                                      : handleUnexpectedCodeCompletionToken();
52040475Sbde    if (Tok.isAnnotation())
5211558Srgrimes      return ConsumeAnnotationToken();
5221558Srgrimes    return ConsumeToken();
5231558Srgrimes  }
52436632Scharnier
5251558Srgrimes
5261558Srgrimes  SourceLocation getEndOfPreviousToken() {
5271558Srgrimes    return PP.getLocForEndOfToken(PrevTokLocation);
5281558Srgrimes  }
5291558Srgrimes
5301558Srgrimes  /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
5311558Srgrimes  /// to the given nullability kind.
5321558Srgrimes  IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
5331558Srgrimes    return Actions.getNullabilityKeyword(nullability);
53492541Simp  }
5351558Srgrimes
53692541Simpprivate:
5371558Srgrimes  //===--------------------------------------------------------------------===//
5381558Srgrimes  // Low-Level token peeking and consumption methods.
5391558Srgrimes  //
54026542Scharnier
5411558Srgrimes  /// isTokenParen - Return true if the cur token is '(' or ')'.
5421558Srgrimes  bool isTokenParen() const {
5431558Srgrimes    return Tok.isOneOf(tok::l_paren, tok::r_paren);
5441558Srgrimes  }
5451558Srgrimes  /// isTokenBracket - Return true if the cur token is '[' or ']'.
5461558Srgrimes  bool isTokenBracket() const {
5471558Srgrimes    return Tok.isOneOf(tok::l_square, tok::r_square);
5481558Srgrimes  }
54936756Scharnier  /// isTokenBrace - Return true if the cur token is '{' or '}'.
55036756Scharnier  bool isTokenBrace() const {
55136756Scharnier    return Tok.isOneOf(tok::l_brace, tok::r_brace);
5521558Srgrimes  }
5531558Srgrimes  /// isTokenStringLiteral - True if this token is a string-literal.
5541558Srgrimes  bool isTokenStringLiteral() const {
55526542Scharnier    return tok::isStringLiteral(Tok.getKind());
5561558Srgrimes  }
5571558Srgrimes  /// isTokenSpecial - True if this token requires special consumption methods.
5581558Srgrimes  bool isTokenSpecial() const {
5591558Srgrimes    return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
5601558Srgrimes           isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation();
5611558Srgrimes  }
5621558Srgrimes
5631558Srgrimes  /// Returns true if the current token is '=' or is a type of '='.
5641558Srgrimes  /// For typos, give a fixit to '='
56592541Simp  bool isTokenEqualOrEqualTypo();
5661558Srgrimes
56738483Sbde  /// Return the current token to the token stream and make the given
56892541Simp  /// token the current token.
5691558Srgrimes  void UnconsumeToken(Token &Consumed) {
5701558Srgrimes      Token Next = Tok;
5711558Srgrimes      PP.EnterToken(Consumed, /*IsReinject*/true);
5721558Srgrimes      PP.Lex(Tok);
57338411Sbde      PP.EnterToken(Next, /*IsReinject*/true);
57438411Sbde  }
57538483Sbde
57638411Sbde  SourceLocation ConsumeAnnotationToken() {
57738411Sbde    assert(Tok.isAnnotation() && "wrong consume method");
57813892Sjoerg    SourceLocation Loc = Tok.getLocation();
57913892Sjoerg    PrevTokLocation = Tok.getAnnotationEndLoc();
58013892Sjoerg    PP.Lex(Tok);
58113544Sjoerg    return Loc;
5821558Srgrimes  }
5831558Srgrimes
5841558Srgrimes  /// ConsumeParen - This consume method keeps the paren count up-to-date.
5851558Srgrimes  ///
5861558Srgrimes  SourceLocation ConsumeParen() {
5871558Srgrimes    assert(isTokenParen() && "wrong consume method");
5881558Srgrimes    if (Tok.getKind() == tok::l_paren)
5891558Srgrimes      ++ParenCount;
5901558Srgrimes    else if (ParenCount) {
5911558Srgrimes      AngleBrackets.clear(*this);
5921558Srgrimes      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
5931558Srgrimes    }
5941558Srgrimes    PrevTokLocation = Tok.getLocation();
5951558Srgrimes    PP.Lex(Tok);
5961558Srgrimes    return PrevTokLocation;
5971558Srgrimes  }
5981558Srgrimes
5991558Srgrimes  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
60026542Scharnier  ///
6011558Srgrimes  SourceLocation ConsumeBracket() {
6021558Srgrimes    assert(isTokenBracket() && "wrong consume method");
6031558Srgrimes    if (Tok.getKind() == tok::l_square)
6041558Srgrimes      ++BracketCount;
6051558Srgrimes    else if (BracketCount) {
6061558Srgrimes      AngleBrackets.clear(*this);
6071558Srgrimes      --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
6081558Srgrimes    }
6091558Srgrimes
6101558Srgrimes    PrevTokLocation = Tok.getLocation();
6111558Srgrimes    PP.Lex(Tok);
6121558Srgrimes    return PrevTokLocation;
6131558Srgrimes  }
6141558Srgrimes
6151558Srgrimes  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
6161558Srgrimes  ///
6171558Srgrimes  SourceLocation ConsumeBrace() {
6181558Srgrimes    assert(isTokenBrace() && "wrong consume method");
6191558Srgrimes    if (Tok.getKind() == tok::l_brace)
62041901Sjkh      ++BraceCount;
62141901Sjkh    else if (BraceCount) {
6221558Srgrimes      AngleBrackets.clear(*this);
6231558Srgrimes      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
6241558Srgrimes    }
62541901Sjkh
62641901Sjkh    PrevTokLocation = Tok.getLocation();
6271558Srgrimes    PP.Lex(Tok);
6281558Srgrimes    return PrevTokLocation;
6291558Srgrimes  }
6301558Srgrimes
6311558Srgrimes  /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
6321558Srgrimes  /// and returning the token kind.  This method is specific to strings, as it
63392058Sobrien  /// handles string literal concatenation, as per C99 5.1.1.2, translation
63492057Sobrien  /// phase #6.
6351558Srgrimes  SourceLocation ConsumeStringToken() {
6361558Srgrimes    assert(isTokenStringLiteral() &&
63792058Sobrien           "Should only consume string literals with this method");
6381558Srgrimes    PrevTokLocation = Tok.getLocation();
6391558Srgrimes    PP.Lex(Tok);
6401558Srgrimes    return PrevTokLocation;
6411558Srgrimes  }
6421558Srgrimes
6431558Srgrimes  /// Consume the current code-completion token.
64426542Scharnier  ///
6451558Srgrimes  /// This routine can be called to consume the code-completion token and
64613892Sjoerg  /// continue processing in special cases where \c cutOffParsing() isn't
64713892Sjoerg  /// desired, such as token caching or completion with lookahead.
64813892Sjoerg  SourceLocation ConsumeCodeCompletionToken() {
64913892Sjoerg    assert(Tok.is(tok::code_completion));
65013892Sjoerg    PrevTokLocation = Tok.getLocation();
65113892Sjoerg    PP.Lex(Tok);
65213892Sjoerg    return PrevTokLocation;
65313892Sjoerg  }
65413892Sjoerg
65526542Scharnier  ///\ brief When we are consuming a code-completion token without having
65613892Sjoerg  /// matched specific position in the grammar, provide code-completion results
65797553Salfred  /// based on context.
6581558Srgrimes  ///
65926542Scharnier  /// \returns the source location of the code-completion token.
6601558Srgrimes  SourceLocation handleUnexpectedCodeCompletionToken();
66113892Sjoerg
66213892Sjoerg  /// Abruptly cut off parsing; mainly used when we have reached the
66399365Smarkm  /// code-completion point.
66413892Sjoerg  void cutOffParsing() {
66513892Sjoerg    if (PP.isCodeCompletionEnabled())
66613892Sjoerg      PP.setCodeCompletionReached();
66713892Sjoerg    // Cut off parsing by acting as if we reached the end-of-file.
66813892Sjoerg    Tok.setKind(tok::eof);
66913892Sjoerg  }
67013892Sjoerg
67197553Salfred  /// Determine if we're at the end of the file or at a transition
6721558Srgrimes  /// between modules.
6731558Srgrimes  bool isEofOrEom() {
67426542Scharnier    tok::TokenKind Kind = Tok.getKind();
67537865Sbde    return Kind == tok::eof || Kind == tok::annot_module_begin ||
67637865Sbde           Kind == tok::annot_module_end || Kind == tok::annot_module_include;
67737865Sbde  }
67837865Sbde
67913544Sjoerg  /// Checks if the \p Level is valid for use in a fold expression.
68013544Sjoerg  bool isFoldOperator(prec::Level Level) const;
68126542Scharnier
68238411Sbde  /// Checks if the \p Kind is a valid operator for fold expressions.
68338384Sdfr  bool isFoldOperator(tok::TokenKind Kind) const;
68438411Sbde
68538411Sbde  /// Initialize all pragma handlers.
68638411Sbde  void initializePragmaHandlers();
68738411Sbde
68838411Sbde  /// Destroy and reset all pragma handlers.
68938411Sbde  void resetPragmaHandlers();
69038411Sbde
69138411Sbde  /// Handle the annotation token produced for #pragma unused(...)
69238384Sdfr  void HandlePragmaUnused();
69338483Sbde
69438483Sbde  /// Handle the annotation token produced for
69538483Sbde  /// #pragma GCC visibility...
69638483Sbde  void HandlePragmaVisibility();
69738411Sbde
6981558Srgrimes  /// Handle the annotation token produced for
69926542Scharnier  /// #pragma pack...
70038411Sbde  void HandlePragmaPack();
70137865Sbde
70237865Sbde  /// Handle the annotation token produced for
7031558Srgrimes  /// #pragma ms_struct...
7041558Srgrimes  void HandlePragmaMSStruct();
7051558Srgrimes
7061558Srgrimes  void HandlePragmaMSPointersToMembers();
7071558Srgrimes
7081558Srgrimes  void HandlePragmaMSVtorDisp();
70926542Scharnier
7101558Srgrimes  void HandlePragmaMSPragma();
7111558Srgrimes  bool HandlePragmaMSSection(StringRef PragmaName,
71226542Scharnier                             SourceLocation PragmaLocation);
7131558Srgrimes  bool HandlePragmaMSSegment(StringRef PragmaName,
7141558Srgrimes                             SourceLocation PragmaLocation);
71538411Sbde  bool HandlePragmaMSInitSeg(StringRef PragmaName,
7161558Srgrimes                             SourceLocation PragmaLocation);
71738411Sbde
7181558Srgrimes  /// Handle the annotation token produced for
7191558Srgrimes  /// #pragma align...
7201558Srgrimes  void HandlePragmaAlign();
7211558Srgrimes
7221558Srgrimes  /// Handle the annotation token produced for
72336632Scharnier  /// #pragma clang __debug dump...
72436632Scharnier  void HandlePragmaDump();
7251558Srgrimes
7261558Srgrimes  /// Handle the annotation token produced for
7271558Srgrimes  /// #pragma weak id...
72813544Sjoerg  void HandlePragmaWeak();
72992541Simp
7301558Srgrimes  /// Handle the annotation token produced for
73192541Simp  /// #pragma weak id = id...
73292541Simp  void HandlePragmaWeakAlias();
7331558Srgrimes
7341558Srgrimes  /// Handle the annotation token produced for
735107041Sjulian  /// #pragma redefine_extname...
7361558Srgrimes  void HandlePragmaRedefineExtname();
7371558Srgrimes
73837234Sbde  /// Handle the annotation token produced for
73913544Sjoerg  /// #pragma STDC FP_CONTRACT...
74013544Sjoerg  void HandlePragmaFPContract();
74113544Sjoerg
74213544Sjoerg  /// Handle the annotation token produced for
7431558Srgrimes  /// #pragma STDC FENV_ACCESS...
7441558Srgrimes  void HandlePragmaFEnvAccess();
7451558Srgrimes
7461558Srgrimes  /// Handle the annotation token produced for
7471558Srgrimes  /// #pragma STDC FENV_ROUND...
7481558Srgrimes  void HandlePragmaFEnvRound();
7491558Srgrimes
7501558Srgrimes  /// Handle the annotation token produced for
75137234Sbde  /// #pragma float_control
75237234Sbde  void HandlePragmaFloatControl();
75337234Sbde
75437234Sbde  /// \brief Handle the annotation token produced for
75537234Sbde  /// #pragma clang fp ...
75637234Sbde  void HandlePragmaFP();
75737234Sbde
75837234Sbde  /// Handle the annotation token produced for
75937234Sbde  /// #pragma OPENCL EXTENSION...
76037234Sbde  void HandlePragmaOpenCLExtension();
76137234Sbde
76237234Sbde  /// Handle the annotation token produced for
76313544Sjoerg  /// #pragma clang __debug captured
76437234Sbde  StmtResult HandlePragmaCaptured();
7651558Srgrimes
7661558Srgrimes  /// Handle the annotation token produced for
7671558Srgrimes  /// #pragma clang loop and #pragma unroll.
7681558Srgrimes  bool HandlePragmaLoopHint(LoopHint &Hint);
7691558Srgrimes
7701558Srgrimes  bool ParsePragmaAttributeSubjectMatchRuleSet(
7711558Srgrimes      attr::ParsedSubjectMatchRuleSet &SubjectMatchRules,
77237234Sbde      SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc);
77337234Sbde
7741558Srgrimes  void HandlePragmaAttribute();
7755393Sgibbs
7761558Srgrimes  /// GetLookAheadToken - This peeks ahead N tokens and returns that token
7771558Srgrimes  /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
7781558Srgrimes  /// returns the token after Tok, etc.
77937234Sbde  ///
78037234Sbde  /// Note that this differs from the Preprocessor's LookAhead method, because
781107041Sjulian  /// the Parser always has one token lexed that the preprocessor doesn't.
7821558Srgrimes  ///
7831558Srgrimes  const Token &GetLookAheadToken(unsigned N) {
7841558Srgrimes    if (N == 0 || Tok.is(tok::eof)) return Tok;
7851558Srgrimes    return PP.LookAhead(N-1);
7861558Srgrimes  }
7871558Srgrimes
78837234Sbdepublic:
78937234Sbde  /// NextToken - This peeks ahead one token and returns it without
79037234Sbde  /// consuming it.
7911558Srgrimes  const Token &NextToken() {
7921558Srgrimes    return PP.LookAhead(0);
7931558Srgrimes  }
79437234Sbde
79537234Sbde  /// getTypeAnnotation - Read a parsed type out of an annotation token.
79637234Sbde  static TypeResult getTypeAnnotation(const Token &Tok) {
7971558Srgrimes    if (!Tok.getAnnotationValue())
7981558Srgrimes      return TypeError();
7991558Srgrimes    return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
8005393Sgibbs  }
80137234Sbde
80237234Sbdeprivate:
80337234Sbde  static void setTypeAnnotation(Token &Tok, TypeResult T) {
8045393Sgibbs    assert((T.isInvalid() || T.get()) &&
8055393Sgibbs           "produced a valid-but-null type annotation?");
8065393Sgibbs    Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr());
8071558Srgrimes  }
8081558Srgrimes
8091558Srgrimes  static NamedDecl *getNonTypeAnnotation(const Token &Tok) {
8101558Srgrimes    return static_cast<NamedDecl*>(Tok.getAnnotationValue());
81137234Sbde  }
81237234Sbde
8131558Srgrimes  static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) {
8141558Srgrimes    Tok.setAnnotationValue(ND);
8151558Srgrimes  }
8161558Srgrimes
81737234Sbde  static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) {
81837234Sbde    return static_cast<IdentifierInfo*>(Tok.getAnnotationValue());
81937234Sbde  }
82037234Sbde
8211558Srgrimes  static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) {
8221558Srgrimes    Tok.setAnnotationValue(ND);
8231558Srgrimes  }
8241558Srgrimes
8251558Srgrimes  /// Read an already-translated primary expression out of an annotation
8261558Srgrimes  /// token.
8271558Srgrimes  static ExprResult getExprAnnotation(const Token &Tok) {
8281558Srgrimes    return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
82913544Sjoerg  }
83092541Simp
8311558Srgrimes  /// Set the primary expression corresponding to the given annotation
83292541Simp  /// token.
8331558Srgrimes  static void setExprAnnotation(Token &Tok, ExprResult ER) {
83424180Simp    Tok.setAnnotationValue(ER.getAsOpaquePointer());
8351558Srgrimes  }
83624180Simp
83724180Simppublic:
83836632Scharnier  // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
8391558Srgrimes  // find a type name by attempting typo correction.
8401558Srgrimes  bool TryAnnotateTypeOrScopeToken();
84124180Simp  bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
84224180Simp                                                 bool IsNewScope);
8431558Srgrimes  bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
8441558Srgrimes
8451558Srgrimes  bool MightBeCXXScopeToken() {
84624180Simp    return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
84724180Simp           (Tok.is(tok::annot_template_id) &&
84836632Scharnier            NextToken().is(tok::coloncolon)) ||
8491558Srgrimes           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super);
8501558Srgrimes  }
8511558Srgrimes  bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) {
85224180Simp    return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext);
8531558Srgrimes  }
8541558Srgrimes
85524180Simpprivate:
8561558Srgrimes  enum AnnotatedNameKind {
8571558Srgrimes    /// Annotation has failed and emitted an error.
8581558Srgrimes    ANK_Error,
8591558Srgrimes    /// The identifier is a tentatively-declared name.
86024180Simp    ANK_TentativeDecl,
8611558Srgrimes    /// The identifier is a template name. FIXME: Add an annotation for that.
8621558Srgrimes    ANK_TemplateName,
8631558Srgrimes    /// The identifier can't be resolved.
8641558Srgrimes    ANK_Unresolved,
8651558Srgrimes    /// Annotation was successful.
8661558Srgrimes    ANK_Success
8671558Srgrimes  };
8681558Srgrimes  AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr);
8691558Srgrimes
8701558Srgrimes  /// Push a tok::annot_cxxscope token onto the token stream.
8711558Srgrimes  void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
8721558Srgrimes
87313544Sjoerg  /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
87492541Simp  /// replacing them with the non-context-sensitive keywords.  This returns
8751558Srgrimes  /// true if the token was replaced.
87692541Simp  bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
87799365Smarkm                       const char *&PrevSpec, unsigned &DiagID,
87899365Smarkm                       bool &isInvalid) {
8791558Srgrimes    if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
8801558Srgrimes      return false;
8811558Srgrimes
8821558Srgrimes    if (Tok.getIdentifierInfo() != Ident_vector &&
88336632Scharnier        Tok.getIdentifierInfo() != Ident_bool &&
8841558Srgrimes        Tok.getIdentifierInfo() != Ident_Bool &&
8851558Srgrimes        (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
8861558Srgrimes      return false;
88736632Scharnier
8881558Srgrimes    return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
8891558Srgrimes  }
8901558Srgrimes
8911558Srgrimes  /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
8921558Srgrimes  /// identifier token, replacing it with the non-context-sensitive __vector.
8931558Srgrimes  /// This returns true if the token was replaced.
8941558Srgrimes  bool TryAltiVecVectorToken() {
8951558Srgrimes    if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
8961558Srgrimes        Tok.getIdentifierInfo() != Ident_vector) return false;
8971558Srgrimes    return TryAltiVecVectorTokenOutOfLine();
89879452Sbrian  }
89936632Scharnier
9001558Srgrimes  bool TryAltiVecVectorTokenOutOfLine();
90199365Smarkm  bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
9021558Srgrimes                                const char *&PrevSpec, unsigned &DiagID,
9031558Srgrimes                                bool &isInvalid);
9041558Srgrimes
90599365Smarkm  /// Returns true if the current token is the identifier 'instancetype'.
9061558Srgrimes  ///
9071558Srgrimes  /// Should only be used in Objective-C language modes.
9081558Srgrimes  bool isObjCInstancetype() {
90992541Simp    assert(getLangOpts().ObjC);
9101558Srgrimes    if (Tok.isAnnotation())
9111558Srgrimes      return false;
9121558Srgrimes    if (!Ident_instancetype)
9131558Srgrimes      Ident_instancetype = PP.getIdentifierInfo("instancetype");
9141558Srgrimes    return Tok.getIdentifierInfo() == Ident_instancetype;
91592541Simp  }
9161558Srgrimes
9171558Srgrimes  /// TryKeywordIdentFallback - For compatibility with system headers using
9181558Srgrimes  /// keywords as identifiers, attempt to convert the current token to an
9191558Srgrimes  /// identifier and optionally disable the keyword for the remainder of the
92092541Simp  /// translation unit. This returns false if the token was not replaced,
9211558Srgrimes  /// otherwise emits a diagnostic and returns true.
92292541Simp  bool TryKeywordIdentFallback(bool DisableKeyword);
9231558Srgrimes
9241558Srgrimes  /// Get the TemplateIdAnnotation from the token.
9251558Srgrimes  TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
9261558Srgrimes
9271558Srgrimes  /// TentativeParsingAction - An object that is used as a kind of "tentative
9281558Srgrimes  /// parsing transaction". It gets instantiated to mark the token position and
9291558Srgrimes  /// after the token consumption is done, Commit() or Revert() is called to
9301558Srgrimes  /// either "commit the consumed tokens" or revert to the previously marked
93192541Simp  /// token position. Example:
9321558Srgrimes  ///
9331558Srgrimes  ///   TentativeParsingAction TPA(*this);
9341558Srgrimes  ///   ConsumeToken();
9351558Srgrimes  ///   ....
9361558Srgrimes  ///   TPA.Revert();
9371558Srgrimes  ///
9381558Srgrimes  class TentativeParsingAction {
93913544Sjoerg    Parser &P;
94092541Simp    PreferredTypeBuilder PrevPreferredType;
9411558Srgrimes    Token PrevTok;
94294065Sphk    size_t PrevTentativelyDeclaredIdentifierCount;
94394065Sphk    unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
944107041Sjulian    bool isActive;
94594065Sphk
946107041Sjulian  public:
947107041Sjulian    explicit TentativeParsingAction(Parser &p)
94892541Simp        : P(p), PrevPreferredType(P.PreferredType) {
9491558Srgrimes      PrevTok = P.Tok;
9501558Srgrimes      PrevTentativelyDeclaredIdentifierCount =
95196475Sphk          P.TentativelyDeclaredIdentifiers.size();
9521558Srgrimes      PrevParenCount = P.ParenCount;
9531558Srgrimes      PrevBracketCount = P.BracketCount;
95413544Sjoerg      PrevBraceCount = P.BraceCount;
9551558Srgrimes      P.PP.EnableBacktrackAtThisPos();
9561558Srgrimes      isActive = true;
9571558Srgrimes    }
9581558Srgrimes    void Commit() {
9591558Srgrimes      assert(isActive && "Parsing action was finished!");
9601558Srgrimes      P.TentativelyDeclaredIdentifiers.resize(
9611558Srgrimes          PrevTentativelyDeclaredIdentifierCount);
9621558Srgrimes      P.PP.CommitBacktrackedTokens();
9631558Srgrimes      isActive = false;
9641558Srgrimes    }
9651558Srgrimes    void Revert() {
9661558Srgrimes      assert(isActive && "Parsing action was finished!");
9671558Srgrimes      P.PP.Backtrack();
96899365Smarkm      P.PreferredType = PrevPreferredType;
9691558Srgrimes      P.Tok = PrevTok;
9701558Srgrimes      P.TentativelyDeclaredIdentifiers.resize(
97194065Sphk          PrevTentativelyDeclaredIdentifierCount);
9721558Srgrimes      P.ParenCount = PrevParenCount;
97397855Siedowse      P.BracketCount = PrevBracketCount;
9741558Srgrimes      P.BraceCount = PrevBraceCount;
97597855Siedowse      isActive = false;
97697855Siedowse    }
977107041Sjulian    ~TentativeParsingAction() {
978107041Sjulian      assert(!isActive && "Forgot to call Commit or Revert!");
979107041Sjulian    }
9801558Srgrimes  };
9811558Srgrimes  /// A TentativeParsingAction that automatically reverts in its destructor.
9821558Srgrimes  /// Useful for disambiguation parses that will always be reverted.
9831558Srgrimes  class RevertingTentativeParsingAction
9841558Srgrimes      : private Parser::TentativeParsingAction {
9851558Srgrimes  public:
9861558Srgrimes    RevertingTentativeParsingAction(Parser &P)
9871558Srgrimes        : Parser::TentativeParsingAction(P) {}
9881558Srgrimes    ~RevertingTentativeParsingAction() { Revert(); }
9891558Srgrimes  };
9901558Srgrimes
9911558Srgrimes  class UnannotatedTentativeParsingAction;
9921558Srgrimes
9931558Srgrimes  /// ObjCDeclContextSwitch - An object used to switch context from
9941558Srgrimes  /// an objective-c decl context to its enclosing decl context and
9951558Srgrimes  /// back.
9961558Srgrimes  class ObjCDeclContextSwitch {
9971558Srgrimes    Parser &P;
9981558Srgrimes    Decl *DC;
9991558Srgrimes    SaveAndRestore<bool> WithinObjCContainer;
10001558Srgrimes  public:
10011558Srgrimes    explicit ObjCDeclContextSwitch(Parser &p)
10021558Srgrimes      : P(p), DC(p.getObjCDeclContext()),
10031558Srgrimes        WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
10041558Srgrimes      if (DC)
1005107041Sjulian        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
10061558Srgrimes    }
10071558Srgrimes    ~ObjCDeclContextSwitch() {
10081558Srgrimes      if (DC)
10091558Srgrimes        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
1010107041Sjulian    }
1011107041Sjulian  };
10121558Srgrimes
10131558Srgrimes  /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
10141558Srgrimes  /// input.  If so, it is consumed and false is returned.
10151558Srgrimes  ///
10161558Srgrimes  /// If a trivial punctuator misspelling is encountered, a FixIt error
10171558Srgrimes  /// diagnostic is issued and false is returned after recovery.
10181558Srgrimes  ///
10191558Srgrimes  /// If the input is malformed, this emits the specified diagnostic and true is
10201558Srgrimes  /// returned.
102199365Smarkm  bool ExpectAndConsume(tok::TokenKind ExpectedTok,
10221558Srgrimes                        unsigned Diag = diag::err_expected,
10231558Srgrimes                        StringRef DiagMsg = "");
10241558Srgrimes
10251558Srgrimes  /// The parser expects a semicolon and, if present, will consume it.
10261558Srgrimes  ///
10271558Srgrimes  /// If the next token is not a semicolon, this emits the specified diagnostic,
10281558Srgrimes  /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
10291558Srgrimes  /// to the semicolon, consumes that extra token.
10301558Srgrimes  bool ExpectAndConsumeSemi(unsigned DiagID);
1031107041Sjulian
1032107041Sjulian  /// The kind of extra semi diagnostic to emit.
10331558Srgrimes  enum ExtraSemiKind {
10341558Srgrimes    OutsideFunction = 0,
10351558Srgrimes    InsideStruct = 1,
10361558Srgrimes    InstanceVariableList = 2,
10371558Srgrimes    AfterMemberFunctionDefinition = 3
10381558Srgrimes  };
10391558Srgrimes
10401558Srgrimes  /// Consume any extra semi-colons until the end of the line.
10411558Srgrimes  void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified);
1042107041Sjulian
1043107041Sjulian  /// Return false if the next token is an identifier. An 'expected identifier'
1044107041Sjulian  /// error is emitted otherwise.
1045107041Sjulian  ///
1046107041Sjulian  /// The parser tries to recover from the error by checking if the next token
1047107041Sjulian  /// is a C++ keyword when parsing Objective-C++. Return false if the recovery
10481558Srgrimes  /// was successful.
10491558Srgrimes  bool expectIdentifier();
10501558Srgrimes
10511558Srgrimes  /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
10521558Srgrimes  enum class CompoundToken {
10531558Srgrimes    /// A '(' '{' beginning a statement-expression.
10541558Srgrimes    StmtExprBegin,
10551558Srgrimes    /// A '}' ')' ending a statement-expression.
1056107041Sjulian    StmtExprEnd,
1057107041Sjulian    /// A '[' '[' beginning a C++11 or C2x attribute.
10581558Srgrimes    AttrBegin,
10591558Srgrimes    /// A ']' ']' ending a C++11 or C2x attribute.
10601558Srgrimes    AttrEnd,
10611558Srgrimes    /// A '::' '*' forming a C++ pointer-to-member declaration.
10621558Srgrimes    MemberPtr,
10631558Srgrimes  };
10641558Srgrimes
10651558Srgrimes  /// Check that a compound operator was written in a "sensible" way, and warn
1066107041Sjulian  /// if not.
1067107041Sjulian  void checkCompoundToken(SourceLocation FirstTokLoc,
10681558Srgrimes                          tok::TokenKind FirstTokKind, CompoundToken Op);
10691558Srgrimes
10701558Srgrimespublic:
10711558Srgrimes  //===--------------------------------------------------------------------===//
10721558Srgrimes  // Scope manipulation
10731558Srgrimes
10741558Srgrimes  /// ParseScope - Introduces a new scope for parsing. The kind of
10751558Srgrimes  /// scope is determined by ScopeFlags. Objects of this type should
1076107041Sjulian  /// be created on the stack to coincide with the position where the
1077107041Sjulian  /// parser enters the new scope, and this object's constructor will
10781558Srgrimes  /// create that new scope. Similarly, once the object is destroyed
10791558Srgrimes  /// the parser will exit the scope.
10801558Srgrimes  class ParseScope {
10811558Srgrimes    Parser *Self;
10821558Srgrimes    ParseScope(const ParseScope &) = delete;
10831558Srgrimes    void operator=(const ParseScope &) = delete;
10841558Srgrimes
10856643Sbde  public:
1086107041Sjulian    // ParseScope - Construct a new object to manage a scope in the
1087107041Sjulian    // parser Self where the new Scope is created with the flags
10886643Sbde    // ScopeFlags, but only when we aren't about to enter a compound statement.
10896643Sbde    ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
10906643Sbde               bool BeforeCompoundStmt = false)
10916643Sbde      : Self(Self) {
10926643Sbde      if (EnteredScope && !BeforeCompoundStmt)
10936643Sbde        Self->EnterScope(ScopeFlags);
10946643Sbde      else {
10951558Srgrimes        if (BeforeCompoundStmt)
1096107041Sjulian          Self->incrementMSManglingNumber();
1097107041Sjulian
10981558Srgrimes        this->Self = nullptr;
10991558Srgrimes      }
11001558Srgrimes    }
11011558Srgrimes
11021558Srgrimes    // Exit - Exit the scope associated with this object now, rather
11031558Srgrimes    // than waiting until the object is destroyed.
11041558Srgrimes    void Exit() {
11051558Srgrimes      if (Self) {
1106107041Sjulian        Self->ExitScope();
1107107041Sjulian        Self = nullptr;
11081558Srgrimes      }
11091558Srgrimes    }
11101558Srgrimes
11111558Srgrimes    ~ParseScope() {
11121558Srgrimes      Exit();
11131558Srgrimes    }
11141558Srgrimes  };
11151558Srgrimes
1116107041Sjulian  /// Introduces zero or more scopes for parsing. The scopes will all be exited
1117107041Sjulian  /// when the object is destroyed.
11181558Srgrimes  class MultiParseScope {
11191558Srgrimes    Parser &Self;
11201558Srgrimes    unsigned NumScopes = 0;
11211558Srgrimes
11221558Srgrimes    MultiParseScope(const MultiParseScope&) = delete;
11231558Srgrimes
11241558Srgrimes  public:
11251558Srgrimes    MultiParseScope(Parser &Self) : Self(Self) {}
1126107041Sjulian    void Enter(unsigned ScopeFlags) {
1127107041Sjulian      Self.EnterScope(ScopeFlags);
11281558Srgrimes      ++NumScopes;
11291558Srgrimes    }
11301558Srgrimes    void Exit() {
11311558Srgrimes      while (NumScopes) {
11321558Srgrimes        Self.ExitScope();
11331558Srgrimes        --NumScopes;
11341558Srgrimes      }
11351558Srgrimes    }
1136107041Sjulian    ~MultiParseScope() {
1137107041Sjulian      Exit();
11381558Srgrimes    }
11391558Srgrimes  };
11401558Srgrimes
1141107041Sjulian  /// EnterScope - Start a new scope.
1142107041Sjulian  void EnterScope(unsigned ScopeFlags);
11431558Srgrimes
11441558Srgrimes  /// ExitScope - Pop a scope off the scope stack.
114573034Sjwd  void ExitScope();
114697534Siedowse
114797534Siedowse  /// Re-enter the template scopes for a declaration that might be a template.
114897534Siedowse  unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
114997534Siedowse
115097534Siedowseprivate:
115197534Siedowse  /// RAII object used to modify the scope flags for the current scope.
115297534Siedowse  class ParseScopeFlags {
115397534Siedowse    Scope *CurScope;
115497534Siedowse    unsigned OldFlags;
115597534Siedowse    ParseScopeFlags(const ParseScopeFlags &) = delete;
115697534Siedowse    void operator=(const ParseScopeFlags &) = delete;
115797534Siedowse
115897534Siedowse  public:
115997534Siedowse    ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
116097534Siedowse    ~ParseScopeFlags();
116197534Siedowse  };
116297534Siedowse
116397534Siedowse  //===--------------------------------------------------------------------===//
116497534Siedowse  // Diagnostic Emission and Error recovery.
116597534Siedowse
116697534Siedowsepublic:
116797534Siedowse  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
116897534Siedowse  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
116997534Siedowse  DiagnosticBuilder Diag(unsigned DiagID) {
117097534Siedowse    return Diag(Tok, DiagID);
117197534Siedowse  }
117297534Siedowse
117397534Siedowseprivate:
117497534Siedowse  void SuggestParentheses(SourceLocation Loc, unsigned DK,
11753111Spst                          SourceRange ParenRange);
11763111Spst  void CheckNestedObjCContexts(SourceLocation AtLoc);
117797534Siedowse
11783111Spstpublic:
11793111Spst
1180107041Sjulian  /// Control flags for SkipUntil functions.
11813111Spst  enum SkipUntilFlags {
118297534Siedowse    StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
118397534Siedowse    /// Stop skipping at specified token, but don't skip the token itself
118473034Sjwd    StopBeforeMatch = 1 << 1,
118597534Siedowse    StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
118673034Sjwd  };
118773034Sjwd
118897534Siedowse  friend constexpr SkipUntilFlags operator|(SkipUntilFlags L,
118973034Sjwd                                            SkipUntilFlags R) {
119073034Sjwd    return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
119173034Sjwd                                       static_cast<unsigned>(R));
1192107041Sjulian  }
119373034Sjwd
119473034Sjwd  /// SkipUntil - Read tokens until we get to the specified token, then consume
119597534Siedowse  /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
11961558Srgrimes  /// that the token will ever occur, this skips to the next token, or to some
119797534Siedowse  /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
119897534Siedowse  /// stop at a ';' character. Balances (), [], and {} delimiter tokens while
119997534Siedowse  /// skipping.
120097534Siedowse  ///
120197534Siedowse  /// If SkipUntil finds the specified token, it returns true, otherwise it
120297534Siedowse  /// returns false.
120397534Siedowse  bool SkipUntil(tok::TokenKind T,
120497534Siedowse                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
120597534Siedowse    return SkipUntil(llvm::makeArrayRef(T), Flags);
120697534Siedowse  }
1207107041Sjulian  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
12081558Srgrimes                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
120997534Siedowse    tok::TokenKind TokArray[] = {T1, T2};
121097534Siedowse    return SkipUntil(TokArray, Flags);
12111558Srgrimes  }
121297534Siedowse  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
121397534Siedowse                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
1214107041Sjulian    tok::TokenKind TokArray[] = {T1, T2, T3};
1215107041Sjulian    return SkipUntil(TokArray, Flags);
1216107041Sjulian  }
121797534Siedowse  bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
121897534Siedowse                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
121997534Siedowse
122097534Siedowse  /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
122197534Siedowse  /// point for skipping past a simple-declaration.
122297534Siedowse  void SkipMalformedDecl();
1223107041Sjulian
1224107041Sjulian  /// The location of the first statement inside an else that might
1225107041Sjulian  /// have a missleading indentation. If there is no
1226107041Sjulian  /// MisleadingIndentationChecker on an else active, this location is invalid.
122797534Siedowse  SourceLocation MisleadingIndentationElseLoc;
122897534Siedowse
122997534Siedowseprivate:
123097534Siedowse  //===--------------------------------------------------------------------===//
123197534Siedowse  // Lexing and parsing of C++ inline methods.
123297534Siedowse
123397534Siedowse  struct ParsingClass;
123497534Siedowse
123597534Siedowse  /// [class.mem]p1: "... the class is regarded as complete within
123697534Siedowse  /// - function bodies
123797534Siedowse  /// - default arguments
1238107041Sjulian  /// - exception-specifications (TODO: C++0x)
123997534Siedowse  /// - and brace-or-equal-initializers for non-static data members
124097534Siedowse  /// (including such things in nested classes)."
1241107041Sjulian  /// LateParsedDeclarations build the tree of those elements so they can
124297534Siedowse  /// be parsed after parsing the top-level class.
1243102231Strhodes  class LateParsedDeclaration {
124497534Siedowse  public:
124597534Siedowse    virtual ~LateParsedDeclaration();
124697534Siedowse
124797534Siedowse    virtual void ParseLexedMethodDeclarations();
124897534Siedowse    virtual void ParseLexedMemberInitializers();
124997534Siedowse    virtual void ParseLexedMethodDefs();
125097534Siedowse    virtual void ParseLexedAttributes();
125197534Siedowse    virtual void ParseLexedPragmas();
125297534Siedowse  };
125397534Siedowse
125497534Siedowse  /// Inner node of the LateParsedDeclaration tree that parses
125597534Siedowse  /// all its members recursively.
125697534Siedowse  class LateParsedClass : public LateParsedDeclaration {
125797534Siedowse  public:
125897534Siedowse    LateParsedClass(Parser *P, ParsingClass *C);
125997534Siedowse    ~LateParsedClass() override;
126097534Siedowse
126197534Siedowse    void ParseLexedMethodDeclarations() override;
126297534Siedowse    void ParseLexedMemberInitializers() override;
126397534Siedowse    void ParseLexedMethodDefs() override;
126497534Siedowse    void ParseLexedAttributes() override;
126597534Siedowse    void ParseLexedPragmas() override;
126697534Siedowse
126797534Siedowse  private:
126897534Siedowse    Parser *Self;
126997534Siedowse    ParsingClass *Class;
127097534Siedowse  };
127197534Siedowse
127297534Siedowse  /// Contains the lexed tokens of an attribute with arguments that
127397534Siedowse  /// may reference member variables and so need to be parsed at the
127497534Siedowse  /// end of the class declaration after parsing all other member
127597534Siedowse  /// member declarations.
127697534Siedowse  /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
127797534Siedowse  /// LateParsedTokens.
127897534Siedowse  struct LateParsedAttribute : public LateParsedDeclaration {
127997534Siedowse    Parser *Self;
128097534Siedowse    CachedTokens Toks;
128197534Siedowse    IdentifierInfo &AttrName;
128297534Siedowse    IdentifierInfo *MacroII = nullptr;
128397534Siedowse    SourceLocation AttrNameLoc;
128497534Siedowse    SmallVector<Decl*, 2> Decls;
128597535Siedowse
128697535Siedowse    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
128797535Siedowse                                 SourceLocation Loc)
128897534Siedowse      : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
128997534Siedowse
129097535Siedowse    void ParseLexedAttributes() override;
129197535Siedowse
129297535Siedowse    void addDecl(Decl *D) { Decls.push_back(D); }
129397534Siedowse  };
12941558Srgrimes
12951558Srgrimes  /// Contains the lexed tokens of a pragma with arguments that
129697534Siedowse  /// may reference member variables and so need to be parsed at the
129797534Siedowse  /// end of the class declaration after parsing all other member
12981558Srgrimes  /// member declarations.
129997534Siedowse  class LateParsedPragma : public LateParsedDeclaration {
13001558Srgrimes    Parser *Self = nullptr;
13011558Srgrimes    AccessSpecifier AS = AS_none;
13021558Srgrimes    CachedTokens Toks;
13031558Srgrimes
13041558Srgrimes  public:
13051558Srgrimes    explicit LateParsedPragma(Parser *P, AccessSpecifier AS)
130613544Sjoerg        : Self(P), AS(AS) {}
130792541Simp
13081558Srgrimes    void takeToks(CachedTokens &Cached) { Toks.swap(Cached); }
130992541Simp    const CachedTokens &toks() const { return Toks; }
13101558Srgrimes    AccessSpecifier getAccessSpecifier() const { return AS; }
13111558Srgrimes
1312107041Sjulian    void ParseLexedPragmas() override;
131373034Sjwd  };
131473034Sjwd
131573034Sjwd  // A list of late-parsed attributes.  Used by ParseGNUAttributes.
131673034Sjwd  class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
13171558Srgrimes  public:
13181558Srgrimes    LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
131937234Sbde
13201558Srgrimes    bool parseSoon() { return ParseSoon; }
13211558Srgrimes
13221558Srgrimes  private:
132337234Sbde    bool ParseSoon;  // Are we planning to parse these shortly after creation?
13241558Srgrimes  };
13251558Srgrimes
13261558Srgrimes  /// Contains the lexed tokens of a member function definition
132737234Sbde  /// which needs to be parsed at the end of the class declaration
13281558Srgrimes  /// after parsing all other member declarations.
13291558Srgrimes  struct LexedMethod : public LateParsedDeclaration {
13301558Srgrimes    Parser *Self;
133137234Sbde    Decl *D;
13321558Srgrimes    CachedTokens Toks;
13331558Srgrimes
13341558Srgrimes    explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
133537234Sbde
13361558Srgrimes    void ParseLexedMethodDefs() override;
13371558Srgrimes  };
13381558Srgrimes
13391558Srgrimes  /// LateParsedDefaultArgument - Keeps track of a parameter that may
13401558Srgrimes  /// have a default argument that cannot be parsed yet because it
134137234Sbde  /// occurs within a member function declaration inside the class
13421558Srgrimes  /// (C++ [class.mem]p2).
13431558Srgrimes  struct LateParsedDefaultArgument {
13441558Srgrimes    explicit LateParsedDefaultArgument(Decl *P,
13451558Srgrimes                                       std::unique_ptr<CachedTokens> Toks = nullptr)
134637234Sbde      : Param(P), Toks(std::move(Toks)) { }
134737234Sbde
134873034Sjwd    /// Param - The parameter declaration for this parameter.
134973034Sjwd    Decl *Param;
135073034Sjwd
135173034Sjwd    /// Toks - The sequence of tokens that comprises the default
135273034Sjwd    /// argument expression, not including the '=' or the terminating
135373034Sjwd    /// ')' or ','. This will be NULL for parameters that have no
13541558Srgrimes    /// default argument.
135573034Sjwd    std::unique_ptr<CachedTokens> Toks;
135673034Sjwd  };
135773034Sjwd
135894065Sphk  /// LateParsedMethodDeclaration - A method declaration inside a class that
135973034Sjwd  /// contains at least one entity whose parsing needs to be delayed
136073034Sjwd  /// until the class itself is completely-defined, such as a default
136173034Sjwd  /// argument (C++ [class.mem]p2).
136273034Sjwd  struct LateParsedMethodDeclaration : public LateParsedDeclaration {
136373034Sjwd    explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
136473034Sjwd        : Self(P), Method(M), ExceptionSpecTokens(nullptr) {}
136573034Sjwd
136673034Sjwd    void ParseLexedMethodDeclarations() override;
136773034Sjwd
136873573Simp    Parser *Self;
136973034Sjwd
137073034Sjwd    /// Method - The method declaration.
137173034Sjwd    Decl *Method;
137273034Sjwd
137373034Sjwd    /// DefaultArgs - Contains the parameters of the function and
137473034Sjwd    /// their default arguments. At least one of the parameters will
137573034Sjwd    /// have a default argument, but all of the parameters of the
137673034Sjwd    /// method will be stored so that they can be reintroduced into
137773573Simp    /// scope at the appropriate times.
137873034Sjwd    SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
137973034Sjwd
138073034Sjwd    /// The set of tokens that make up an exception-specification that
138173573Simp    /// has not yet been parsed.
138273034Sjwd    CachedTokens *ExceptionSpecTokens;
138373034Sjwd  };
138473034Sjwd
138573573Simp  /// LateParsedMemberInitializer - An initializer for a non-static class data
138673034Sjwd  /// member whose parsing must to be delayed until the class is completely
138773034Sjwd  /// defined (C++11 [class.mem]p2).
138873034Sjwd  struct LateParsedMemberInitializer : public LateParsedDeclaration {
138973034Sjwd    LateParsedMemberInitializer(Parser *P, Decl *FD)
139073034Sjwd      : Self(P), Field(FD) { }
139173034Sjwd
139273034Sjwd    void ParseLexedMemberInitializers() override;
139373034Sjwd
139473034Sjwd    Parser *Self;
139573034Sjwd
139673034Sjwd    /// Field - The field declaration.
139773034Sjwd    Decl *Field;
139873034Sjwd
139973034Sjwd    /// CachedTokens - The sequence of tokens that comprises the initializer,
140073034Sjwd    /// including any leading '='.
140173034Sjwd    CachedTokens Toks;
140273034Sjwd  };
140373034Sjwd
140473034Sjwd  /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
140573034Sjwd  /// C++ class, its method declarations that contain parts that won't be
140673034Sjwd  /// parsed until after the definition is completed (C++ [class.mem]p2),
140794065Sphk  /// the method declarations and possibly attached inline definitions
140873034Sjwd  /// will be stored here with the tokens that will be parsed to create those
140973034Sjwd  /// entities.
141073034Sjwd  typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
141173034Sjwd
141273034Sjwd  /// Representation of a class that has been parsed, including
141373034Sjwd  /// any member function declarations or definitions that need to be
141473034Sjwd  /// parsed after the corresponding top-level class is complete.
141573034Sjwd  struct ParsingClass {
141673034Sjwd    ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
141794065Sphk        : TopLevelClass(TopLevelClass), IsInterface(IsInterface),
141873034Sjwd          TagOrTemplate(TagOrTemplate) {}
141973034Sjwd
142073034Sjwd    /// Whether this is a "top-level" class, meaning that it is
142173034Sjwd    /// not nested within another class.
142273034Sjwd    bool TopLevelClass : 1;
142373034Sjwd
142473034Sjwd    /// Whether this class is an __interface.
142573034Sjwd    bool IsInterface : 1;
142673034Sjwd
142773034Sjwd    /// The class or class template whose definition we are parsing.
142873034Sjwd    Decl *TagOrTemplate;
142973034Sjwd
143073034Sjwd    /// LateParsedDeclarations - Method declarations, inline definitions and
143173034Sjwd    /// nested classes that contain pieces whose parsing will be delayed until
143273034Sjwd    /// the top-level class is fully defined.
143373034Sjwd    LateParsedDeclarationsContainer LateParsedDeclarations;
143473034Sjwd  };
143573034Sjwd
143694065Sphk  /// The stack of classes that is currently being
143773034Sjwd  /// parsed. Nested and local classes will be pushed onto this stack
143873034Sjwd  /// when they are parsed, and removed afterward.
143973034Sjwd  std::stack<ParsingClass *> ClassStack;
144073034Sjwd
144173034Sjwd  ParsingClass &getCurrentClass() {
144273034Sjwd    assert(!ClassStack.empty() && "No lexed method stacks!");
144373034Sjwd    return *ClassStack.top();
144473034Sjwd  }
144573034Sjwd
144673034Sjwd  /// RAII object used to manage the parsing of a class definition.
144773034Sjwd  class ParsingClassDefinition {
144873034Sjwd    Parser &P;
144973034Sjwd    bool Popped;
145073034Sjwd    Sema::ParsingClassState State;
145173034Sjwd
14521558Srgrimes  public:
14531558Srgrimes    ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
145473034Sjwd                           bool IsInterface)
145573034Sjwd      : P(P), Popped(false),
145694065Sphk        State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
145773034Sjwd    }
145873034Sjwd
145973034Sjwd    /// Pop this class of the stack.
146073034Sjwd    void Pop() {
146173034Sjwd      assert(!Popped && "Nested class has already been popped");
146273034Sjwd      Popped = true;
146373034Sjwd      P.PopParsingClass(State);
146473034Sjwd    }
1465107534Sgrog
1466107534Sgrog    ~ParsingClassDefinition() {
146773034Sjwd      if (!Popped)
146894065Sphk        P.PopParsingClass(State);
146994065Sphk    }
147073034Sjwd  };
147173034Sjwd
147273034Sjwd  /// Contains information about any template-specific
147373034Sjwd  /// information that has been parsed prior to parsing declaration
147494065Sphk  /// specifiers.
147573034Sjwd  struct ParsedTemplateInfo {
147673034Sjwd    ParsedTemplateInfo()
147773034Sjwd      : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
147873034Sjwd
147973034Sjwd    ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
148073034Sjwd                       bool isSpecialization,
148194065Sphk                       bool lastParameterListWasEmpty = false)
148273034Sjwd      : Kind(isSpecialization? ExplicitSpecialization : Template),
148373034Sjwd        TemplateParams(TemplateParams),
148494065Sphk        LastParameterListWasEmpty(lastParameterListWasEmpty) { }
148573034Sjwd
148673034Sjwd    explicit ParsedTemplateInfo(SourceLocation ExternLoc,
148773034Sjwd                                SourceLocation TemplateLoc)
148873034Sjwd      : Kind(ExplicitInstantiation), TemplateParams(nullptr),
148973034Sjwd        ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
149073034Sjwd        LastParameterListWasEmpty(false){ }
149173034Sjwd
14921558Srgrimes    /// The kind of template we are parsing.
149337234Sbde    enum {
149437234Sbde      /// We are not parsing a template at all.
149592058Sobrien      NonTemplate = 0,
149692058Sobrien      /// We are parsing a template declaration.
149792058Sobrien      Template,
149892058Sobrien      /// We are parsing an explicit specialization.
149992058Sobrien      ExplicitSpecialization,
150092058Sobrien      /// We are parsing an explicit instantiation.
150192058Sobrien      ExplicitInstantiation
150292058Sobrien    } Kind;
15031558Srgrimes
15041558Srgrimes    /// The template parameter lists, for template declarations
15051558Srgrimes    /// and explicit specializations.
15061558Srgrimes    TemplateParameterLists *TemplateParams;
15071558Srgrimes
15081558Srgrimes    /// The location of the 'extern' keyword, if any, for an explicit
15091558Srgrimes    /// instantiation
15101558Srgrimes    SourceLocation ExternLoc;
15111558Srgrimes
15121558Srgrimes    /// The location of the 'template' keyword, for an explicit
15131558Srgrimes    /// instantiation.
15141558Srgrimes    SourceLocation TemplateLoc;
15151558Srgrimes
15161558Srgrimes    /// Whether the last template parameter list was empty.
15171558Srgrimes    bool LastParameterListWasEmpty;
151813544Sjoerg
15191558Srgrimes    SourceRange getSourceRange() const LLVM_READONLY;
15201558Srgrimes  };
15211558Srgrimes
152294065Sphk  // In ParseCXXInlineMethods.cpp.
152373034Sjwd  struct ReenterTemplateScopeRAII;
152473034Sjwd  struct ReenterClassScopeRAII;
152573034Sjwd
152673034Sjwd  void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
152773034Sjwd  void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
152873034Sjwd
152973034Sjwd  static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
153073034Sjwd
153173034Sjwd  Sema::ParsingClassState
153273034Sjwd  PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
153373034Sjwd  void DeallocateParsedClasses(ParsingClass *Class);
153473034Sjwd  void PopParsingClass(Sema::ParsingClassState);
153573034Sjwd
153673034Sjwd  enum CachedInitKind {
153773034Sjwd    CIK_DefaultArgument,
153873034Sjwd    CIK_DefaultInitializer
153973034Sjwd  };
154073034Sjwd
1541107534Sgrog  NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1542107534Sgrog                                     ParsedAttributes &AccessAttrs,
1543107534Sgrog                                     ParsingDeclarator &D,
1544107534Sgrog                                     const ParsedTemplateInfo &TemplateInfo,
154573034Sjwd                                     const VirtSpecifiers &VS,
154673034Sjwd                                     SourceLocation PureSpecLoc);
154773034Sjwd  void ParseCXXNonStaticMemberInitializer(Decl *VarD);
154873034Sjwd  void ParseLexedAttributes(ParsingClass &Class);
154973034Sjwd  void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
155073034Sjwd                               bool EnterScope, bool OnDefinition);
155173034Sjwd  void ParseLexedAttribute(LateParsedAttribute &LA,
155273034Sjwd                           bool EnterScope, bool OnDefinition);
155373034Sjwd  void ParseLexedMethodDeclarations(ParsingClass &Class);
155473034Sjwd  void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
15551558Srgrimes  void ParseLexedMethodDefs(ParsingClass &Class);
15561558Srgrimes  void ParseLexedMethodDef(LexedMethod &LM);
15571558Srgrimes  void ParseLexedMemberInitializers(ParsingClass &Class);
15581558Srgrimes  void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
15591558Srgrimes  void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
156037234Sbde  void ParseLexedPragmas(ParsingClass &Class);
156137234Sbde  void ParseLexedPragma(LateParsedPragma &LP);
15621558Srgrimes  bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
15631558Srgrimes  bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
15641558Srgrimes  bool ConsumeAndStoreConditional(CachedTokens &Toks);
15651558Srgrimes  bool ConsumeAndStoreUntil(tok::TokenKind T1,
15661558Srgrimes                            CachedTokens &Toks,
156713550Sjoerg                            bool StopAtSemi = true,
156813550Sjoerg                            bool ConsumeFinalToken = true) {
156913550Sjoerg    return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
157013550Sjoerg  }
157113550Sjoerg  bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
157213550Sjoerg                            CachedTokens &Toks,
157313550Sjoerg                            bool StopAtSemi = true,
157413550Sjoerg                            bool ConsumeFinalToken = true);
157513550Sjoerg
157613550Sjoerg  //===--------------------------------------------------------------------===//
157713550Sjoerg  // C99 6.9: External Definitions.
157899365Smarkm  DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1579103669Sphk                                          ParsingDeclSpec *DS = nullptr);
158099365Smarkm  bool isDeclarationAfterDeclarator();
158113550Sjoerg  bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1582103669Sphk  DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1583103669Sphk                                                  ParsedAttributesWithRange &attrs,
158413550Sjoerg                                                  ParsingDeclSpec *DS = nullptr,
158513550Sjoerg                                                  AccessSpecifier AS = AS_none);
158637773Sbde  DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
158716431Sbde                                                ParsingDeclSpec &DS,
158813550Sjoerg                                                AccessSpecifier AS);
158999365Smarkm
159099365Smarkm  void SkipFunctionBody();
159199365Smarkm  Decl *ParseFunctionDefinition(ParsingDeclarator &D,
159216431Sbde                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
159313550Sjoerg                 LateParsedAttrList *LateParsedAttrs = nullptr);
159468044Sjkh  void ParseKNRParamDeclarations(Declarator &D);
1595103669Sphk  // EndLoc is filled with the location of the last token of the simple-asm.
1596103669Sphk  ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc);
1597103669Sphk  ExprResult ParseAsmStringLiteral(bool ForAsmLabel);
1598103669Sphk
1599103669Sphk  // Objective-C External Declarations
1600103669Sphk  void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1601103669Sphk  DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs);
1602103669Sphk  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1603103669Sphk  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1604103669Sphk                                        ParsedAttributes &prefixAttrs);
1605103669Sphk  class ObjCTypeParamListScope;
1606103669Sphk  ObjCTypeParamList *parseObjCTypeParamList();
160768044Sjkh  ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1608103669Sphk      ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1609103669Sphk      SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1610103669Sphk      SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1611103669Sphk
161268044Sjkh  void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1613103669Sphk                                        BalancedDelimiterTracker &T,
1614103669Sphk                                        SmallVectorImpl<Decl *> &AllIvarDecls,
1615103669Sphk                                        bool RBraceMissing);
1616103669Sphk  void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1617103669Sphk                                       tok::ObjCKeywordKind visibility,
1618103669Sphk                                       SourceLocation atLoc);
1619103669Sphk  bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1620103669Sphk                                   SmallVectorImpl<SourceLocation> &PLocs,
1621103669Sphk                                   bool WarnOnDeclarations,
1622103669Sphk                                   bool ForObjCContainer,
1623103669Sphk                                   SourceLocation &LAngleLoc,
1624103669Sphk                                   SourceLocation &EndProtoLoc,
1625103669Sphk                                   bool consumeLastToken);
1626103669Sphk
1627103669Sphk  /// Parse the first angle-bracket-delimited clause for an
1628103669Sphk  /// Objective-C object or object pointer type, which may be either
1629103669Sphk  /// type arguments or protocol qualifiers.
1630103669Sphk  void parseObjCTypeArgsOrProtocolQualifiers(
1631103669Sphk         ParsedType baseType,
1632103669Sphk         SourceLocation &typeArgsLAngleLoc,
1633103669Sphk         SmallVectorImpl<ParsedType> &typeArgs,
1634103669Sphk         SourceLocation &typeArgsRAngleLoc,
1635103669Sphk         SourceLocation &protocolLAngleLoc,
1636103669Sphk         SmallVectorImpl<Decl *> &protocols,
1637103669Sphk         SmallVectorImpl<SourceLocation> &protocolLocs,
1638103669Sphk         SourceLocation &protocolRAngleLoc,
1639103669Sphk         bool consumeLastToken,
164099365Smarkm         bool warnOnIncompleteProtocols);
164113550Sjoerg
164213550Sjoerg  /// Parse either Objective-C type arguments or protocol qualifiers; if the
164313550Sjoerg  /// former, also parse protocol qualifiers afterward.
16441558Srgrimes  void parseObjCTypeArgsAndProtocolQualifiers(
16451558Srgrimes         ParsedType baseType,
1646102231Strhodes         SourceLocation &typeArgsLAngleLoc,
16471558Srgrimes         SmallVectorImpl<ParsedType> &typeArgs,
16481558Srgrimes         SourceLocation &typeArgsRAngleLoc,
164913544Sjoerg         SourceLocation &protocolLAngleLoc,
165092541Simp         SmallVectorImpl<Decl *> &protocols,
16511558Srgrimes         SmallVectorImpl<SourceLocation> &protocolLocs,
165292541Simp         SourceLocation &protocolRAngleLoc,
16531558Srgrimes         bool consumeLastToken);
16541558Srgrimes
16551558Srgrimes  /// Parse a protocol qualifier type such as '<NSCopying>', which is
16561558Srgrimes  /// an anachronistic way of writing 'id<NSCopying>'.
16571558Srgrimes  TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
16581558Srgrimes
16591558Srgrimes  /// Parse Objective-C type arguments and protocol qualifiers, extending the
16601558Srgrimes  /// current type with the parsed result.
16611558Srgrimes  TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
16621558Srgrimes                                                    ParsedType type,
16631558Srgrimes                                                    bool consumeLastToken,
16641558Srgrimes                                                    SourceLocation &endLoc);
16651558Srgrimes
16661558Srgrimes  void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
16671558Srgrimes                                  Decl *CDecl);
16681558Srgrimes  DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
16691558Srgrimes                                                ParsedAttributes &prefixAttrs);
16701558Srgrimes
16711558Srgrimes  struct ObjCImplParsingDataRAII {
16721558Srgrimes    Parser &P;
16731558Srgrimes    Decl *Dcl;
16741558Srgrimes    bool HasCFunction;
16751558Srgrimes    typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
16761558Srgrimes    LateParsedObjCMethodContainer LateParsedObjCMethods;
16771558Srgrimes
16781558Srgrimes    ObjCImplParsingDataRAII(Parser &parser, Decl *D)
16791558Srgrimes      : P(parser), Dcl(D), HasCFunction(false) {
16801558Srgrimes      P.CurParsedObjCImpl = this;
168136632Scharnier      Finished = false;
168236632Scharnier    }
16831558Srgrimes    ~ObjCImplParsingDataRAII();
16841558Srgrimes
16851558Srgrimes    void finish(SourceRange AtEnd);
168613544Sjoerg    bool isFinished() const { return Finished; }
168792541Simp
16881558Srgrimes  private:
168913544Sjoerg    bool Finished;
16901558Srgrimes  };
16911558Srgrimes  ObjCImplParsingDataRAII *CurParsedObjCImpl;
169213544Sjoerg  void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
169313544Sjoerg
16941558Srgrimes  DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
169513544Sjoerg                                                      ParsedAttributes &Attrs);
16961558Srgrimes  DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
16971558Srgrimes  Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
169813544Sjoerg  Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
169992541Simp  Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
17001558Srgrimes
17011558Srgrimes  IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
170226542Scharnier  // Definitions for Objective-c context sensitive keywords recognition.
170326542Scharnier  enum ObjCTypeQual {
170426542Scharnier    objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
170573034Sjwd    objc_nonnull, objc_nullable, objc_null_unspecified,
170626542Scharnier    objc_NumQuals
170773034Sjwd  };
170826542Scharnier  IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
170973034Sjwd
171026542Scharnier  bool isTokIdentifier_in() const;
17111558Srgrimes
171273034Sjwd  ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
171326542Scharnier                               ParsedAttributes *ParamAttrs);
171473034Sjwd  Decl *ParseObjCMethodPrototype(
171526542Scharnier            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
171673034Sjwd            bool MethodDefinition = true);
171726542Scharnier  Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
17181558Srgrimes            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
171973034Sjwd            bool MethodDefinition=true);
172026542Scharnier  void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
172173034Sjwd
172226542Scharnier  Decl *ParseObjCMethodDefinition();
172373034Sjwd
172426542Scharnierpublic:
17251558Srgrimes  //===--------------------------------------------------------------------===//
172626542Scharnier  // C99 6.5: Expressions.
172726542Scharnier
17281558Srgrimes  /// TypeCastState - State whether an expression is or may be a type cast.
172926542Scharnier  enum TypeCastState {
173026542Scharnier    NotTypeCast = 0,
173173034Sjwd    MaybeTypeCast,
173226542Scharnier    IsTypeCast
173373034Sjwd  };
173426542Scharnier
173573034Sjwd  ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
173626542Scharnier  ExprResult ParseConstantExpressionInExprEvalContext(
173726542Scharnier      TypeCastState isTypeCast = NotTypeCast);
173826542Scharnier  ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
17391558Srgrimes  ExprResult ParseCaseExpression(SourceLocation CaseLoc);
17401558Srgrimes  ExprResult ParseConstraintExpression();
17411558Srgrimes  ExprResult
1742  ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause);
1743  ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause);
1744  // Expr that doesn't include commas.
1745  ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1746
1747  ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1748                                  unsigned &NumLineToksConsumed,
1749                                  bool IsUnevaluated);
1750
1751  ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1752
1753private:
1754  ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1755
1756  ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1757
1758  ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1759                                        prec::Level MinPrec);
1760  /// Control what ParseCastExpression will parse.
1761  enum CastParseKind {
1762    AnyCastExpr = 0,
1763    UnaryExprOnly,
1764    PrimaryExprOnly
1765  };
1766  ExprResult ParseCastExpression(CastParseKind ParseKind,
1767                                 bool isAddressOfOperand,
1768                                 bool &NotCastExpr,
1769                                 TypeCastState isTypeCast,
1770                                 bool isVectorLiteral = false,
1771                                 bool *NotPrimaryExpression = nullptr);
1772  ExprResult ParseCastExpression(CastParseKind ParseKind,
1773                                 bool isAddressOfOperand = false,
1774                                 TypeCastState isTypeCast = NotTypeCast,
1775                                 bool isVectorLiteral = false,
1776                                 bool *NotPrimaryExpression = nullptr);
1777
1778  /// Returns true if the next token cannot start an expression.
1779  bool isNotExpressionStart();
1780
1781  /// Returns true if the next token would start a postfix-expression
1782  /// suffix.
1783  bool isPostfixExpressionSuffixStart() {
1784    tok::TokenKind K = Tok.getKind();
1785    return (K == tok::l_square || K == tok::l_paren ||
1786            K == tok::period || K == tok::arrow ||
1787            K == tok::plusplus || K == tok::minusminus);
1788  }
1789
1790  bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less);
1791  void checkPotentialAngleBracket(ExprResult &PotentialTemplateName);
1792  bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &,
1793                                           const Token &OpToken);
1794  bool checkPotentialAngleBracketDelimiter(const Token &OpToken) {
1795    if (auto *Info = AngleBrackets.getCurrent(*this))
1796      return checkPotentialAngleBracketDelimiter(*Info, OpToken);
1797    return false;
1798  }
1799
1800  ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1801  ExprResult ParseUnaryExprOrTypeTraitExpression();
1802  ExprResult ParseBuiltinPrimaryExpression();
1803
1804  ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1805                                                     bool &isCastExpr,
1806                                                     ParsedType &CastTy,
1807                                                     SourceRange &CastRange);
1808
1809  typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1810
1811  /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1812  bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1813                           SmallVectorImpl<SourceLocation> &CommaLocs,
1814                           llvm::function_ref<void()> ExpressionStarts =
1815                               llvm::function_ref<void()>());
1816
1817  /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1818  /// used for misc language extensions.
1819  bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1820                                 SmallVectorImpl<SourceLocation> &CommaLocs);
1821
1822
1823  /// ParenParseOption - Control what ParseParenExpression will parse.
1824  enum ParenParseOption {
1825    SimpleExpr,      // Only parse '(' expression ')'
1826    FoldExpr,        // Also allow fold-expression <anything>
1827    CompoundStmt,    // Also allow '(' compound-statement ')'
1828    CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1829    CastExpr         // Also allow '(' type-name ')' <anything>
1830  };
1831  ExprResult ParseParenExpression(ParenParseOption &ExprType,
1832                                        bool stopIfCastExpr,
1833                                        bool isTypeCast,
1834                                        ParsedType &CastTy,
1835                                        SourceLocation &RParenLoc);
1836
1837  ExprResult ParseCXXAmbiguousParenExpression(
1838      ParenParseOption &ExprType, ParsedType &CastTy,
1839      BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1840  ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1841                                                  SourceLocation LParenLoc,
1842                                                  SourceLocation RParenLoc);
1843
1844  ExprResult ParseGenericSelectionExpression();
1845
1846  ExprResult ParseObjCBoolLiteral();
1847
1848  ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1849
1850  //===--------------------------------------------------------------------===//
1851  // C++ Expressions
1852  ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1853                                     Token &Replacement);
1854  ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1855
1856  bool areTokensAdjacent(const Token &A, const Token &B);
1857
1858  void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1859                                  bool EnteringContext, IdentifierInfo &II,
1860                                  CXXScopeSpec &SS);
1861
1862  bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1863                                      ParsedType ObjectType,
1864                                      bool ObjectHasErrors,
1865                                      bool EnteringContext,
1866                                      bool *MayBePseudoDestructor = nullptr,
1867                                      bool IsTypename = false,
1868                                      IdentifierInfo **LastII = nullptr,
1869                                      bool OnlyNamespace = false,
1870                                      bool InUsingDeclaration = false);
1871
1872  //===--------------------------------------------------------------------===//
1873  // C++11 5.1.2: Lambda expressions
1874
1875  /// Result of tentatively parsing a lambda-introducer.
1876  enum class LambdaIntroducerTentativeParse {
1877    /// This appears to be a lambda-introducer, which has been fully parsed.
1878    Success,
1879    /// This is a lambda-introducer, but has not been fully parsed, and this
1880    /// function needs to be called again to parse it.
1881    Incomplete,
1882    /// This is definitely an Objective-C message send expression, rather than
1883    /// a lambda-introducer, attribute-specifier, or array designator.
1884    MessageSend,
1885    /// This is not a lambda-introducer.
1886    Invalid,
1887  };
1888
1889  // [...] () -> type {...}
1890  ExprResult ParseLambdaExpression();
1891  ExprResult TryParseLambdaExpression();
1892  bool
1893  ParseLambdaIntroducer(LambdaIntroducer &Intro,
1894                        LambdaIntroducerTentativeParse *Tentative = nullptr);
1895  ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro);
1896
1897  //===--------------------------------------------------------------------===//
1898  // C++ 5.2p1: C++ Casts
1899  ExprResult ParseCXXCasts();
1900
1901  /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast.
1902  ExprResult ParseBuiltinBitCast();
1903
1904  //===--------------------------------------------------------------------===//
1905  // C++ 5.2p1: C++ Type Identification
1906  ExprResult ParseCXXTypeid();
1907
1908  //===--------------------------------------------------------------------===//
1909  //  C++ : Microsoft __uuidof Expression
1910  ExprResult ParseCXXUuidof();
1911
1912  //===--------------------------------------------------------------------===//
1913  // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1914  ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1915                                            tok::TokenKind OpKind,
1916                                            CXXScopeSpec &SS,
1917                                            ParsedType ObjectType);
1918
1919  //===--------------------------------------------------------------------===//
1920  // C++ 9.3.2: C++ 'this' pointer
1921  ExprResult ParseCXXThis();
1922
1923  //===--------------------------------------------------------------------===//
1924  // C++ 15: C++ Throw Expression
1925  ExprResult ParseThrowExpression();
1926
1927  ExceptionSpecificationType tryParseExceptionSpecification(
1928                    bool Delayed,
1929                    SourceRange &SpecificationRange,
1930                    SmallVectorImpl<ParsedType> &DynamicExceptions,
1931                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1932                    ExprResult &NoexceptExpr,
1933                    CachedTokens *&ExceptionSpecTokens);
1934
1935  // EndLoc is filled with the location of the last token of the specification.
1936  ExceptionSpecificationType ParseDynamicExceptionSpecification(
1937                                  SourceRange &SpecificationRange,
1938                                  SmallVectorImpl<ParsedType> &Exceptions,
1939                                  SmallVectorImpl<SourceRange> &Ranges);
1940
1941  //===--------------------------------------------------------------------===//
1942  // C++0x 8: Function declaration trailing-return-type
1943  TypeResult ParseTrailingReturnType(SourceRange &Range,
1944                                     bool MayBeFollowedByDirectInit);
1945
1946  //===--------------------------------------------------------------------===//
1947  // C++ 2.13.5: C++ Boolean Literals
1948  ExprResult ParseCXXBoolLiteral();
1949
1950  //===--------------------------------------------------------------------===//
1951  // C++ 5.2.3: Explicit type conversion (functional notation)
1952  ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1953
1954  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1955  /// This should only be called when the current token is known to be part of
1956  /// simple-type-specifier.
1957  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1958
1959  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1960
1961  //===--------------------------------------------------------------------===//
1962  // C++ 5.3.4 and 5.3.5: C++ new and delete
1963  bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1964                                   Declarator &D);
1965  void ParseDirectNewDeclarator(Declarator &D);
1966  ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1967  ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1968                                            SourceLocation Start);
1969
1970  //===--------------------------------------------------------------------===//
1971  // C++ if/switch/while/for condition expression.
1972  struct ForRangeInfo;
1973  Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
1974                                          SourceLocation Loc,
1975                                          Sema::ConditionKind CK,
1976                                          ForRangeInfo *FRI = nullptr,
1977                                          bool EnterForConditionScope = false);
1978
1979  //===--------------------------------------------------------------------===//
1980  // C++ Coroutines
1981
1982  ExprResult ParseCoyieldExpression();
1983
1984  //===--------------------------------------------------------------------===//
1985  // C++ Concepts
1986
1987  ExprResult ParseRequiresExpression();
1988  void ParseTrailingRequiresClause(Declarator &D);
1989
1990  //===--------------------------------------------------------------------===//
1991  // C99 6.7.8: Initialization.
1992
1993  /// ParseInitializer
1994  ///       initializer: [C99 6.7.8]
1995  ///         assignment-expression
1996  ///         '{' ...
1997  ExprResult ParseInitializer() {
1998    if (Tok.isNot(tok::l_brace))
1999      return ParseAssignmentExpression();
2000    return ParseBraceInitializer();
2001  }
2002  bool MayBeDesignationStart();
2003  ExprResult ParseBraceInitializer();
2004  struct DesignatorCompletionInfo {
2005    SmallVectorImpl<Expr *> &InitExprs;
2006    QualType PreferredBaseType;
2007  };
2008  ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
2009
2010  //===--------------------------------------------------------------------===//
2011  // clang Expressions
2012
2013  ExprResult ParseBlockLiteralExpression();  // ^{...}
2014
2015  //===--------------------------------------------------------------------===//
2016  // Objective-C Expressions
2017  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
2018  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
2019  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
2020  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
2021  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
2022  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
2023  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
2024  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
2025  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
2026  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
2027  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
2028  bool isSimpleObjCMessageExpression();
2029  ExprResult ParseObjCMessageExpression();
2030  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
2031                                            SourceLocation SuperLoc,
2032                                            ParsedType ReceiverType,
2033                                            Expr *ReceiverExpr);
2034  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
2035      SourceLocation LBracloc, SourceLocation SuperLoc,
2036      ParsedType ReceiverType, Expr *ReceiverExpr);
2037  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
2038
2039  //===--------------------------------------------------------------------===//
2040  // C99 6.8: Statements and Blocks.
2041
2042  /// A SmallVector of statements, with stack size 32 (as that is the only one
2043  /// used.)
2044  typedef SmallVector<Stmt*, 32> StmtVector;
2045  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
2046  typedef SmallVector<Expr*, 12> ExprVector;
2047  /// A SmallVector of types.
2048  typedef SmallVector<ParsedType, 12> TypeVector;
2049
2050  StmtResult
2051  ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
2052                 ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt);
2053  StmtResult ParseStatementOrDeclaration(
2054      StmtVector &Stmts, ParsedStmtContext StmtCtx,
2055      SourceLocation *TrailingElseLoc = nullptr);
2056  StmtResult ParseStatementOrDeclarationAfterAttributes(
2057                                         StmtVector &Stmts,
2058                                         ParsedStmtContext StmtCtx,
2059                                         SourceLocation *TrailingElseLoc,
2060                                         ParsedAttributesWithRange &Attrs);
2061  StmtResult ParseExprStatement(ParsedStmtContext StmtCtx);
2062  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs,
2063                                   ParsedStmtContext StmtCtx);
2064  StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx,
2065                                bool MissingCase = false,
2066                                ExprResult Expr = ExprResult());
2067  StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx);
2068  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
2069  StmtResult ParseCompoundStatement(bool isStmtExpr,
2070                                    unsigned ScopeFlags);
2071  void ParseCompoundStatementLeadingPragmas();
2072  bool ConsumeNullStmt(StmtVector &Stmts);
2073  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
2074  bool ParseParenExprOrCondition(StmtResult *InitStmt,
2075                                 Sema::ConditionResult &CondResult,
2076                                 SourceLocation Loc, Sema::ConditionKind CK,
2077                                 SourceLocation *LParenLoc = nullptr,
2078                                 SourceLocation *RParenLoc = nullptr);
2079  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
2080  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
2081  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
2082  StmtResult ParseDoStatement();
2083  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
2084  StmtResult ParseGotoStatement();
2085  StmtResult ParseContinueStatement();
2086  StmtResult ParseBreakStatement();
2087  StmtResult ParseReturnStatement();
2088  StmtResult ParseAsmStatement(bool &msAsm);
2089  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
2090  StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
2091                                 ParsedStmtContext StmtCtx,
2092                                 SourceLocation *TrailingElseLoc,
2093                                 ParsedAttributesWithRange &Attrs);
2094
2095  /// Describes the behavior that should be taken for an __if_exists
2096  /// block.
2097  enum IfExistsBehavior {
2098    /// Parse the block; this code is always used.
2099    IEB_Parse,
2100    /// Skip the block entirely; this code is never used.
2101    IEB_Skip,
2102    /// Parse the block as a dependent block, which may be used in
2103    /// some template instantiations but not others.
2104    IEB_Dependent
2105  };
2106
2107  /// Describes the condition of a Microsoft __if_exists or
2108  /// __if_not_exists block.
2109  struct IfExistsCondition {
2110    /// The location of the initial keyword.
2111    SourceLocation KeywordLoc;
2112    /// Whether this is an __if_exists block (rather than an
2113    /// __if_not_exists block).
2114    bool IsIfExists;
2115
2116    /// Nested-name-specifier preceding the name.
2117    CXXScopeSpec SS;
2118
2119    /// The name we're looking for.
2120    UnqualifiedId Name;
2121
2122    /// The behavior of this __if_exists or __if_not_exists block
2123    /// should.
2124    IfExistsBehavior Behavior;
2125  };
2126
2127  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
2128  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
2129  void ParseMicrosoftIfExistsExternalDeclaration();
2130  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
2131                                              ParsedAttributes &AccessAttrs,
2132                                              AccessSpecifier &CurAS);
2133  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
2134                                              bool &InitExprsOk);
2135  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
2136                           SmallVectorImpl<Expr *> &Constraints,
2137                           SmallVectorImpl<Expr *> &Exprs);
2138
2139  //===--------------------------------------------------------------------===//
2140  // C++ 6: Statements and Blocks
2141
2142  StmtResult ParseCXXTryBlock();
2143  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
2144  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
2145
2146  //===--------------------------------------------------------------------===//
2147  // MS: SEH Statements and Blocks
2148
2149  StmtResult ParseSEHTryBlock();
2150  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
2151  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
2152  StmtResult ParseSEHLeaveStatement();
2153
2154  //===--------------------------------------------------------------------===//
2155  // Objective-C Statements
2156
2157  StmtResult ParseObjCAtStatement(SourceLocation atLoc,
2158                                  ParsedStmtContext StmtCtx);
2159  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
2160  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
2161  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
2162  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
2163
2164
2165  //===--------------------------------------------------------------------===//
2166  // C99 6.7: Declarations.
2167
2168  /// A context for parsing declaration specifiers.  TODO: flesh this
2169  /// out, there are other significant restrictions on specifiers than
2170  /// would be best implemented in the parser.
2171  enum class DeclSpecContext {
2172    DSC_normal, // normal context
2173    DSC_class,  // class context, enables 'friend'
2174    DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
2175    DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
2176    DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
2177    DSC_top_level, // top-level/namespace declaration context
2178    DSC_template_param, // template parameter context
2179    DSC_template_type_arg, // template type argument context
2180    DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
2181    DSC_condition // condition declaration context
2182  };
2183
2184  /// Is this a context in which we are parsing just a type-specifier (or
2185  /// trailing-type-specifier)?
2186  static bool isTypeSpecifier(DeclSpecContext DSC) {
2187    switch (DSC) {
2188    case DeclSpecContext::DSC_normal:
2189    case DeclSpecContext::DSC_template_param:
2190    case DeclSpecContext::DSC_class:
2191    case DeclSpecContext::DSC_top_level:
2192    case DeclSpecContext::DSC_objc_method_result:
2193    case DeclSpecContext::DSC_condition:
2194      return false;
2195
2196    case DeclSpecContext::DSC_template_type_arg:
2197    case DeclSpecContext::DSC_type_specifier:
2198    case DeclSpecContext::DSC_trailing:
2199    case DeclSpecContext::DSC_alias_declaration:
2200      return true;
2201    }
2202    llvm_unreachable("Missing DeclSpecContext case");
2203  }
2204
2205  /// Whether a defining-type-specifier is permitted in a given context.
2206  enum class AllowDefiningTypeSpec {
2207    /// The grammar doesn't allow a defining-type-specifier here, and we must
2208    /// not parse one (eg, because a '{' could mean something else).
2209    No,
2210    /// The grammar doesn't allow a defining-type-specifier here, but we permit
2211    /// one for error recovery purposes. Sema will reject.
2212    NoButErrorRecovery,
2213    /// The grammar allows a defining-type-specifier here, even though it's
2214    /// always invalid. Sema will reject.
2215    YesButInvalid,
2216    /// The grammar allows a defining-type-specifier here, and one can be valid.
2217    Yes
2218  };
2219
2220  /// Is this a context in which we are parsing defining-type-specifiers (and
2221  /// so permit class and enum definitions in addition to non-defining class and
2222  /// enum elaborated-type-specifiers)?
2223  static AllowDefiningTypeSpec
2224  isDefiningTypeSpecifierContext(DeclSpecContext DSC) {
2225    switch (DSC) {
2226    case DeclSpecContext::DSC_normal:
2227    case DeclSpecContext::DSC_class:
2228    case DeclSpecContext::DSC_top_level:
2229    case DeclSpecContext::DSC_alias_declaration:
2230    case DeclSpecContext::DSC_objc_method_result:
2231      return AllowDefiningTypeSpec::Yes;
2232
2233    case DeclSpecContext::DSC_condition:
2234    case DeclSpecContext::DSC_template_param:
2235      return AllowDefiningTypeSpec::YesButInvalid;
2236
2237    case DeclSpecContext::DSC_template_type_arg:
2238    case DeclSpecContext::DSC_type_specifier:
2239      return AllowDefiningTypeSpec::NoButErrorRecovery;
2240
2241    case DeclSpecContext::DSC_trailing:
2242      return AllowDefiningTypeSpec::No;
2243    }
2244    llvm_unreachable("Missing DeclSpecContext case");
2245  }
2246
2247  /// Is this a context in which an opaque-enum-declaration can appear?
2248  static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
2249    switch (DSC) {
2250    case DeclSpecContext::DSC_normal:
2251    case DeclSpecContext::DSC_class:
2252    case DeclSpecContext::DSC_top_level:
2253      return true;
2254
2255    case DeclSpecContext::DSC_alias_declaration:
2256    case DeclSpecContext::DSC_objc_method_result:
2257    case DeclSpecContext::DSC_condition:
2258    case DeclSpecContext::DSC_template_param:
2259    case DeclSpecContext::DSC_template_type_arg:
2260    case DeclSpecContext::DSC_type_specifier:
2261    case DeclSpecContext::DSC_trailing:
2262      return false;
2263    }
2264    llvm_unreachable("Missing DeclSpecContext case");
2265  }
2266
2267  /// Is this a context in which we can perform class template argument
2268  /// deduction?
2269  static bool isClassTemplateDeductionContext(DeclSpecContext DSC) {
2270    switch (DSC) {
2271    case DeclSpecContext::DSC_normal:
2272    case DeclSpecContext::DSC_template_param:
2273    case DeclSpecContext::DSC_class:
2274    case DeclSpecContext::DSC_top_level:
2275    case DeclSpecContext::DSC_condition:
2276    case DeclSpecContext::DSC_type_specifier:
2277      return true;
2278
2279    case DeclSpecContext::DSC_objc_method_result:
2280    case DeclSpecContext::DSC_template_type_arg:
2281    case DeclSpecContext::DSC_trailing:
2282    case DeclSpecContext::DSC_alias_declaration:
2283      return false;
2284    }
2285    llvm_unreachable("Missing DeclSpecContext case");
2286  }
2287
2288  /// Information on a C++0x for-range-initializer found while parsing a
2289  /// declaration which turns out to be a for-range-declaration.
2290  struct ForRangeInit {
2291    SourceLocation ColonLoc;
2292    ExprResult RangeExpr;
2293
2294    bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
2295  };
2296  struct ForRangeInfo : ForRangeInit {
2297    StmtResult LoopVar;
2298  };
2299
2300  DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context,
2301                                  SourceLocation &DeclEnd,
2302                                  ParsedAttributesWithRange &attrs,
2303                                  SourceLocation *DeclSpecStart = nullptr);
2304  DeclGroupPtrTy
2305  ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
2306                         ParsedAttributesWithRange &attrs, bool RequireSemi,
2307                         ForRangeInit *FRI = nullptr,
2308                         SourceLocation *DeclSpecStart = nullptr);
2309  bool MightBeDeclarator(DeclaratorContext Context);
2310  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context,
2311                                SourceLocation *DeclEnd = nullptr,
2312                                ForRangeInit *FRI = nullptr);
2313  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
2314               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
2315  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
2316  Decl *ParseDeclarationAfterDeclaratorAndAttributes(
2317      Declarator &D,
2318      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2319      ForRangeInit *FRI = nullptr);
2320  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
2321  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
2322
2323  /// When in code-completion, skip parsing of the function/method body
2324  /// unless the body contains the code-completion point.
2325  ///
2326  /// \returns true if the function body was skipped.
2327  bool trySkippingFunctionBody();
2328
2329  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2330                        const ParsedTemplateInfo &TemplateInfo,
2331                        AccessSpecifier AS, DeclSpecContext DSC,
2332                        ParsedAttributesWithRange &Attrs);
2333  DeclSpecContext
2334  getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
2335  void ParseDeclarationSpecifiers(
2336      DeclSpec &DS,
2337      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2338      AccessSpecifier AS = AS_none,
2339      DeclSpecContext DSC = DeclSpecContext::DSC_normal,
2340      LateParsedAttrList *LateAttrs = nullptr);
2341  bool DiagnoseMissingSemiAfterTagDefinition(
2342      DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext,
2343      LateParsedAttrList *LateAttrs = nullptr);
2344
2345  void ParseSpecifierQualifierList(
2346      DeclSpec &DS, AccessSpecifier AS = AS_none,
2347      DeclSpecContext DSC = DeclSpecContext::DSC_normal);
2348
2349  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
2350                                  DeclaratorContext Context);
2351
2352  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
2353                          const ParsedTemplateInfo &TemplateInfo,
2354                          AccessSpecifier AS, DeclSpecContext DSC);
2355  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
2356  void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType,
2357                            RecordDecl *TagDecl);
2358
2359  void ParseStructDeclaration(
2360      ParsingDeclSpec &DS,
2361      llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
2362
2363  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
2364  bool isTypeSpecifierQualifier();
2365
2366  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2367  /// is definitely a type-specifier.  Return false if it isn't part of a type
2368  /// specifier or if we're not sure.
2369  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
2370
2371  /// Return true if we know that we are definitely looking at a
2372  /// decl-specifier, and isn't part of an expression such as a function-style
2373  /// cast. Return false if it's no a decl-specifier, or we're not sure.
2374  bool isKnownToBeDeclarationSpecifier() {
2375    if (getLangOpts().CPlusPlus)
2376      return isCXXDeclarationSpecifier() == TPResult::True;
2377    return isDeclarationSpecifier(true);
2378  }
2379
2380  /// isDeclarationStatement - Disambiguates between a declaration or an
2381  /// expression statement, when parsing function bodies.
2382  /// Returns true for declaration, false for expression.
2383  bool isDeclarationStatement() {
2384    if (getLangOpts().CPlusPlus)
2385      return isCXXDeclarationStatement();
2386    return isDeclarationSpecifier(true);
2387  }
2388
2389  /// isForInitDeclaration - Disambiguates between a declaration or an
2390  /// expression in the context of the C 'clause-1' or the C++
2391  // 'for-init-statement' part of a 'for' statement.
2392  /// Returns true for declaration, false for expression.
2393  bool isForInitDeclaration() {
2394    if (getLangOpts().OpenMP)
2395      Actions.startOpenMPLoop();
2396    if (getLangOpts().CPlusPlus)
2397      return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
2398    return isDeclarationSpecifier(true);
2399  }
2400
2401  /// Determine whether this is a C++1z for-range-identifier.
2402  bool isForRangeIdentifier();
2403
2404  /// Determine whether we are currently at the start of an Objective-C
2405  /// class message that appears to be missing the open bracket '['.
2406  bool isStartOfObjCClassMessageMissingOpenBracket();
2407
2408  /// Starting with a scope specifier, identifier, or
2409  /// template-id that refers to the current class, determine whether
2410  /// this is a constructor declarator.
2411  bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false);
2412
2413  /// Specifies the context in which type-id/expression
2414  /// disambiguation will occur.
2415  enum TentativeCXXTypeIdContext {
2416    TypeIdInParens,
2417    TypeIdUnambiguous,
2418    TypeIdAsTemplateArgument
2419  };
2420
2421
2422  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
2423  /// whether the parens contain an expression or a type-id.
2424  /// Returns true for a type-id and false for an expression.
2425  bool isTypeIdInParens(bool &isAmbiguous) {
2426    if (getLangOpts().CPlusPlus)
2427      return isCXXTypeId(TypeIdInParens, isAmbiguous);
2428    isAmbiguous = false;
2429    return isTypeSpecifierQualifier();
2430  }
2431  bool isTypeIdInParens() {
2432    bool isAmbiguous;
2433    return isTypeIdInParens(isAmbiguous);
2434  }
2435
2436  /// Checks if the current tokens form type-id or expression.
2437  /// It is similar to isTypeIdInParens but does not suppose that type-id
2438  /// is in parenthesis.
2439  bool isTypeIdUnambiguously() {
2440    bool IsAmbiguous;
2441    if (getLangOpts().CPlusPlus)
2442      return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
2443    return isTypeSpecifierQualifier();
2444  }
2445
2446  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
2447  /// between a declaration or an expression statement, when parsing function
2448  /// bodies. Returns true for declaration, false for expression.
2449  bool isCXXDeclarationStatement();
2450
2451  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
2452  /// between a simple-declaration or an expression-statement.
2453  /// If during the disambiguation process a parsing error is encountered,
2454  /// the function returns true to let the declaration parsing code handle it.
2455  /// Returns false if the statement is disambiguated as expression.
2456  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
2457
2458  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
2459  /// a constructor-style initializer, when parsing declaration statements.
2460  /// Returns true for function declarator and false for constructor-style
2461  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
2462  /// might be a constructor-style initializer.
2463  /// If during the disambiguation process a parsing error is encountered,
2464  /// the function returns true to let the declaration parsing code handle it.
2465  bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
2466
2467  struct ConditionDeclarationOrInitStatementState;
2468  enum class ConditionOrInitStatement {
2469    Expression,    ///< Disambiguated as an expression (either kind).
2470    ConditionDecl, ///< Disambiguated as the declaration form of condition.
2471    InitStmtDecl,  ///< Disambiguated as a simple-declaration init-statement.
2472    ForRangeDecl,  ///< Disambiguated as a for-range declaration.
2473    Error          ///< Can't be any of the above!
2474  };
2475  /// Disambiguates between the different kinds of things that can happen
2476  /// after 'if (' or 'switch ('. This could be one of two different kinds of
2477  /// declaration (depending on whether there is a ';' later) or an expression.
2478  ConditionOrInitStatement
2479  isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt,
2480                                           bool CanBeForRangeDecl);
2481
2482  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
2483  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
2484    bool isAmbiguous;
2485    return isCXXTypeId(Context, isAmbiguous);
2486  }
2487
2488  /// TPResult - Used as the result value for functions whose purpose is to
2489  /// disambiguate C++ constructs by "tentatively parsing" them.
2490  enum class TPResult {
2491    True, False, Ambiguous, Error
2492  };
2493
2494  /// Determine whether we could have an enum-base.
2495  ///
2496  /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
2497  /// only consider this to be an enum-base if the next token is a '{'.
2498  ///
2499  /// \return \c false if this cannot possibly be an enum base; \c true
2500  /// otherwise.
2501  bool isEnumBase(bool AllowSemi);
2502
2503  /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2504  /// declaration specifier, TPResult::False if it is not,
2505  /// TPResult::Ambiguous if it could be either a decl-specifier or a
2506  /// function-style cast, and TPResult::Error if a parsing error was
2507  /// encountered. If it could be a braced C++11 function-style cast, returns
2508  /// BracedCastResult.
2509  /// Doesn't consume tokens.
2510  TPResult
2511  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2512                            bool *InvalidAsDeclSpec = nullptr);
2513
2514  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2515  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2516  /// a type-specifier other than a cv-qualifier.
2517  bool isCXXDeclarationSpecifierAType();
2518
2519  /// Determine whether the current token sequence might be
2520  ///   '<' template-argument-list '>'
2521  /// rather than a less-than expression.
2522  TPResult isTemplateArgumentList(unsigned TokensToSkip);
2523
2524  /// Determine whether an '(' after an 'explicit' keyword is part of a C++20
2525  /// 'explicit(bool)' declaration, in earlier language modes where that is an
2526  /// extension.
2527  TPResult isExplicitBool();
2528
2529  /// Determine whether an identifier has been tentatively declared as a
2530  /// non-type. Such tentative declarations should not be found to name a type
2531  /// during a tentative parse, but also should not be annotated as a non-type.
2532  bool isTentativelyDeclared(IdentifierInfo *II);
2533
2534  // "Tentative parsing" functions, used for disambiguation. If a parsing error
2535  // is encountered they will return TPResult::Error.
2536  // Returning TPResult::True/False indicates that the ambiguity was
2537  // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2538  // that more tentative parsing is necessary for disambiguation.
2539  // They all consume tokens, so backtracking should be used after calling them.
2540
2541  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2542  TPResult TryParseTypeofSpecifier();
2543  TPResult TryParseProtocolQualifiers();
2544  TPResult TryParsePtrOperatorSeq();
2545  TPResult TryParseOperatorId();
2546  TPResult TryParseInitDeclaratorList();
2547  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true,
2548                              bool mayHaveDirectInit = false);
2549  TPResult
2550  TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2551                                     bool VersusTemplateArg = false);
2552  TPResult TryParseFunctionDeclarator();
2553  TPResult TryParseBracketDeclarator();
2554  TPResult TryConsumeDeclarationSpecifier();
2555
2556  /// Try to skip a possibly empty sequence of 'attribute-specifier's without
2557  /// full validation of the syntactic structure of attributes.
2558  bool TrySkipAttributes();
2559
2560public:
2561  TypeResult
2562  ParseTypeName(SourceRange *Range = nullptr,
2563                DeclaratorContext Context = DeclaratorContext::TypeName,
2564                AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr,
2565                ParsedAttributes *Attrs = nullptr);
2566
2567private:
2568  void ParseBlockId(SourceLocation CaretLoc);
2569
2570  /// Are [[]] attributes enabled?
2571  bool standardAttributesAllowed() const {
2572    const LangOptions &LO = getLangOpts();
2573    return LO.DoubleSquareBracketAttributes;
2574  }
2575
2576  // Check for the start of an attribute-specifier-seq in a context where an
2577  // attribute is not allowed.
2578  bool CheckProhibitedCXX11Attribute() {
2579    assert(Tok.is(tok::l_square));
2580    if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
2581      return false;
2582    return DiagnoseProhibitedCXX11Attribute();
2583  }
2584
2585  bool DiagnoseProhibitedCXX11Attribute();
2586  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2587                                    SourceLocation CorrectLocation) {
2588    if (!standardAttributesAllowed())
2589      return;
2590    if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2591        Tok.isNot(tok::kw_alignas))
2592      return;
2593    DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2594  }
2595  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2596                                       SourceLocation CorrectLocation);
2597
2598  void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
2599                                      DeclSpec &DS, Sema::TagUseKind TUK);
2600
2601  // FixItLoc = possible correct location for the attributes
2602  void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
2603                          SourceLocation FixItLoc = SourceLocation()) {
2604    if (Attrs.Range.isInvalid())
2605      return;
2606    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2607    Attrs.clear();
2608  }
2609
2610  void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
2611                          SourceLocation FixItLoc = SourceLocation()) {
2612    if (Attrs.Range.isInvalid())
2613      return;
2614    DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
2615    Attrs.clearListOnly();
2616  }
2617  void DiagnoseProhibitedAttributes(const SourceRange &Range,
2618                                    SourceLocation FixItLoc);
2619
2620  // Forbid C++11 and C2x attributes that appear on certain syntactic locations
2621  // which standard permits but we don't supported yet, for example, attributes
2622  // appertain to decl specifiers.
2623  void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
2624                               unsigned DiagID,
2625                               bool DiagnoseEmptyAttrs = false);
2626
2627  /// Skip C++11 and C2x attributes and return the end location of the
2628  /// last one.
2629  /// \returns SourceLocation() if there are no attributes.
2630  SourceLocation SkipCXX11Attributes();
2631
2632  /// Diagnose and skip C++11 and C2x attributes that appear in syntactic
2633  /// locations where attributes are not allowed.
2634  void DiagnoseAndSkipCXX11Attributes();
2635
2636  /// Parses syntax-generic attribute arguments for attributes which are
2637  /// known to the implementation, and adds them to the given ParsedAttributes
2638  /// list with the given attribute syntax. Returns the number of arguments
2639  /// parsed for the attribute.
2640  unsigned
2641  ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2642                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
2643                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2644                           ParsedAttr::Syntax Syntax);
2645
2646  enum ParseAttrKindMask {
2647    PAKM_GNU = 1 << 0,
2648    PAKM_Declspec = 1 << 1,
2649    PAKM_CXX11 = 1 << 2,
2650  };
2651
2652  /// \brief Parse attributes based on what syntaxes are desired, allowing for
2653  /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec:
2654  /// __attribute__((...)) __declspec(...) __attribute__((...)))
2655  /// Note that Microsoft attributes (spelled with single square brackets) are
2656  /// not supported by this because of parsing ambiguities with other
2657  /// constructs.
2658  ///
2659  /// There are some attribute parse orderings that should not be allowed in
2660  /// arbitrary order. e.g.,
2661  ///
2662  ///   [[]] __attribute__(()) int i; // OK
2663  ///   __attribute__(()) [[]] int i; // Not OK
2664  ///
2665  /// Such situations should use the specific attribute parsing functionality.
2666  void ParseAttributes(unsigned WhichAttrKinds,
2667                       ParsedAttributesWithRange &Attrs,
2668                       SourceLocation *End = nullptr,
2669                       LateParsedAttrList *LateAttrs = nullptr);
2670  void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2671                       SourceLocation *End = nullptr,
2672                       LateParsedAttrList *LateAttrs = nullptr) {
2673    ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2674    ParseAttributes(WhichAttrKinds, AttrsWithRange, End, LateAttrs);
2675    Attrs.takeAllFrom(AttrsWithRange);
2676  }
2677  /// \brief Possibly parse attributes based on what syntaxes are desired,
2678  /// allowing for the order to vary.
2679  bool MaybeParseAttributes(unsigned WhichAttrKinds,
2680                            ParsedAttributesWithRange &Attrs,
2681                            SourceLocation *End = nullptr,
2682                            LateParsedAttrList *LateAttrs = nullptr) {
2683    if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2684        (standardAttributesAllowed() && isCXX11AttributeSpecifier())) {
2685      ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs);
2686      return true;
2687    }
2688    return false;
2689  }
2690  bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
2691                            SourceLocation *End = nullptr,
2692                            LateParsedAttrList *LateAttrs = nullptr) {
2693    if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) ||
2694        (standardAttributesAllowed() && isCXX11AttributeSpecifier())) {
2695      ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs);
2696      return true;
2697    }
2698    return false;
2699  }
2700
2701  void MaybeParseGNUAttributes(Declarator &D,
2702                               LateParsedAttrList *LateAttrs = nullptr) {
2703    if (Tok.is(tok::kw___attribute)) {
2704      ParsedAttributes attrs(AttrFactory);
2705      SourceLocation endLoc;
2706      ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2707      D.takeAttributes(attrs, endLoc);
2708    }
2709  }
2710
2711  /// Parses GNU-style attributes and returns them without source range
2712  /// information.
2713  ///
2714  /// This API is discouraged. Use the version that takes a
2715  /// ParsedAttributesWithRange instead.
2716  bool MaybeParseGNUAttributes(ParsedAttributes &Attrs,
2717                               SourceLocation *EndLoc = nullptr,
2718                               LateParsedAttrList *LateAttrs = nullptr) {
2719    if (Tok.is(tok::kw___attribute)) {
2720      ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2721      ParseGNUAttributes(Attrs, EndLoc, LateAttrs);
2722      Attrs.takeAllFrom(AttrsWithRange);
2723      return true;
2724    }
2725    return false;
2726  }
2727
2728  bool MaybeParseGNUAttributes(ParsedAttributesWithRange &Attrs,
2729                               SourceLocation *EndLoc = nullptr,
2730                               LateParsedAttrList *LateAttrs = nullptr) {
2731    if (Tok.is(tok::kw___attribute)) {
2732      ParseGNUAttributes(Attrs, EndLoc, LateAttrs);
2733      return true;
2734    }
2735    return false;
2736  }
2737
2738  /// Parses GNU-style attributes and returns them without source range
2739  /// information.
2740  ///
2741  /// This API is discouraged. Use the version that takes a
2742  /// ParsedAttributesWithRange instead.
2743  void ParseGNUAttributes(ParsedAttributes &Attrs,
2744                          SourceLocation *EndLoc = nullptr,
2745                          LateParsedAttrList *LateAttrs = nullptr,
2746                          Declarator *D = nullptr) {
2747    ParsedAttributesWithRange AttrsWithRange(AttrFactory);
2748    ParseGNUAttributes(AttrsWithRange, EndLoc, LateAttrs, D);
2749    Attrs.takeAllFrom(AttrsWithRange);
2750  }
2751
2752  void ParseGNUAttributes(ParsedAttributesWithRange &Attrs,
2753                          SourceLocation *EndLoc = nullptr,
2754                          LateParsedAttrList *LateAttrs = nullptr,
2755                          Declarator *D = nullptr);
2756  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2757                             SourceLocation AttrNameLoc,
2758                             ParsedAttributes &Attrs, SourceLocation *EndLoc,
2759                             IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2760                             ParsedAttr::Syntax Syntax, Declarator *D);
2761  IdentifierLoc *ParseIdentifierLoc();
2762
2763  unsigned
2764  ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2765                          ParsedAttributes &Attrs, SourceLocation *EndLoc,
2766                          IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2767                          ParsedAttr::Syntax Syntax);
2768
2769  void MaybeParseCXX11Attributes(Declarator &D) {
2770    if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2771      ParsedAttributesWithRange attrs(AttrFactory);
2772      SourceLocation endLoc;
2773      ParseCXX11Attributes(attrs, &endLoc);
2774      D.takeAttributes(attrs, endLoc);
2775    }
2776  }
2777  bool MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2778                                 SourceLocation *endLoc = nullptr) {
2779    if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
2780      ParsedAttributesWithRange attrsWithRange(AttrFactory);
2781      ParseCXX11Attributes(attrsWithRange, endLoc);
2782      attrs.takeAllFrom(attrsWithRange);
2783      return true;
2784    }
2785    return false;
2786  }
2787  bool MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2788                                 SourceLocation *endLoc = nullptr,
2789                                 bool OuterMightBeMessageSend = false) {
2790    if (standardAttributesAllowed() &&
2791        isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) {
2792      ParseCXX11Attributes(attrs, endLoc);
2793      return true;
2794    }
2795    return false;
2796  }
2797
2798  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2799                                    SourceLocation *EndLoc = nullptr);
2800  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2801                            SourceLocation *EndLoc = nullptr);
2802  /// Parses a C++11 (or C2x)-style attribute argument list. Returns true
2803  /// if this results in adding an attribute to the ParsedAttributes list.
2804  bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2805                               SourceLocation AttrNameLoc,
2806                               ParsedAttributes &Attrs, SourceLocation *EndLoc,
2807                               IdentifierInfo *ScopeName,
2808                               SourceLocation ScopeLoc);
2809
2810  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2811
2812  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2813                                     SourceLocation *endLoc = nullptr) {
2814    if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2815      ParseMicrosoftAttributes(attrs, endLoc);
2816  }
2817  void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
2818  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2819                                SourceLocation *endLoc = nullptr);
2820  bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2821                                    SourceLocation *End = nullptr) {
2822    const auto &LO = getLangOpts();
2823    if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) {
2824      ParseMicrosoftDeclSpecs(Attrs, End);
2825      return true;
2826    }
2827    return false;
2828  }
2829  void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2830                               SourceLocation *End = nullptr);
2831  bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2832                                  SourceLocation AttrNameLoc,
2833                                  ParsedAttributes &Attrs);
2834  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2835  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2836  SourceLocation SkipExtendedMicrosoftTypeAttributes();
2837  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2838  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2839  void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
2840  void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2841  void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2842
2843  VersionTuple ParseVersionTuple(SourceRange &Range);
2844  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2845                                  SourceLocation AvailabilityLoc,
2846                                  ParsedAttributes &attrs,
2847                                  SourceLocation *endLoc,
2848                                  IdentifierInfo *ScopeName,
2849                                  SourceLocation ScopeLoc,
2850                                  ParsedAttr::Syntax Syntax);
2851
2852  Optional<AvailabilitySpec> ParseAvailabilitySpec();
2853  ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
2854
2855  void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
2856                                          SourceLocation Loc,
2857                                          ParsedAttributes &Attrs,
2858                                          SourceLocation *EndLoc,
2859                                          IdentifierInfo *ScopeName,
2860                                          SourceLocation ScopeLoc,
2861                                          ParsedAttr::Syntax Syntax);
2862
2863  void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2864                                       SourceLocation ObjCBridgeRelatedLoc,
2865                                       ParsedAttributes &attrs,
2866                                       SourceLocation *endLoc,
2867                                       IdentifierInfo *ScopeName,
2868                                       SourceLocation ScopeLoc,
2869                                       ParsedAttr::Syntax Syntax);
2870
2871  void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
2872                                  SourceLocation AttrNameLoc,
2873                                  ParsedAttributes &Attrs,
2874                                  SourceLocation *EndLoc,
2875                                  IdentifierInfo *ScopeName,
2876                                  SourceLocation ScopeLoc,
2877                                  ParsedAttr::Syntax Syntax);
2878
2879  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2880                                        SourceLocation AttrNameLoc,
2881                                        ParsedAttributes &Attrs,
2882                                        SourceLocation *EndLoc,
2883                                        IdentifierInfo *ScopeName,
2884                                        SourceLocation ScopeLoc,
2885                                        ParsedAttr::Syntax Syntax);
2886
2887  void
2888  ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2889                            SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
2890                            SourceLocation *EndLoc, IdentifierInfo *ScopeName,
2891                            SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
2892
2893  void ParseTypeofSpecifier(DeclSpec &DS);
2894  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2895  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2896                                         SourceLocation StartLoc,
2897                                         SourceLocation EndLoc);
2898  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2899  void ParseAtomicSpecifier(DeclSpec &DS);
2900
2901  ExprResult ParseAlignArgument(SourceLocation Start,
2902                                SourceLocation &EllipsisLoc);
2903  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2904                               SourceLocation *endLoc = nullptr);
2905  ExprResult ParseExtIntegerArgument();
2906
2907  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2908  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2909    return isCXX11VirtSpecifier(Tok);
2910  }
2911  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2912                                          SourceLocation FriendLoc);
2913
2914  bool isCXX11FinalKeyword() const;
2915
2916  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2917  /// enter a new C++ declarator scope and exit it when the function is
2918  /// finished.
2919  class DeclaratorScopeObj {
2920    Parser &P;
2921    CXXScopeSpec &SS;
2922    bool EnteredScope;
2923    bool CreatedScope;
2924  public:
2925    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2926      : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2927
2928    void EnterDeclaratorScope() {
2929      assert(!EnteredScope && "Already entered the scope!");
2930      assert(SS.isSet() && "C++ scope was not set!");
2931
2932      CreatedScope = true;
2933      P.EnterScope(0); // Not a decl scope.
2934
2935      if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2936        EnteredScope = true;
2937    }
2938
2939    ~DeclaratorScopeObj() {
2940      if (EnteredScope) {
2941        assert(SS.isSet() && "C++ scope was cleared ?");
2942        P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2943      }
2944      if (CreatedScope)
2945        P.ExitScope();
2946    }
2947  };
2948
2949  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2950  void ParseDeclarator(Declarator &D);
2951  /// A function that parses a variant of direct-declarator.
2952  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2953  void ParseDeclaratorInternal(Declarator &D,
2954                               DirectDeclParseFunction DirectDeclParser);
2955
2956  enum AttrRequirements {
2957    AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2958    AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2959    AR_GNUAttributesParsed = 1 << 1,
2960    AR_CXX11AttributesParsed = 1 << 2,
2961    AR_DeclspecAttributesParsed = 1 << 3,
2962    AR_AllAttributesParsed = AR_GNUAttributesParsed |
2963                             AR_CXX11AttributesParsed |
2964                             AR_DeclspecAttributesParsed,
2965    AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2966                                AR_DeclspecAttributesParsed
2967  };
2968
2969  void ParseTypeQualifierListOpt(
2970      DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
2971      bool AtomicAllowed = true, bool IdentifierRequired = false,
2972      Optional<llvm::function_ref<void()>> CodeCompletionHandler = None);
2973  void ParseDirectDeclarator(Declarator &D);
2974  void ParseDecompositionDeclarator(Declarator &D);
2975  void ParseParenDeclarator(Declarator &D);
2976  void ParseFunctionDeclarator(Declarator &D,
2977                               ParsedAttributes &attrs,
2978                               BalancedDelimiterTracker &Tracker,
2979                               bool IsAmbiguous,
2980                               bool RequiresArg = false);
2981  void InitCXXThisScopeForDeclaratorIfRelevant(
2982      const Declarator &D, const DeclSpec &DS,
2983      llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope);
2984  bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2985                         SourceLocation &RefQualifierLoc);
2986  bool isFunctionDeclaratorIdentifierList();
2987  void ParseFunctionDeclaratorIdentifierList(
2988         Declarator &D,
2989         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2990  void ParseParameterDeclarationClause(
2991         DeclaratorContext DeclaratorContext,
2992         ParsedAttributes &attrs,
2993         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2994         SourceLocation &EllipsisLoc);
2995  void ParseBracketDeclarator(Declarator &D);
2996  void ParseMisplacedBracketDeclarator(Declarator &D);
2997
2998  //===--------------------------------------------------------------------===//
2999  // C++ 7: Declarations [dcl.dcl]
3000
3001  /// The kind of attribute specifier we have found.
3002  enum CXX11AttributeKind {
3003    /// This is not an attribute specifier.
3004    CAK_NotAttributeSpecifier,
3005    /// This should be treated as an attribute-specifier.
3006    CAK_AttributeSpecifier,
3007    /// The next tokens are '[[', but this is not an attribute-specifier. This
3008    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
3009    CAK_InvalidAttributeSpecifier
3010  };
3011  CXX11AttributeKind
3012  isCXX11AttributeSpecifier(bool Disambiguate = false,
3013                            bool OuterMightBeMessageSend = false);
3014
3015  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
3016
3017  DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
3018                                SourceLocation &DeclEnd,
3019                                SourceLocation InlineLoc = SourceLocation());
3020
3021  struct InnerNamespaceInfo {
3022    SourceLocation NamespaceLoc;
3023    SourceLocation InlineLoc;
3024    SourceLocation IdentLoc;
3025    IdentifierInfo *Ident;
3026  };
3027  using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>;
3028
3029  void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
3030                           unsigned int index, SourceLocation &InlineLoc,
3031                           ParsedAttributes &attrs,
3032                           BalancedDelimiterTracker &Tracker);
3033  Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context);
3034  Decl *ParseExportDeclaration();
3035  DeclGroupPtrTy ParseUsingDirectiveOrDeclaration(
3036      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3037      SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs);
3038  Decl *ParseUsingDirective(DeclaratorContext Context,
3039                            SourceLocation UsingLoc,
3040                            SourceLocation &DeclEnd,
3041                            ParsedAttributes &attrs);
3042
3043  struct UsingDeclarator {
3044    SourceLocation TypenameLoc;
3045    CXXScopeSpec SS;
3046    UnqualifiedId Name;
3047    SourceLocation EllipsisLoc;
3048
3049    void clear() {
3050      TypenameLoc = EllipsisLoc = SourceLocation();
3051      SS.clear();
3052      Name.clear();
3053    }
3054  };
3055
3056  bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D);
3057  DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context,
3058                                       const ParsedTemplateInfo &TemplateInfo,
3059                                       SourceLocation UsingLoc,
3060                                       SourceLocation &DeclEnd,
3061                                       AccessSpecifier AS = AS_none);
3062  Decl *ParseAliasDeclarationAfterDeclarator(
3063      const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
3064      UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
3065      ParsedAttributes &Attrs, Decl **OwnedType = nullptr);
3066
3067  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
3068  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
3069                            SourceLocation AliasLoc, IdentifierInfo *Alias,
3070                            SourceLocation &DeclEnd);
3071
3072  //===--------------------------------------------------------------------===//
3073  // C++ 9: classes [class] and C structs/unions.
3074  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
3075  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
3076                           DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
3077                           AccessSpecifier AS, bool EnteringContext,
3078                           DeclSpecContext DSC,
3079                           ParsedAttributesWithRange &Attributes);
3080  void SkipCXXMemberSpecification(SourceLocation StartLoc,
3081                                  SourceLocation AttrFixitLoc,
3082                                  unsigned TagType,
3083                                  Decl *TagDecl);
3084  void ParseCXXMemberSpecification(SourceLocation StartLoc,
3085                                   SourceLocation AttrFixitLoc,
3086                                   ParsedAttributesWithRange &Attrs,
3087                                   unsigned TagType,
3088                                   Decl *TagDecl);
3089  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
3090                                       SourceLocation &EqualLoc);
3091  bool
3092  ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
3093                                            VirtSpecifiers &VS,
3094                                            ExprResult &BitfieldSize,
3095                                            LateParsedAttrList &LateAttrs);
3096  void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
3097                                                               VirtSpecifiers &VS);
3098  DeclGroupPtrTy ParseCXXClassMemberDeclaration(
3099      AccessSpecifier AS, ParsedAttributes &Attr,
3100      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
3101      ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
3102  DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
3103      AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3104      DeclSpec::TST TagType, Decl *Tag);
3105  void ParseConstructorInitializer(Decl *ConstructorDecl);
3106  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
3107  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
3108                                      Decl *ThisDecl);
3109
3110  //===--------------------------------------------------------------------===//
3111  // C++ 10: Derived classes [class.derived]
3112  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
3113                                    SourceLocation &EndLocation);
3114  void ParseBaseClause(Decl *ClassDecl);
3115  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
3116  AccessSpecifier getAccessSpecifierIfPresent() const;
3117
3118  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
3119                                    ParsedType ObjectType,
3120                                    bool ObjectHadErrors,
3121                                    SourceLocation TemplateKWLoc,
3122                                    IdentifierInfo *Name,
3123                                    SourceLocation NameLoc,
3124                                    bool EnteringContext,
3125                                    UnqualifiedId &Id,
3126                                    bool AssumeTemplateId);
3127  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
3128                                  ParsedType ObjectType,
3129                                  UnqualifiedId &Result);
3130
3131  //===--------------------------------------------------------------------===//
3132  // OpenMP: Directives and clauses.
3133  /// Parse clauses for '#pragma omp declare simd'.
3134  DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
3135                                            CachedTokens &Toks,
3136                                            SourceLocation Loc);
3137
3138  /// Parse a property kind into \p TIProperty for the selector set \p Set and
3139  /// selector \p Selector.
3140  void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
3141                                 llvm::omp::TraitSet Set,
3142                                 llvm::omp::TraitSelector Selector,
3143                                 llvm::StringMap<SourceLocation> &Seen);
3144
3145  /// Parse a selector kind into \p TISelector for the selector set \p Set.
3146  void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
3147                                 llvm::omp::TraitSet Set,
3148                                 llvm::StringMap<SourceLocation> &Seen);
3149
3150  /// Parse a selector set kind into \p TISet.
3151  void parseOMPTraitSetKind(OMPTraitSet &TISet,
3152                            llvm::StringMap<SourceLocation> &Seen);
3153
3154  /// Parses an OpenMP context property.
3155  void parseOMPContextProperty(OMPTraitSelector &TISelector,
3156                               llvm::omp::TraitSet Set,
3157                               llvm::StringMap<SourceLocation> &Seen);
3158
3159  /// Parses an OpenMP context selector.
3160  void parseOMPContextSelector(OMPTraitSelector &TISelector,
3161                               llvm::omp::TraitSet Set,
3162                               llvm::StringMap<SourceLocation> &SeenSelectors);
3163
3164  /// Parses an OpenMP context selector set.
3165  void parseOMPContextSelectorSet(OMPTraitSet &TISet,
3166                                  llvm::StringMap<SourceLocation> &SeenSets);
3167
3168  /// Parses OpenMP context selectors.
3169  bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
3170
3171  /// Parse a `match` clause for an '#pragma omp declare variant'. Return true
3172  /// if there was an error.
3173  bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
3174                                         OMPTraitInfo *ParentTI);
3175
3176  /// Parse clauses for '#pragma omp declare variant'.
3177  void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
3178                                     SourceLocation Loc);
3179
3180  /// Parse 'omp [begin] assume[s]' directive.
3181  void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
3182                                   SourceLocation Loc);
3183
3184  /// Parse 'omp end assumes' directive.
3185  void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
3186
3187  /// Parse clauses for '#pragma omp [begin] declare target'.
3188  void ParseOMPDeclareTargetClauses(Sema::DeclareTargetContextInfo &DTCI);
3189
3190  /// Parse '#pragma omp end declare target'.
3191  void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
3192                                         OpenMPDirectiveKind EndDKind,
3193                                         SourceLocation Loc);
3194
3195  /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
3196  /// it is not the current token.
3197  void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
3198
3199  /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
3200  /// that the "end" matching the "begin" directive of kind \p BeginKind was not
3201  /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
3202  /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
3203  void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
3204                            OpenMPDirectiveKind ExpectedKind,
3205                            OpenMPDirectiveKind FoundKind,
3206                            SourceLocation MatchingLoc,
3207                            SourceLocation FoundLoc,
3208                            bool SkipUntilOpenMPEnd);
3209
3210  /// Parses declarative OpenMP directives.
3211  DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
3212      AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
3213      bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified,
3214      Decl *TagDecl = nullptr);
3215  /// Parse 'omp declare reduction' construct.
3216  DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS);
3217  /// Parses initializer for provided omp_priv declaration inside the reduction
3218  /// initializer.
3219  void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm);
3220
3221  /// Parses 'omp declare mapper' directive.
3222  DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS);
3223  /// Parses variable declaration in 'omp declare mapper' directive.
3224  TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
3225                                             DeclarationName &Name,
3226                                             AccessSpecifier AS = AS_none);
3227
3228  /// Tries to parse cast part of OpenMP array shaping operation:
3229  /// '[' expression ']' { '[' expression ']' } ')'.
3230  bool tryParseOpenMPArrayShapingCastPart();
3231
3232  /// Parses simple list of variables.
3233  ///
3234  /// \param Kind Kind of the directive.
3235  /// \param Callback Callback function to be called for the list elements.
3236  /// \param AllowScopeSpecifier true, if the variables can have fully
3237  /// qualified names.
3238  ///
3239  bool ParseOpenMPSimpleVarList(
3240      OpenMPDirectiveKind Kind,
3241      const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
3242          Callback,
3243      bool AllowScopeSpecifier);
3244  /// Parses declarative or executable directive.
3245  ///
3246  /// \param StmtCtx The context in which we're parsing the directive.
3247  StmtResult
3248  ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx);
3249  /// Parses clause of kind \a CKind for directive of a kind \a Kind.
3250  ///
3251  /// \param DKind Kind of current directive.
3252  /// \param CKind Kind of current clause.
3253  /// \param FirstClause true, if this is the first clause of a kind \a CKind
3254  /// in current directive.
3255  ///
3256  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
3257                               OpenMPClauseKind CKind, bool FirstClause);
3258  /// Parses clause with a single expression of a kind \a Kind.
3259  ///
3260  /// \param Kind Kind of current clause.
3261  /// \param ParseOnly true to skip the clause's semantic actions and return
3262  /// nullptr.
3263  ///
3264  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3265                                         bool ParseOnly);
3266  /// Parses simple clause of a kind \a Kind.
3267  ///
3268  /// \param Kind Kind of current clause.
3269  /// \param ParseOnly true to skip the clause's semantic actions and return
3270  /// nullptr.
3271  ///
3272  OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
3273  /// Parses clause with a single expression and an additional argument
3274  /// of a kind \a Kind.
3275  ///
3276  /// \param DKind Directive kind.
3277  /// \param Kind Kind of current clause.
3278  /// \param ParseOnly true to skip the clause's semantic actions and return
3279  /// nullptr.
3280  ///
3281  OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3282                                                OpenMPClauseKind Kind,
3283                                                bool ParseOnly);
3284
3285  /// Parses the 'sizes' clause of a '#pragma omp tile' directive.
3286  OMPClause *ParseOpenMPSizesClause();
3287
3288  /// Parses clause without any additional arguments.
3289  ///
3290  /// \param Kind Kind of current clause.
3291  /// \param ParseOnly true to skip the clause's semantic actions and return
3292  /// nullptr.
3293  ///
3294  OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false);
3295  /// Parses clause with the list of variables of a kind \a Kind.
3296  ///
3297  /// \param Kind Kind of current clause.
3298  /// \param ParseOnly true to skip the clause's semantic actions and return
3299  /// nullptr.
3300  ///
3301  OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
3302                                      OpenMPClauseKind Kind, bool ParseOnly);
3303
3304  /// Parses and creates OpenMP 5.0 iterators expression:
3305  /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
3306  /// <range-specification> }+ ')'
3307  ExprResult ParseOpenMPIteratorsExpr();
3308
3309  /// Parses allocators and traits in the context of the uses_allocator clause.
3310  /// Expected format:
3311  /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
3312  OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
3313
3314  /// Parses clause with an interop variable of kind \a Kind.
3315  ///
3316  /// \param Kind Kind of current clause.
3317  /// \param ParseOnly true to skip the clause's semantic actions and return
3318  /// nullptr.
3319  //
3320  OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly);
3321
3322public:
3323  /// Parses simple expression in parens for single-expression clauses of OpenMP
3324  /// constructs.
3325  /// \param RLoc Returned location of right paren.
3326  ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc,
3327                                   bool IsAddressOfOperand = false);
3328
3329  /// Data used for parsing list of variables in OpenMP clauses.
3330  struct OpenMPVarListDataTy {
3331    Expr *DepModOrTailExpr = nullptr;
3332    SourceLocation ColonLoc;
3333    SourceLocation RLoc;
3334    CXXScopeSpec ReductionOrMapperIdScopeSpec;
3335    DeclarationNameInfo ReductionOrMapperId;
3336    int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
3337                            ///< lastprivate clause.
3338    SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3339    MapTypeModifiers;
3340    SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
3341    MapTypeModifiersLoc;
3342    SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
3343        MotionModifiers;
3344    SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
3345    bool IsMapTypeImplicit = false;
3346    SourceLocation ExtraModifierLoc;
3347  };
3348
3349  /// Parses clauses with list.
3350  bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
3351                          SmallVectorImpl<Expr *> &Vars,
3352                          OpenMPVarListDataTy &Data);
3353  bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
3354                          bool ObjectHadErrors, bool EnteringContext,
3355                          bool AllowDestructorName, bool AllowConstructorName,
3356                          bool AllowDeductionGuide,
3357                          SourceLocation *TemplateKWLoc, UnqualifiedId &Result);
3358
3359  /// Parses the mapper modifier in map, to, and from clauses.
3360  bool parseMapperModifier(OpenMPVarListDataTy &Data);
3361  /// Parses map-type-modifiers in map clause.
3362  /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
3363  /// where, map-type-modifier ::= always | close | mapper(mapper-identifier)
3364  bool parseMapTypeModifiers(OpenMPVarListDataTy &Data);
3365
3366private:
3367  //===--------------------------------------------------------------------===//
3368  // C++ 14: Templates [temp]
3369
3370  // C++ 14.1: Template Parameters [temp.param]
3371  Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context,
3372                                             SourceLocation &DeclEnd,
3373                                             ParsedAttributes &AccessAttrs,
3374                                             AccessSpecifier AS = AS_none);
3375  Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context,
3376                                                 SourceLocation &DeclEnd,
3377                                                 ParsedAttributes &AccessAttrs,
3378                                                 AccessSpecifier AS);
3379  Decl *ParseSingleDeclarationAfterTemplate(
3380      DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
3381      ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd,
3382      ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none);
3383  bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth,
3384                               SmallVectorImpl<NamedDecl *> &TemplateParams,
3385                               SourceLocation &LAngleLoc,
3386                               SourceLocation &RAngleLoc);
3387  bool ParseTemplateParameterList(unsigned Depth,
3388                                  SmallVectorImpl<NamedDecl*> &TemplateParams);
3389  TPResult isStartOfTemplateTypeParameter();
3390  NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position);
3391  NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position);
3392  NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
3393  NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
3394  bool isTypeConstraintAnnotation();
3395  bool TryAnnotateTypeConstraint();
3396  void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
3397                                 SourceLocation CorrectLoc,
3398                                 bool AlreadyHasEllipsis,
3399                                 bool IdentifierHasName);
3400  void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
3401                                             Declarator &D);
3402  // C++ 14.3: Template arguments [temp.arg]
3403  typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
3404
3405  bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
3406                                      SourceLocation &RAngleLoc,
3407                                      bool ConsumeLastToken,
3408                                      bool ObjCGenericList);
3409  bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
3410                                        SourceLocation &LAngleLoc,
3411                                        TemplateArgList &TemplateArgs,
3412                                        SourceLocation &RAngleLoc);
3413
3414  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
3415                               CXXScopeSpec &SS,
3416                               SourceLocation TemplateKWLoc,
3417                               UnqualifiedId &TemplateName,
3418                               bool AllowTypeAnnotation = true,
3419                               bool TypeConstraint = false);
3420  void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
3421                                     bool IsClassName = false);
3422  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
3423  ParsedTemplateArgument ParseTemplateTemplateArgument();
3424  ParsedTemplateArgument ParseTemplateArgument();
3425  Decl *ParseExplicitInstantiation(DeclaratorContext Context,
3426                                   SourceLocation ExternLoc,
3427                                   SourceLocation TemplateLoc,
3428                                   SourceLocation &DeclEnd,
3429                                   ParsedAttributes &AccessAttrs,
3430                                   AccessSpecifier AS = AS_none);
3431  // C++2a: Template, concept definition [temp]
3432  Decl *
3433  ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
3434                         SourceLocation &DeclEnd);
3435
3436  //===--------------------------------------------------------------------===//
3437  // Modules
3438  DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl);
3439  Decl *ParseModuleImport(SourceLocation AtLoc);
3440  bool parseMisplacedModuleImport();
3441  bool tryParseMisplacedModuleImport() {
3442    tok::TokenKind Kind = Tok.getKind();
3443    if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
3444        Kind == tok::annot_module_include)
3445      return parseMisplacedModuleImport();
3446    return false;
3447  }
3448
3449  bool ParseModuleName(
3450      SourceLocation UseLoc,
3451      SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
3452      bool IsImport);
3453
3454  //===--------------------------------------------------------------------===//
3455  // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
3456  ExprResult ParseTypeTrait();
3457
3458  //===--------------------------------------------------------------------===//
3459  // Embarcadero: Arary and Expression Traits
3460  ExprResult ParseArrayTypeTrait();
3461  ExprResult ParseExpressionTrait();
3462
3463  //===--------------------------------------------------------------------===//
3464  // Preprocessor code-completion pass-through
3465  void CodeCompleteDirective(bool InConditional) override;
3466  void CodeCompleteInConditionalExclusion() override;
3467  void CodeCompleteMacroName(bool IsDefinition) override;
3468  void CodeCompletePreprocessorExpression() override;
3469  void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
3470                                 unsigned ArgumentIndex) override;
3471  void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override;
3472  void CodeCompleteNaturalLanguage() override;
3473
3474  class GNUAsmQualifiers {
3475    unsigned Qualifiers = AQ_unspecified;
3476
3477  public:
3478    enum AQ {
3479      AQ_unspecified = 0,
3480      AQ_volatile    = 1,
3481      AQ_inline      = 2,
3482      AQ_goto        = 4,
3483    };
3484    static const char *getQualifierName(AQ Qualifier);
3485    bool setAsmQualifier(AQ Qualifier);
3486    inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
3487    inline bool isInline() const { return Qualifiers & AQ_inline; };
3488    inline bool isGoto() const { return Qualifiers & AQ_goto; }
3489  };
3490  bool isGCCAsmStatement(const Token &TokAfterAsm) const;
3491  bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
3492  GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
3493  bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
3494};
3495
3496}  // end namespace clang
3497
3498#endif
3499