1193326Sed//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file defines the Parser interface.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#ifndef LLVM_CLANG_PARSE_PARSER_H
15193326Sed#define LLVM_CLANG_PARSE_PARSER_H
16193326Sed
17249423Sdim#include "clang/Basic/OpenMPKinds.h"
18249423Sdim#include "clang/Basic/OperatorPrecedence.h"
19202879Srdivacky#include "clang/Basic/Specifiers.h"
20249423Sdim#include "clang/Lex/CodeCompletionHandler.h"
21193326Sed#include "clang/Lex/Preprocessor.h"
22249423Sdim#include "clang/Sema/DeclSpec.h"
23276479Sdim#include "clang/Sema/LoopHint.h"
24212904Sdim#include "clang/Sema/Sema.h"
25226633Sdim#include "llvm/ADT/SmallVector.h"
26234353Sdim#include "llvm/Support/Compiler.h"
27234353Sdim#include "llvm/Support/PrettyStackTrace.h"
28239462Sdim#include "llvm/Support/SaveAndRestore.h"
29276479Sdim#include <memory>
30193326Sed#include <stack>
31193326Sed
32193326Sednamespace clang {
33193326Sed  class PragmaHandler;
34193326Sed  class Scope;
35239462Sdim  class BalancedDelimiterTracker;
36243830Sdim  class CorrectionCandidateCallback;
37212904Sdim  class DeclGroupRef;
38193326Sed  class DiagnosticBuilder;
39193326Sed  class Parser;
40239462Sdim  class ParsingDeclRAIIObject;
41239462Sdim  class ParsingDeclSpec;
42239462Sdim  class ParsingDeclarator;
43239462Sdim  class ParsingFieldDeclarator;
44200583Srdivacky  class ColonProtectionRAIIObject;
45218893Sdim  class InMessageExpressionRAIIObject;
46221345Sdim  class PoisonSEHIdentifiersRAIIObject;
47221345Sdim  class VersionTuple;
48261991Sdim  class OMPClause;
49288943Sdim  class ObjCTypeParamList;
50288943Sdim  class ObjCTypeParameter;
51234353Sdim
52193326Sed/// Parser - This implements a parser for the C family of languages.  After
53193326Sed/// parsing units of the grammar, productions are invoked to handle whatever has
54193326Sed/// been read.
55193326Sed///
56212904Sdimclass Parser : public CodeCompletionHandler {
57200583Srdivacky  friend class ColonProtectionRAIIObject;
58218893Sdim  friend class InMessageExpressionRAIIObject;
59221345Sdim  friend class PoisonSEHIdentifiersRAIIObject;
60239462Sdim  friend class ObjCDeclContextSwitch;
61210299Sed  friend class ParenBraceBracketBalancer;
62239462Sdim  friend class BalancedDelimiterTracker;
63198092Srdivacky
64193326Sed  Preprocessor &PP;
65198092Srdivacky
66193326Sed  /// Tok - The current token we are peeking ahead.  All parsing methods assume
67193326Sed  /// that this is valid.
68193326Sed  Token Tok;
69198092Srdivacky
70193326Sed  // PrevTokLocation - The location of the token we previously
71193326Sed  // consumed. This token is used for diagnostics where we expected to
72193326Sed  // see a token following another token (e.g., the ';' at the end of
73193326Sed  // a statement).
74193326Sed  SourceLocation PrevTokLocation;
75193326Sed
76193326Sed  unsigned short ParenCount, BracketCount, BraceCount;
77276479Sdim
78193326Sed  /// Actions - These are the callbacks we invoke as we parse various constructs
79234353Sdim  /// in the file.
80212904Sdim  Sema &Actions;
81198092Srdivacky
82226633Sdim  DiagnosticsEngine &Diags;
83198092Srdivacky
84193326Sed  /// ScopeCache - Cache scopes to reduce malloc traffic.
85193326Sed  enum { ScopeCacheSize = 16 };
86193326Sed  unsigned NumCachedScopes;
87193326Sed  Scope *ScopeCache[ScopeCacheSize];
88193326Sed
89221345Sdim  /// Identifiers used for SEH handling in Borland. These are only
90221345Sdim  /// allowed in particular circumstances
91234353Sdim  // __except block
92234353Sdim  IdentifierInfo *Ident__exception_code,
93234353Sdim                 *Ident___exception_code,
94234353Sdim                 *Ident_GetExceptionCode;
95234353Sdim  // __except filter expression
96234353Sdim  IdentifierInfo *Ident__exception_info,
97234353Sdim                 *Ident___exception_info,
98234353Sdim                 *Ident_GetExceptionInfo;
99234353Sdim  // __finally
100234353Sdim  IdentifierInfo *Ident__abnormal_termination,
101234353Sdim                 *Ident___abnormal_termination,
102234353Sdim                 *Ident_AbnormalTermination;
103221345Sdim
104234353Sdim  /// Contextual keywords for Microsoft extensions.
105234353Sdim  IdentifierInfo *Ident__except;
106261991Sdim  mutable IdentifierInfo *Ident_sealed;
107234353Sdim
108193326Sed  /// Ident_super - IdentifierInfo for "super", to support fast
109193326Sed  /// comparison.
110193326Sed  IdentifierInfo *Ident_super;
111288943Sdim  /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and
112288943Sdim  /// "bool" fast comparison.  Only present if AltiVec or ZVector are enabled.
113203955Srdivacky  IdentifierInfo *Ident_vector;
114288943Sdim  IdentifierInfo *Ident_bool;
115288943Sdim  /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison.
116288943Sdim  /// Only present if AltiVec enabled.
117203955Srdivacky  IdentifierInfo *Ident_pixel;
118193326Sed
119226633Sdim  /// Objective-C contextual keywords.
120226633Sdim  mutable IdentifierInfo *Ident_instancetype;
121234353Sdim
122221345Sdim  /// \brief Identifier for "introduced".
123221345Sdim  IdentifierInfo *Ident_introduced;
124221345Sdim
125221345Sdim  /// \brief Identifier for "deprecated".
126221345Sdim  IdentifierInfo *Ident_deprecated;
127221345Sdim
128221345Sdim  /// \brief Identifier for "obsoleted".
129221345Sdim  IdentifierInfo *Ident_obsoleted;
130221345Sdim
131221345Sdim  /// \brief Identifier for "unavailable".
132221345Sdim  IdentifierInfo *Ident_unavailable;
133234353Sdim
134234353Sdim  /// \brief Identifier for "message".
135234353Sdim  IdentifierInfo *Ident_message;
136221345Sdim
137234353Sdim  /// C++0x contextual keywords.
138218893Sdim  mutable IdentifierInfo *Ident_final;
139218893Sdim  mutable IdentifierInfo *Ident_override;
140218893Sdim
141280031Sdim  // C++ type trait keywords that can be reverted to identifiers and still be
142280031Sdim  // used as type traits.
143280031Sdim  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
144243830Sdim
145276479Sdim  std::unique_ptr<PragmaHandler> AlignHandler;
146276479Sdim  std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
147276479Sdim  std::unique_ptr<PragmaHandler> OptionsHandler;
148276479Sdim  std::unique_ptr<PragmaHandler> PackHandler;
149276479Sdim  std::unique_ptr<PragmaHandler> MSStructHandler;
150276479Sdim  std::unique_ptr<PragmaHandler> UnusedHandler;
151276479Sdim  std::unique_ptr<PragmaHandler> WeakHandler;
152276479Sdim  std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
153276479Sdim  std::unique_ptr<PragmaHandler> FPContractHandler;
154276479Sdim  std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
155276479Sdim  std::unique_ptr<PragmaHandler> OpenMPHandler;
156276479Sdim  std::unique_ptr<PragmaHandler> MSCommentHandler;
157276479Sdim  std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
158276479Sdim  std::unique_ptr<PragmaHandler> MSPointersToMembers;
159276479Sdim  std::unique_ptr<PragmaHandler> MSVtorDisp;
160276479Sdim  std::unique_ptr<PragmaHandler> MSInitSeg;
161276479Sdim  std::unique_ptr<PragmaHandler> MSDataSeg;
162276479Sdim  std::unique_ptr<PragmaHandler> MSBSSSeg;
163276479Sdim  std::unique_ptr<PragmaHandler> MSConstSeg;
164276479Sdim  std::unique_ptr<PragmaHandler> MSCodeSeg;
165276479Sdim  std::unique_ptr<PragmaHandler> MSSection;
166296417Sdim  std::unique_ptr<PragmaHandler> MSRuntimeChecks;
167276479Sdim  std::unique_ptr<PragmaHandler> OptimizeHandler;
168276479Sdim  std::unique_ptr<PragmaHandler> LoopHintHandler;
169276479Sdim  std::unique_ptr<PragmaHandler> UnrollHintHandler;
170280031Sdim  std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
171198092Srdivacky
172276479Sdim  std::unique_ptr<CommentHandler> CommentSemaHandler;
173276479Sdim
174193326Sed  /// Whether the '>' token acts as an operator or not. This will be
175193326Sed  /// true except when we are parsing an expression within a C++
176193326Sed  /// template argument list, where the '>' closes the template
177193326Sed  /// argument list.
178193326Sed  bool GreaterThanIsOperator;
179234353Sdim
180200583Srdivacky  /// ColonIsSacred - When this is false, we aggressively try to recover from
181200583Srdivacky  /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
182200583Srdivacky  /// safe in case statements and a few other things.  This is managed by the
183200583Srdivacky  /// ColonProtectionRAIIObject RAII object.
184200583Srdivacky  bool ColonIsSacred;
185193326Sed
186276479Sdim  /// \brief When true, we are directly inside an Objective-C message
187218893Sdim  /// send expression.
188218893Sdim  ///
189218893Sdim  /// This is managed by the \c InMessageExpressionRAIIObject class, and
190218893Sdim  /// should not be set directly.
191218893Sdim  bool InMessageExpression;
192234353Sdim
193198092Srdivacky  /// The "depth" of the template parameters currently being parsed.
194198092Srdivacky  unsigned TemplateParameterDepth;
195234353Sdim
196251662Sdim  /// \brief RAII class that manages the template parameter depth.
197251662Sdim  class TemplateParameterDepthRAII {
198251662Sdim    unsigned &Depth;
199251662Sdim    unsigned AddedLevels;
200251662Sdim  public:
201251662Sdim    explicit TemplateParameterDepthRAII(unsigned &Depth)
202251662Sdim      : Depth(Depth), AddedLevels(0) {}
203251662Sdim
204251662Sdim    ~TemplateParameterDepthRAII() {
205251662Sdim      Depth -= AddedLevels;
206251662Sdim    }
207251662Sdim
208251662Sdim    void operator++() {
209251662Sdim      ++Depth;
210251662Sdim      ++AddedLevels;
211251662Sdim    }
212276479Sdim    void addDepth(unsigned D) {
213276479Sdim      Depth += D;
214276479Sdim      AddedLevels += D;
215276479Sdim    }
216251662Sdim    unsigned getDepth() const { return Depth; }
217251662Sdim  };
218251662Sdim
219218893Sdim  /// Factory object for creating AttributeList objects.
220221345Sdim  AttributeFactory AttrFactory;
221198092Srdivacky
222234982Sdim  /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
223234982Sdim  /// top-level declaration is finished.
224234982Sdim  SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
225224145Sdim
226243830Sdim  /// \brief Identifiers which have been declared within a tentative parse.
227243830Sdim  SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
228243830Sdim
229234353Sdim  IdentifierInfo *getSEHExceptKeyword();
230234353Sdim
231239462Sdim  /// True if we are within an Objective-C container while parsing C-like decls.
232239462Sdim  ///
233239462Sdim  /// This is necessary because Sema thinks we have left the container
234239462Sdim  /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
235239462Sdim  /// be NULL.
236239462Sdim  bool ParsingInObjCContainer;
237239462Sdim
238234353Sdim  bool SkipFunctionBodies;
239234353Sdim
240193326Sedpublic:
241234353Sdim  Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
242288943Sdim  ~Parser() override;
243193326Sed
244234353Sdim  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
245199482Srdivacky  const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
246193326Sed  Preprocessor &getPreprocessor() const { return PP; }
247212904Sdim  Sema &getActions() const { return Actions; }
248239462Sdim  AttributeFactory &getAttrFactory() { return AttrFactory; }
249198092Srdivacky
250193326Sed  const Token &getCurToken() const { return Tok; }
251210299Sed  Scope *getCurScope() const { return Actions.getCurScope(); }
252288943Sdim  void incrementMSManglingNumber() const {
253288943Sdim    return Actions.incrementMSManglingNumber();
254276479Sdim  }
255234353Sdim
256226633Sdim  Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
257234353Sdim
258193326Sed  // Type forwarding.  All of these are statically 'void*', but they may all be
259193326Sed  // different actual classes based on the actions in place.
260212904Sdim  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
261212904Sdim  typedef OpaquePtr<TemplateName> TemplateTy;
262193326Sed
263226633Sdim  typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
264193326Sed
265212904Sdim  typedef Sema::FullExprArg FullExprArg;
266193326Sed
267193326Sed  // Parsing methods.
268198092Srdivacky
269193326Sed  /// Initialize - Warm up the parser.
270193326Sed  ///
271193326Sed  void Initialize();
272198092Srdivacky
273198092Srdivacky  /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
274193326Sed  /// the EOF was encountered.
275193326Sed  bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
276276479Sdim  bool ParseTopLevelDecl() {
277276479Sdim    DeclGroupPtrTy Result;
278276479Sdim    return ParseTopLevelDecl(Result);
279276479Sdim  }
280198092Srdivacky
281243830Sdim  /// ConsumeToken - Consume the current 'peek token' and lex the next one.
282276479Sdim  /// This does not work with special tokens: string literals, code completion
283276479Sdim  /// and balanced tokens must be handled using the specific consume methods.
284276479Sdim  /// Returns the location of the consumed token.
285276479Sdim  SourceLocation ConsumeToken() {
286276479Sdim    assert(!isTokenSpecial() &&
287243830Sdim           "Should consume special tokens with Consume*Token");
288243830Sdim    PrevTokLocation = Tok.getLocation();
289243830Sdim    PP.Lex(Tok);
290243830Sdim    return PrevTokLocation;
291243830Sdim  }
292243830Sdim
293276479Sdim  bool TryConsumeToken(tok::TokenKind Expected) {
294276479Sdim    if (Tok.isNot(Expected))
295276479Sdim      return false;
296276479Sdim    assert(!isTokenSpecial() &&
297276479Sdim           "Should consume special tokens with Consume*Token");
298276479Sdim    PrevTokLocation = Tok.getLocation();
299276479Sdim    PP.Lex(Tok);
300276479Sdim    return true;
301276479Sdim  }
302276479Sdim
303276479Sdim  bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) {
304276479Sdim    if (!TryConsumeToken(Expected))
305276479Sdim      return false;
306276479Sdim    Loc = PrevTokLocation;
307276479Sdim    return true;
308276479Sdim  }
309276479Sdim
310288943Sdim  /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds
311288943Sdim  /// to the given nullability kind.
312288943Sdim  IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) {
313288943Sdim    return Actions.getNullabilityKeyword(nullability);
314288943Sdim  }
315288943Sdim
316193326Sedprivate:
317193326Sed  //===--------------------------------------------------------------------===//
318193326Sed  // Low-Level token peeking and consumption methods.
319193326Sed  //
320198092Srdivacky
321193326Sed  /// isTokenParen - Return true if the cur token is '(' or ')'.
322193326Sed  bool isTokenParen() const {
323193326Sed    return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
324193326Sed  }
325193326Sed  /// isTokenBracket - Return true if the cur token is '[' or ']'.
326193326Sed  bool isTokenBracket() const {
327193326Sed    return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
328193326Sed  }
329193326Sed  /// isTokenBrace - Return true if the cur token is '{' or '}'.
330193326Sed  bool isTokenBrace() const {
331193326Sed    return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
332193326Sed  }
333193326Sed  /// isTokenStringLiteral - True if this token is a string-literal.
334193326Sed  bool isTokenStringLiteral() const {
335249423Sdim    return tok::isStringLiteral(Tok.getKind());
336193326Sed  }
337276479Sdim  /// isTokenSpecial - True if this token requires special consumption methods.
338276479Sdim  bool isTokenSpecial() const {
339276479Sdim    return isTokenStringLiteral() || isTokenParen() || isTokenBracket() ||
340276479Sdim           isTokenBrace() || Tok.is(tok::code_completion);
341276479Sdim  }
342193326Sed
343234353Sdim  /// \brief Returns true if the current token is '=' or is a type of '='.
344234353Sdim  /// For typos, give a fixit to '='
345234353Sdim  bool isTokenEqualOrEqualTypo();
346218893Sdim
347280031Sdim  /// \brief Return the current token to the token stream and make the given
348280031Sdim  /// token the current token.
349280031Sdim  void UnconsumeToken(Token &Consumed) {
350280031Sdim      Token Next = Tok;
351280031Sdim      PP.EnterToken(Consumed);
352280031Sdim      PP.Lex(Tok);
353280031Sdim      PP.EnterToken(Next);
354280031Sdim  }
355280031Sdim
356193326Sed  /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
357193326Sed  /// current token type.  This should only be used in cases where the type of
358193326Sed  /// the token really isn't known, e.g. in error recovery.
359249423Sdim  SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
360193326Sed    if (isTokenParen())
361193326Sed      return ConsumeParen();
362276479Sdim    if (isTokenBracket())
363193326Sed      return ConsumeBracket();
364276479Sdim    if (isTokenBrace())
365193326Sed      return ConsumeBrace();
366276479Sdim    if (isTokenStringLiteral())
367193326Sed      return ConsumeStringToken();
368276479Sdim    if (Tok.is(tok::code_completion))
369276479Sdim      return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken()
370276479Sdim                                      : handleUnexpectedCodeCompletionToken();
371276479Sdim    return ConsumeToken();
372193326Sed  }
373198092Srdivacky
374193326Sed  /// ConsumeParen - This consume method keeps the paren count up-to-date.
375193326Sed  ///
376193326Sed  SourceLocation ConsumeParen() {
377193326Sed    assert(isTokenParen() && "wrong consume method");
378193326Sed    if (Tok.getKind() == tok::l_paren)
379193326Sed      ++ParenCount;
380193326Sed    else if (ParenCount)
381193326Sed      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
382193326Sed    PrevTokLocation = Tok.getLocation();
383193326Sed    PP.Lex(Tok);
384193326Sed    return PrevTokLocation;
385193326Sed  }
386198092Srdivacky
387193326Sed  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
388193326Sed  ///
389193326Sed  SourceLocation ConsumeBracket() {
390193326Sed    assert(isTokenBracket() && "wrong consume method");
391193326Sed    if (Tok.getKind() == tok::l_square)
392193326Sed      ++BracketCount;
393193326Sed    else if (BracketCount)
394193326Sed      --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
395198092Srdivacky
396193326Sed    PrevTokLocation = Tok.getLocation();
397193326Sed    PP.Lex(Tok);
398193326Sed    return PrevTokLocation;
399193326Sed  }
400198092Srdivacky
401193326Sed  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
402193326Sed  ///
403193326Sed  SourceLocation ConsumeBrace() {
404193326Sed    assert(isTokenBrace() && "wrong consume method");
405193326Sed    if (Tok.getKind() == tok::l_brace)
406193326Sed      ++BraceCount;
407193326Sed    else if (BraceCount)
408193326Sed      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
409198092Srdivacky
410193326Sed    PrevTokLocation = Tok.getLocation();
411193326Sed    PP.Lex(Tok);
412193326Sed    return PrevTokLocation;
413193326Sed  }
414198092Srdivacky
415193326Sed  /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
416193326Sed  /// and returning the token kind.  This method is specific to strings, as it
417193326Sed  /// handles string literal concatenation, as per C99 5.1.1.2, translation
418193326Sed  /// phase #6.
419193326Sed  SourceLocation ConsumeStringToken() {
420193326Sed    assert(isTokenStringLiteral() &&
421193326Sed           "Should only consume string literals with this method");
422193326Sed    PrevTokLocation = Tok.getLocation();
423193326Sed    PP.Lex(Tok);
424193326Sed    return PrevTokLocation;
425193326Sed  }
426198092Srdivacky
427208600Srdivacky  /// \brief Consume the current code-completion token.
428208600Srdivacky  ///
429276479Sdim  /// This routine can be called to consume the code-completion token and
430276479Sdim  /// continue processing in special cases where \c cutOffParsing() isn't
431276479Sdim  /// desired, such as token caching or completion with lookahead.
432208600Srdivacky  SourceLocation ConsumeCodeCompletionToken() {
433208600Srdivacky    assert(Tok.is(tok::code_completion));
434208600Srdivacky    PrevTokLocation = Tok.getLocation();
435208600Srdivacky    PP.Lex(Tok);
436234353Sdim    return PrevTokLocation;
437208600Srdivacky  }
438234353Sdim
439226633Sdim  ///\ brief When we are consuming a code-completion token without having
440208600Srdivacky  /// matched specific position in the grammar, provide code-completion results
441208600Srdivacky  /// based on context.
442226633Sdim  ///
443226633Sdim  /// \returns the source location of the code-completion token.
444226633Sdim  SourceLocation handleUnexpectedCodeCompletionToken();
445208600Srdivacky
446226633Sdim  /// \brief Abruptly cut off parsing; mainly used when we have reached the
447226633Sdim  /// code-completion point.
448226633Sdim  void cutOffParsing() {
449261991Sdim    if (PP.isCodeCompletionEnabled())
450261991Sdim      PP.setCodeCompletionReached();
451226633Sdim    // Cut off parsing by acting as if we reached the end-of-file.
452226633Sdim    Tok.setKind(tok::eof);
453226633Sdim  }
454226633Sdim
455276479Sdim  /// \brief Determine if we're at the end of the file or at a transition
456276479Sdim  /// between modules.
457276479Sdim  bool isEofOrEom() {
458276479Sdim    tok::TokenKind Kind = Tok.getKind();
459276479Sdim    return Kind == tok::eof || Kind == tok::annot_module_begin ||
460276479Sdim           Kind == tok::annot_module_end || Kind == tok::annot_module_include;
461276479Sdim  }
462276479Sdim
463276479Sdim  /// \brief Initialize all pragma handlers.
464276479Sdim  void initializePragmaHandlers();
465276479Sdim
466276479Sdim  /// \brief Destroy and reset all pragma handlers.
467276479Sdim  void resetPragmaHandlers();
468276479Sdim
469218893Sdim  /// \brief Handle the annotation token produced for #pragma unused(...)
470218893Sdim  void HandlePragmaUnused();
471218893Sdim
472234353Sdim  /// \brief Handle the annotation token produced for
473234353Sdim  /// #pragma GCC visibility...
474234353Sdim  void HandlePragmaVisibility();
475234353Sdim
476234353Sdim  /// \brief Handle the annotation token produced for
477234353Sdim  /// #pragma pack...
478234353Sdim  void HandlePragmaPack();
479234353Sdim
480243830Sdim  /// \brief Handle the annotation token produced for
481243830Sdim  /// #pragma ms_struct...
482243830Sdim  void HandlePragmaMSStruct();
483243830Sdim
484243830Sdim  /// \brief Handle the annotation token produced for
485261991Sdim  /// #pragma comment...
486261991Sdim  void HandlePragmaMSComment();
487261991Sdim
488276479Sdim  void HandlePragmaMSPointersToMembers();
489276479Sdim
490276479Sdim  void HandlePragmaMSVtorDisp();
491276479Sdim
492276479Sdim  void HandlePragmaMSPragma();
493276479Sdim  bool HandlePragmaMSSection(StringRef PragmaName,
494276479Sdim                             SourceLocation PragmaLocation);
495276479Sdim  bool HandlePragmaMSSegment(StringRef PragmaName,
496276479Sdim                             SourceLocation PragmaLocation);
497276479Sdim  bool HandlePragmaMSInitSeg(StringRef PragmaName,
498276479Sdim                             SourceLocation PragmaLocation);
499276479Sdim
500261991Sdim  /// \brief Handle the annotation token produced for
501243830Sdim  /// #pragma align...
502243830Sdim  void HandlePragmaAlign();
503243830Sdim
504243830Sdim  /// \brief Handle the annotation token produced for
505296417Sdim  /// #pragma clang __debug dump...
506296417Sdim  void HandlePragmaDump();
507296417Sdim
508296417Sdim  /// \brief Handle the annotation token produced for
509243830Sdim  /// #pragma weak id...
510243830Sdim  void HandlePragmaWeak();
511243830Sdim
512243830Sdim  /// \brief Handle the annotation token produced for
513243830Sdim  /// #pragma weak id = id...
514243830Sdim  void HandlePragmaWeakAlias();
515243830Sdim
516243830Sdim  /// \brief Handle the annotation token produced for
517243830Sdim  /// #pragma redefine_extname...
518243830Sdim  void HandlePragmaRedefineExtname();
519243830Sdim
520243830Sdim  /// \brief Handle the annotation token produced for
521243830Sdim  /// #pragma STDC FP_CONTRACT...
522243830Sdim  void HandlePragmaFPContract();
523243830Sdim
524243830Sdim  /// \brief Handle the annotation token produced for
525243830Sdim  /// #pragma OPENCL EXTENSION...
526243830Sdim  void HandlePragmaOpenCLExtension();
527243830Sdim
528251662Sdim  /// \brief Handle the annotation token produced for
529251662Sdim  /// #pragma clang __debug captured
530251662Sdim  StmtResult HandlePragmaCaptured();
531251662Sdim
532276479Sdim  /// \brief Handle the annotation token produced for
533276479Sdim  /// #pragma clang loop and #pragma unroll.
534280031Sdim  bool HandlePragmaLoopHint(LoopHint &Hint);
535276479Sdim
536193326Sed  /// GetLookAheadToken - This peeks ahead N tokens and returns that token
537193326Sed  /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
538193326Sed  /// returns the token after Tok, etc.
539193326Sed  ///
540193326Sed  /// Note that this differs from the Preprocessor's LookAhead method, because
541193326Sed  /// the Parser always has one token lexed that the preprocessor doesn't.
542193326Sed  ///
543193326Sed  const Token &GetLookAheadToken(unsigned N) {
544193326Sed    if (N == 0 || Tok.is(tok::eof)) return Tok;
545193326Sed    return PP.LookAhead(N-1);
546193326Sed  }
547193326Sed
548243830Sdimpublic:
549193326Sed  /// NextToken - This peeks ahead one token and returns it without
550193326Sed  /// consuming it.
551193326Sed  const Token &NextToken() {
552193326Sed    return PP.LookAhead(0);
553193326Sed  }
554193326Sed
555212904Sdim  /// getTypeAnnotation - Read a parsed type out of an annotation token.
556212904Sdim  static ParsedType getTypeAnnotation(Token &Tok) {
557212904Sdim    return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
558212904Sdim  }
559212904Sdim
560243830Sdimprivate:
561212904Sdim  static void setTypeAnnotation(Token &Tok, ParsedType T) {
562212904Sdim    Tok.setAnnotationValue(T.getAsOpaquePtr());
563212904Sdim  }
564234353Sdim
565221345Sdim  /// \brief Read an already-translated primary expression out of an annotation
566221345Sdim  /// token.
567221345Sdim  static ExprResult getExprAnnotation(Token &Tok) {
568251662Sdim    return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
569221345Sdim  }
570234353Sdim
571221345Sdim  /// \brief Set the primary expression corresponding to the given annotation
572221345Sdim  /// token.
573221345Sdim  static void setExprAnnotation(Token &Tok, ExprResult ER) {
574251662Sdim    Tok.setAnnotationValue(ER.getAsOpaquePointer());
575221345Sdim  }
576212904Sdim
577243830Sdimpublic:
578226633Sdim  // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
579226633Sdim  // find a type name by attempting typo correction.
580226633Sdim  bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
581226633Sdim                                   bool NeedType = false);
582243830Sdim  bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
583243830Sdim                                                 bool NeedType,
584243830Sdim                                                 CXXScopeSpec &SS,
585243830Sdim                                                 bool IsNewScope);
586198092Srdivacky  bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
587193326Sed
588243830Sdimprivate:
589243830Sdim  enum AnnotatedNameKind {
590243830Sdim    /// Annotation has failed and emitted an error.
591243830Sdim    ANK_Error,
592243830Sdim    /// The identifier is a tentatively-declared name.
593243830Sdim    ANK_TentativeDecl,
594243830Sdim    /// The identifier is a template name. FIXME: Add an annotation for that.
595243830Sdim    ANK_TemplateName,
596243830Sdim    /// The identifier can't be resolved.
597243830Sdim    ANK_Unresolved,
598243830Sdim    /// Annotation was successful.
599243830Sdim    ANK_Success
600243830Sdim  };
601280031Sdim  AnnotatedNameKind
602280031Sdim  TryAnnotateName(bool IsAddressOfOperand,
603280031Sdim                  std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
604243830Sdim
605243830Sdim  /// Push a tok::annot_cxxscope token onto the token stream.
606243830Sdim  void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
607243830Sdim
608203955Srdivacky  /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
609203955Srdivacky  /// replacing them with the non-context-sensitive keywords.  This returns
610203955Srdivacky  /// true if the token was replaced.
611203955Srdivacky  bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
612204643Srdivacky                       const char *&PrevSpec, unsigned &DiagID,
613204643Srdivacky                       bool &isInvalid) {
614288943Sdim    if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
615204643Srdivacky      return false;
616234353Sdim
617288943Sdim    if (Tok.getIdentifierInfo() != Ident_vector &&
618288943Sdim        Tok.getIdentifierInfo() != Ident_bool &&
619288943Sdim        (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
620288943Sdim      return false;
621288943Sdim
622204643Srdivacky    return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
623203955Srdivacky  }
624203955Srdivacky
625203955Srdivacky  /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
626203955Srdivacky  /// identifier token, replacing it with the non-context-sensitive __vector.
627203955Srdivacky  /// This returns true if the token was replaced.
628203955Srdivacky  bool TryAltiVecVectorToken() {
629288943Sdim    if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
630204643Srdivacky        Tok.getIdentifierInfo() != Ident_vector) return false;
631204643Srdivacky    return TryAltiVecVectorTokenOutOfLine();
632203955Srdivacky  }
633234353Sdim
634204643Srdivacky  bool TryAltiVecVectorTokenOutOfLine();
635204643Srdivacky  bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
636204643Srdivacky                                const char *&PrevSpec, unsigned &DiagID,
637204643Srdivacky                                bool &isInvalid);
638224145Sdim
639288943Sdim  /// Returns true if the current token is the identifier 'instancetype'.
640288943Sdim  ///
641288943Sdim  /// Should only be used in Objective-C language modes.
642288943Sdim  bool isObjCInstancetype() {
643288943Sdim    assert(getLangOpts().ObjC1);
644288943Sdim    if (!Ident_instancetype)
645288943Sdim      Ident_instancetype = PP.getIdentifierInfo("instancetype");
646288943Sdim    return Tok.getIdentifierInfo() == Ident_instancetype;
647288943Sdim  }
648288943Sdim
649261991Sdim  /// TryKeywordIdentFallback - For compatibility with system headers using
650261991Sdim  /// keywords as identifiers, attempt to convert the current token to an
651261991Sdim  /// identifier and optionally disable the keyword for the remainder of the
652261991Sdim  /// translation unit. This returns false if the token was not replaced,
653261991Sdim  /// otherwise emits a diagnostic and returns true.
654261991Sdim  bool TryKeywordIdentFallback(bool DisableKeyword);
655261991Sdim
656234982Sdim  /// \brief Get the TemplateIdAnnotation from the token.
657224145Sdim  TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
658224145Sdim
659193326Sed  /// TentativeParsingAction - An object that is used as a kind of "tentative
660193326Sed  /// parsing transaction". It gets instantiated to mark the token position and
661193326Sed  /// after the token consumption is done, Commit() or Revert() is called to
662193326Sed  /// either "commit the consumed tokens" or revert to the previously marked
663193326Sed  /// token position. Example:
664193326Sed  ///
665199482Srdivacky  ///   TentativeParsingAction TPA(*this);
666193326Sed  ///   ConsumeToken();
667193326Sed  ///   ....
668193326Sed  ///   TPA.Revert();
669193326Sed  ///
670193326Sed  class TentativeParsingAction {
671193326Sed    Parser &P;
672193326Sed    Token PrevTok;
673243830Sdim    size_t PrevTentativelyDeclaredIdentifierCount;
674235864Sdim    unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
675193326Sed    bool isActive;
676193326Sed
677193326Sed  public:
678193326Sed    explicit TentativeParsingAction(Parser& p) : P(p) {
679193326Sed      PrevTok = P.Tok;
680243830Sdim      PrevTentativelyDeclaredIdentifierCount =
681243830Sdim          P.TentativelyDeclaredIdentifiers.size();
682235864Sdim      PrevParenCount = P.ParenCount;
683235864Sdim      PrevBracketCount = P.BracketCount;
684235864Sdim      PrevBraceCount = P.BraceCount;
685193326Sed      P.PP.EnableBacktrackAtThisPos();
686193326Sed      isActive = true;
687193326Sed    }
688193326Sed    void Commit() {
689193326Sed      assert(isActive && "Parsing action was finished!");
690243830Sdim      P.TentativelyDeclaredIdentifiers.resize(
691243830Sdim          PrevTentativelyDeclaredIdentifierCount);
692193326Sed      P.PP.CommitBacktrackedTokens();
693193326Sed      isActive = false;
694193326Sed    }
695193326Sed    void Revert() {
696193326Sed      assert(isActive && "Parsing action was finished!");
697193326Sed      P.PP.Backtrack();
698193326Sed      P.Tok = PrevTok;
699243830Sdim      P.TentativelyDeclaredIdentifiers.resize(
700243830Sdim          PrevTentativelyDeclaredIdentifierCount);
701235864Sdim      P.ParenCount = PrevParenCount;
702235864Sdim      P.BracketCount = PrevBracketCount;
703235864Sdim      P.BraceCount = PrevBraceCount;
704193326Sed      isActive = false;
705193326Sed    }
706193326Sed    ~TentativeParsingAction() {
707193326Sed      assert(!isActive && "Forgot to call Commit or Revert!");
708193326Sed    }
709193326Sed  };
710261991Sdim  class UnannotatedTentativeParsingAction;
711198092Srdivacky
712226633Sdim  /// ObjCDeclContextSwitch - An object used to switch context from
713226633Sdim  /// an objective-c decl context to its enclosing decl context and
714226633Sdim  /// back.
715226633Sdim  class ObjCDeclContextSwitch {
716226633Sdim    Parser &P;
717226633Sdim    Decl *DC;
718239462Sdim    SaveAndRestore<bool> WithinObjCContainer;
719226633Sdim  public:
720239462Sdim    explicit ObjCDeclContextSwitch(Parser &p)
721239462Sdim      : P(p), DC(p.getObjCDeclContext()),
722276479Sdim        WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
723226633Sdim      if (DC)
724234353Sdim        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
725226633Sdim    }
726226633Sdim    ~ObjCDeclContextSwitch() {
727226633Sdim      if (DC)
728234353Sdim        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
729226633Sdim    }
730226633Sdim  };
731198092Srdivacky
732193326Sed  /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
733193326Sed  /// input.  If so, it is consumed and false is returned.
734193326Sed  ///
735276479Sdim  /// If a trivial punctuator misspelling is encountered, a FixIt error
736276479Sdim  /// diagnostic is issued and false is returned after recovery.
737276479Sdim  ///
738276479Sdim  /// If the input is malformed, this emits the specified diagnostic and true is
739193326Sed  /// returned.
740276479Sdim  bool ExpectAndConsume(tok::TokenKind ExpectedTok,
741276479Sdim                        unsigned Diag = diag::err_expected,
742276479Sdim                        StringRef DiagMsg = "");
743193326Sed
744218893Sdim  /// \brief The parser expects a semicolon and, if present, will consume it.
745218893Sdim  ///
746218893Sdim  /// If the next token is not a semicolon, this emits the specified diagnostic,
747218893Sdim  /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
748218893Sdim  /// to the semicolon, consumes that extra token.
749218893Sdim  bool ExpectAndConsumeSemi(unsigned DiagID);
750234353Sdim
751239462Sdim  /// \brief The kind of extra semi diagnostic to emit.
752239462Sdim  enum ExtraSemiKind {
753239462Sdim    OutsideFunction = 0,
754239462Sdim    InsideStruct = 1,
755239462Sdim    InstanceVariableList = 2,
756239462Sdim    AfterMemberFunctionDefinition = 3
757239462Sdim  };
758239462Sdim
759239462Sdim  /// \brief Consume any extra semi-colons until the end of the line.
760239462Sdim  void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
761239462Sdim
762243830Sdimpublic:
763193326Sed  //===--------------------------------------------------------------------===//
764193326Sed  // Scope manipulation
765198092Srdivacky
766193326Sed  /// ParseScope - Introduces a new scope for parsing. The kind of
767193326Sed  /// scope is determined by ScopeFlags. Objects of this type should
768193326Sed  /// be created on the stack to coincide with the position where the
769193326Sed  /// parser enters the new scope, and this object's constructor will
770193326Sed  /// create that new scope. Similarly, once the object is destroyed
771193326Sed  /// the parser will exit the scope.
772193326Sed  class ParseScope {
773193326Sed    Parser *Self;
774288943Sdim    ParseScope(const ParseScope &) = delete;
775288943Sdim    void operator=(const ParseScope &) = delete;
776193326Sed
777193326Sed  public:
778193326Sed    // ParseScope - Construct a new object to manage a scope in the
779193326Sed    // parser Self where the new Scope is created with the flags
780276479Sdim    // ScopeFlags, but only when we aren't about to enter a compound statement.
781276479Sdim    ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
782276479Sdim               bool BeforeCompoundStmt = false)
783193326Sed      : Self(Self) {
784276479Sdim      if (EnteredScope && !BeforeCompoundStmt)
785193326Sed        Self->EnterScope(ScopeFlags);
786276479Sdim      else {
787276479Sdim        if (BeforeCompoundStmt)
788288943Sdim          Self->incrementMSManglingNumber();
789276479Sdim
790276479Sdim        this->Self = nullptr;
791276479Sdim      }
792193326Sed    }
793193326Sed
794193326Sed    // Exit - Exit the scope associated with this object now, rather
795193326Sed    // than waiting until the object is destroyed.
796193326Sed    void Exit() {
797193326Sed      if (Self) {
798193326Sed        Self->ExitScope();
799276479Sdim        Self = nullptr;
800193326Sed      }
801193326Sed    }
802193326Sed
803193326Sed    ~ParseScope() {
804193326Sed      Exit();
805193326Sed    }
806193326Sed  };
807193326Sed
808193326Sed  /// EnterScope - Start a new scope.
809193326Sed  void EnterScope(unsigned ScopeFlags);
810198092Srdivacky
811193326Sed  /// ExitScope - Pop a scope off the scope stack.
812193326Sed  void ExitScope();
813193326Sed
814243830Sdimprivate:
815223017Sdim  /// \brief RAII object used to modify the scope flags for the current scope.
816223017Sdim  class ParseScopeFlags {
817223017Sdim    Scope *CurScope;
818223017Sdim    unsigned OldFlags;
819288943Sdim    ParseScopeFlags(const ParseScopeFlags &) = delete;
820288943Sdim    void operator=(const ParseScopeFlags &) = delete;
821223017Sdim
822223017Sdim  public:
823223017Sdim    ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
824223017Sdim    ~ParseScopeFlags();
825223017Sdim  };
826223017Sdim
827193326Sed  //===--------------------------------------------------------------------===//
828193326Sed  // Diagnostic Emission and Error recovery.
829193326Sed
830207619Srdivackypublic:
831193326Sed  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
832193326Sed  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
833239462Sdim  DiagnosticBuilder Diag(unsigned DiagID) {
834239462Sdim    return Diag(Tok, DiagID);
835239462Sdim  }
836193326Sed
837207619Srdivackyprivate:
838198092Srdivacky  void SuggestParentheses(SourceLocation Loc, unsigned DK,
839193326Sed                          SourceRange ParenRange);
840234353Sdim  void CheckNestedObjCContexts(SourceLocation AtLoc);
841193326Sed
842243830Sdimpublic:
843261991Sdim
844261991Sdim  /// \brief Control flags for SkipUntil functions.
845261991Sdim  enum SkipUntilFlags {
846261991Sdim    StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
847261991Sdim    /// \brief Stop skipping at specified token, but don't skip the token itself
848261991Sdim    StopBeforeMatch = 1 << 1,
849261991Sdim    StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
850261991Sdim  };
851261991Sdim
852261991Sdim  friend LLVM_CONSTEXPR SkipUntilFlags operator|(SkipUntilFlags L,
853261991Sdim                                                 SkipUntilFlags R) {
854261991Sdim    return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
855261991Sdim                                       static_cast<unsigned>(R));
856261991Sdim  }
857261991Sdim
858193326Sed  /// SkipUntil - Read tokens until we get to the specified token, then consume
859261991Sdim  /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
860261991Sdim  /// that the token will ever occur, this skips to the next token, or to some
861261991Sdim  /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
862261991Sdim  /// stop at a ';' character.
863198092Srdivacky  ///
864193326Sed  /// If SkipUntil finds the specified token, it returns true, otherwise it
865198092Srdivacky  /// returns false.
866261991Sdim  bool SkipUntil(tok::TokenKind T,
867261991Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
868261991Sdim    return SkipUntil(llvm::makeArrayRef(T), Flags);
869193326Sed  }
870261991Sdim  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
871261991Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
872193326Sed    tok::TokenKind TokArray[] = {T1, T2};
873261991Sdim    return SkipUntil(TokArray, Flags);
874193326Sed  }
875234353Sdim  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
876261991Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
877234353Sdim    tok::TokenKind TokArray[] = {T1, T2, T3};
878261991Sdim    return SkipUntil(TokArray, Flags);
879234353Sdim  }
880261991Sdim  bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
881261991Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
882193326Sed
883234353Sdim  /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
884234353Sdim  /// point for skipping past a simple-declaration.
885234353Sdim  void SkipMalformedDecl();
886234353Sdim
887243830Sdimprivate:
888193326Sed  //===--------------------------------------------------------------------===//
889193326Sed  // Lexing and parsing of C++ inline methods.
890193326Sed
891218893Sdim  struct ParsingClass;
892218893Sdim
893218893Sdim  /// [class.mem]p1: "... the class is regarded as complete within
894218893Sdim  /// - function bodies
895218893Sdim  /// - default arguments
896218893Sdim  /// - exception-specifications (TODO: C++0x)
897223017Sdim  /// - and brace-or-equal-initializers for non-static data members
898223017Sdim  /// (including such things in nested classes)."
899218893Sdim  /// LateParsedDeclarations build the tree of those elements so they can
900218893Sdim  /// be parsed after parsing the top-level class.
901218893Sdim  class LateParsedDeclaration {
902218893Sdim  public:
903218893Sdim    virtual ~LateParsedDeclaration();
904218893Sdim
905218893Sdim    virtual void ParseLexedMethodDeclarations();
906223017Sdim    virtual void ParseLexedMemberInitializers();
907218893Sdim    virtual void ParseLexedMethodDefs();
908226633Sdim    virtual void ParseLexedAttributes();
909218893Sdim  };
910218893Sdim
911218893Sdim  /// Inner node of the LateParsedDeclaration tree that parses
912218893Sdim  /// all its members recursively.
913218893Sdim  class LateParsedClass : public LateParsedDeclaration {
914218893Sdim  public:
915218893Sdim    LateParsedClass(Parser *P, ParsingClass *C);
916288943Sdim    ~LateParsedClass() override;
917218893Sdim
918276479Sdim    void ParseLexedMethodDeclarations() override;
919276479Sdim    void ParseLexedMemberInitializers() override;
920276479Sdim    void ParseLexedMethodDefs() override;
921276479Sdim    void ParseLexedAttributes() override;
922218893Sdim
923218893Sdim  private:
924218893Sdim    Parser *Self;
925218893Sdim    ParsingClass *Class;
926218893Sdim  };
927218893Sdim
928234353Sdim  /// Contains the lexed tokens of an attribute with arguments that
929234353Sdim  /// may reference member variables and so need to be parsed at the
930234353Sdim  /// end of the class declaration after parsing all other member
931226633Sdim  /// member declarations.
932226633Sdim  /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
933226633Sdim  /// LateParsedTokens.
934226633Sdim  struct LateParsedAttribute : public LateParsedDeclaration {
935226633Sdim    Parser *Self;
936226633Sdim    CachedTokens Toks;
937226633Sdim    IdentifierInfo &AttrName;
938226633Sdim    SourceLocation AttrNameLoc;
939234353Sdim    SmallVector<Decl*, 2> Decls;
940226633Sdim
941234353Sdim    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
942226633Sdim                                 SourceLocation Loc)
943234353Sdim      : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
944226633Sdim
945276479Sdim    void ParseLexedAttributes() override;
946226633Sdim
947234353Sdim    void addDecl(Decl *D) { Decls.push_back(D); }
948226633Sdim  };
949226633Sdim
950243830Sdim  // A list of late-parsed attributes.  Used by ParseGNUAttributes.
951249423Sdim  class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
952243830Sdim  public:
953243830Sdim    LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
954226633Sdim
955243830Sdim    bool parseSoon() { return ParseSoon; }
956226633Sdim
957243830Sdim  private:
958243830Sdim    bool ParseSoon;  // Are we planning to parse these shortly after creation?
959243830Sdim  };
960243830Sdim
961218893Sdim  /// Contains the lexed tokens of a member function definition
962218893Sdim  /// which needs to be parsed at the end of the class declaration
963218893Sdim  /// after parsing all other member declarations.
964218893Sdim  struct LexedMethod : public LateParsedDeclaration {
965218893Sdim    Parser *Self;
966212904Sdim    Decl *D;
967193326Sed    CachedTokens Toks;
968198092Srdivacky
969198092Srdivacky    /// \brief Whether this member function had an associated template
970198092Srdivacky    /// scope. When true, D is a template declaration.
971249423Sdim    /// otherwise, it is a member function declaration.
972198092Srdivacky    bool TemplateScope;
973198092Srdivacky
974218893Sdim    explicit LexedMethod(Parser* P, Decl *MD)
975218893Sdim      : Self(P), D(MD), TemplateScope(false) {}
976218893Sdim
977276479Sdim    void ParseLexedMethodDefs() override;
978193326Sed  };
979193326Sed
980193326Sed  /// LateParsedDefaultArgument - Keeps track of a parameter that may
981193326Sed  /// have a default argument that cannot be parsed yet because it
982193326Sed  /// occurs within a member function declaration inside the class
983193326Sed  /// (C++ [class.mem]p2).
984193326Sed  struct LateParsedDefaultArgument {
985212904Sdim    explicit LateParsedDefaultArgument(Decl *P,
986276479Sdim                                       CachedTokens *Toks = nullptr)
987193326Sed      : Param(P), Toks(Toks) { }
988193326Sed
989193326Sed    /// Param - The parameter declaration for this parameter.
990212904Sdim    Decl *Param;
991193326Sed
992193326Sed    /// Toks - The sequence of tokens that comprises the default
993193326Sed    /// argument expression, not including the '=' or the terminating
994193326Sed    /// ')' or ','. This will be NULL for parameters that have no
995193326Sed    /// default argument.
996193326Sed    CachedTokens *Toks;
997193326Sed  };
998198092Srdivacky
999193326Sed  /// LateParsedMethodDeclaration - A method declaration inside a class that
1000193326Sed  /// contains at least one entity whose parsing needs to be delayed
1001193326Sed  /// until the class itself is completely-defined, such as a default
1002193326Sed  /// argument (C++ [class.mem]p2).
1003218893Sdim  struct LateParsedMethodDeclaration : public LateParsedDeclaration {
1004218893Sdim    explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
1005276479Sdim      : Self(P), Method(M), TemplateScope(false),
1006276479Sdim        ExceptionSpecTokens(nullptr) {}
1007193326Sed
1008276479Sdim    void ParseLexedMethodDeclarations() override;
1009218893Sdim
1010218893Sdim    Parser* Self;
1011218893Sdim
1012193326Sed    /// Method - The method declaration.
1013212904Sdim    Decl *Method;
1014193326Sed
1015198092Srdivacky    /// \brief Whether this member function had an associated template
1016198092Srdivacky    /// scope. When true, D is a template declaration.
1017198092Srdivacky    /// othewise, it is a member function declaration.
1018198092Srdivacky    bool TemplateScope;
1019198092Srdivacky
1020193326Sed    /// DefaultArgs - Contains the parameters of the function and
1021193326Sed    /// their default arguments. At least one of the parameters will
1022193326Sed    /// have a default argument, but all of the parameters of the
1023193326Sed    /// method will be stored so that they can be reintroduced into
1024198092Srdivacky    /// scope at the appropriate times.
1025226633Sdim    SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
1026234982Sdim
1027234982Sdim    /// \brief The set of tokens that make up an exception-specification that
1028234982Sdim    /// has not yet been parsed.
1029234982Sdim    CachedTokens *ExceptionSpecTokens;
1030193326Sed  };
1031193326Sed
1032223017Sdim  /// LateParsedMemberInitializer - An initializer for a non-static class data
1033223017Sdim  /// member whose parsing must to be delayed until the class is completely
1034223017Sdim  /// defined (C++11 [class.mem]p2).
1035223017Sdim  struct LateParsedMemberInitializer : public LateParsedDeclaration {
1036223017Sdim    LateParsedMemberInitializer(Parser *P, Decl *FD)
1037223017Sdim      : Self(P), Field(FD) { }
1038223017Sdim
1039276479Sdim    void ParseLexedMemberInitializers() override;
1040223017Sdim
1041223017Sdim    Parser *Self;
1042223017Sdim
1043223017Sdim    /// Field - The field declaration.
1044223017Sdim    Decl *Field;
1045223017Sdim
1046223017Sdim    /// CachedTokens - The sequence of tokens that comprises the initializer,
1047223017Sdim    /// including any leading '='.
1048223017Sdim    CachedTokens Toks;
1049223017Sdim  };
1050223017Sdim
1051218893Sdim  /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
1052218893Sdim  /// C++ class, its method declarations that contain parts that won't be
1053221345Sdim  /// parsed until after the definition is completed (C++ [class.mem]p2),
1054218893Sdim  /// the method declarations and possibly attached inline definitions
1055234353Sdim  /// will be stored here with the tokens that will be parsed to create those
1056234353Sdim  /// entities.
1057234353Sdim  typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
1058193326Sed
1059193326Sed  /// \brief Representation of a class that has been parsed, including
1060193326Sed  /// any member function declarations or definitions that need to be
1061193326Sed  /// parsed after the corresponding top-level class is complete.
1062193326Sed  struct ParsingClass {
1063243830Sdim    ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
1064198092Srdivacky      : TopLevelClass(TopLevelClass), TemplateScope(false),
1065243830Sdim        IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
1066193326Sed
1067193326Sed    /// \brief Whether this is a "top-level" class, meaning that it is
1068193326Sed    /// not nested within another class.
1069193326Sed    bool TopLevelClass : 1;
1070193326Sed
1071193326Sed    /// \brief Whether this class had an associated template
1072193326Sed    /// scope. When true, TagOrTemplate is a template declaration;
1073193326Sed    /// othewise, it is a tag declaration.
1074193326Sed    bool TemplateScope : 1;
1075193326Sed
1076243830Sdim    /// \brief Whether this class is an __interface.
1077243830Sdim    bool IsInterface : 1;
1078243830Sdim
1079193326Sed    /// \brief The class or class template whose definition we are parsing.
1080212904Sdim    Decl *TagOrTemplate;
1081193326Sed
1082218893Sdim    /// LateParsedDeclarations - Method declarations, inline definitions and
1083218893Sdim    /// nested classes that contain pieces whose parsing will be delayed until
1084218893Sdim    /// the top-level class is fully defined.
1085218893Sdim    LateParsedDeclarationsContainer LateParsedDeclarations;
1086193326Sed  };
1087193326Sed
1088193326Sed  /// \brief The stack of classes that is currently being
1089193326Sed  /// parsed. Nested and local classes will be pushed onto this stack
1090193326Sed  /// when they are parsed, and removed afterward.
1091193326Sed  std::stack<ParsingClass *> ClassStack;
1092193326Sed
1093193326Sed  ParsingClass &getCurrentClass() {
1094193326Sed    assert(!ClassStack.empty() && "No lexed method stacks!");
1095193326Sed    return *ClassStack.top();
1096193326Sed  }
1097193326Sed
1098239462Sdim  /// \brief RAII object used to manage the parsing of a class definition.
1099193326Sed  class ParsingClassDefinition {
1100193326Sed    Parser &P;
1101193326Sed    bool Popped;
1102218893Sdim    Sema::ParsingClassState State;
1103193326Sed
1104193326Sed  public:
1105243830Sdim    ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1106243830Sdim                           bool IsInterface)
1107218893Sdim      : P(P), Popped(false),
1108243830Sdim        State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1109193326Sed    }
1110193326Sed
1111193326Sed    /// \brief Pop this class of the stack.
1112198092Srdivacky    void Pop() {
1113193326Sed      assert(!Popped && "Nested class has already been popped");
1114193326Sed      Popped = true;
1115218893Sdim      P.PopParsingClass(State);
1116193326Sed    }
1117193326Sed
1118198092Srdivacky    ~ParsingClassDefinition() {
1119193326Sed      if (!Popped)
1120218893Sdim        P.PopParsingClass(State);
1121193326Sed    }
1122193326Sed  };
1123193326Sed
1124193326Sed  /// \brief Contains information about any template-specific
1125193326Sed  /// information that has been parsed prior to parsing declaration
1126193326Sed  /// specifiers.
1127193326Sed  struct ParsedTemplateInfo {
1128198092Srdivacky    ParsedTemplateInfo()
1129276479Sdim      : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { }
1130193326Sed
1131193326Sed    ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1132198893Srdivacky                       bool isSpecialization,
1133198893Srdivacky                       bool lastParameterListWasEmpty = false)
1134193326Sed      : Kind(isSpecialization? ExplicitSpecialization : Template),
1135234353Sdim        TemplateParams(TemplateParams),
1136198893Srdivacky        LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1137193326Sed
1138198092Srdivacky    explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1139198092Srdivacky                                SourceLocation TemplateLoc)
1140276479Sdim      : Kind(ExplicitInstantiation), TemplateParams(nullptr),
1141198893Srdivacky        ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1142198893Srdivacky        LastParameterListWasEmpty(false){ }
1143193326Sed
1144193326Sed    /// \brief The kind of template we are parsing.
1145193326Sed    enum {
1146193326Sed      /// \brief We are not parsing a template at all.
1147193326Sed      NonTemplate = 0,
1148193326Sed      /// \brief We are parsing a template declaration.
1149193326Sed      Template,
1150193326Sed      /// \brief We are parsing an explicit specialization.
1151193326Sed      ExplicitSpecialization,
1152193326Sed      /// \brief We are parsing an explicit instantiation.
1153193326Sed      ExplicitInstantiation
1154193326Sed    } Kind;
1155193326Sed
1156193326Sed    /// \brief The template parameter lists, for template declarations
1157193326Sed    /// and explicit specializations.
1158193326Sed    TemplateParameterLists *TemplateParams;
1159193326Sed
1160198092Srdivacky    /// \brief The location of the 'extern' keyword, if any, for an explicit
1161198092Srdivacky    /// instantiation
1162198092Srdivacky    SourceLocation ExternLoc;
1163198092Srdivacky
1164193326Sed    /// \brief The location of the 'template' keyword, for an explicit
1165193326Sed    /// instantiation.
1166193326Sed    SourceLocation TemplateLoc;
1167234353Sdim
1168198893Srdivacky    /// \brief Whether the last template parameter list was empty.
1169198893Srdivacky    bool LastParameterListWasEmpty;
1170218893Sdim
1171234353Sdim    SourceRange getSourceRange() const LLVM_READONLY;
1172193326Sed  };
1173193326Sed
1174221345Sdim  void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1175261991Sdim  void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1176221345Sdim
1177261991Sdim  static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1178280031Sdim  static void LateTemplateParserCleanupCallback(void *P);
1179221345Sdim
1180218893Sdim  Sema::ParsingClassState
1181243830Sdim  PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1182198092Srdivacky  void DeallocateParsedClasses(ParsingClass *Class);
1183218893Sdim  void PopParsingClass(Sema::ParsingClassState);
1184198092Srdivacky
1185261991Sdim  enum CachedInitKind {
1186261991Sdim    CIK_DefaultArgument,
1187261991Sdim    CIK_DefaultInitializer
1188261991Sdim  };
1189261991Sdim
1190249423Sdim  NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1191249423Sdim                                AttributeList *AccessAttrs,
1192226633Sdim                                ParsingDeclarator &D,
1193218893Sdim                                const ParsedTemplateInfo &TemplateInfo,
1194234353Sdim                                const VirtSpecifiers& VS,
1195288943Sdim                                SourceLocation PureSpecLoc);
1196223017Sdim  void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1197226633Sdim  void ParseLexedAttributes(ParsingClass &Class);
1198234353Sdim  void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1199234353Sdim                               bool EnterScope, bool OnDefinition);
1200234353Sdim  void ParseLexedAttribute(LateParsedAttribute &LA,
1201234353Sdim                           bool EnterScope, bool OnDefinition);
1202198092Srdivacky  void ParseLexedMethodDeclarations(ParsingClass &Class);
1203218893Sdim  void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1204198092Srdivacky  void ParseLexedMethodDefs(ParsingClass &Class);
1205218893Sdim  void ParseLexedMethodDef(LexedMethod &LM);
1206223017Sdim  void ParseLexedMemberInitializers(ParsingClass &Class);
1207223017Sdim  void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1208239462Sdim  void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1209226633Sdim  bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1210261991Sdim  bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1211261991Sdim  bool ConsumeAndStoreConditional(CachedTokens &Toks);
1212207619Srdivacky  bool ConsumeAndStoreUntil(tok::TokenKind T1,
1213207619Srdivacky                            CachedTokens &Toks,
1214207619Srdivacky                            bool StopAtSemi = true,
1215207619Srdivacky                            bool ConsumeFinalToken = true) {
1216207619Srdivacky    return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1217207619Srdivacky  }
1218198092Srdivacky  bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1219198092Srdivacky                            CachedTokens &Toks,
1220207619Srdivacky                            bool StopAtSemi = true,
1221198092Srdivacky                            bool ConsumeFinalToken = true);
1222198092Srdivacky
1223193326Sed  //===--------------------------------------------------------------------===//
1224193326Sed  // C99 6.9: External Definitions.
1225218893Sdim  struct ParsedAttributesWithRange : ParsedAttributes {
1226221345Sdim    ParsedAttributesWithRange(AttributeFactory &factory)
1227221345Sdim      : ParsedAttributes(factory) {}
1228221345Sdim
1229218893Sdim    SourceRange Range;
1230218893Sdim  };
1231218893Sdim
1232218893Sdim  DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1233276479Sdim                                          ParsingDeclSpec *DS = nullptr);
1234223017Sdim  bool isDeclarationAfterDeclarator();
1235210299Sed  bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1236239462Sdim  DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1237239462Sdim                                                  ParsedAttributesWithRange &attrs,
1238276479Sdim                                                  ParsingDeclSpec *DS = nullptr,
1239218893Sdim                                                  AccessSpecifier AS = AS_none);
1240239462Sdim  DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1241239462Sdim                                                ParsingDeclSpec &DS,
1242239462Sdim                                                AccessSpecifier AS);
1243234353Sdim
1244296417Sdim  void SkipFunctionBody();
1245212904Sdim  Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1246234353Sdim                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1247276479Sdim                 LateParsedAttrList *LateParsedAttrs = nullptr);
1248193326Sed  void ParseKNRParamDeclarations(Declarator &D);
1249193326Sed  // EndLoc, if non-NULL, is filled with the location of the last token of
1250193326Sed  // the simple-asm.
1251276479Sdim  ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
1252212904Sdim  ExprResult ParseAsmStringLiteral();
1253193326Sed
1254193326Sed  // Objective-C External Declarations
1255249423Sdim  void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1256234353Sdim  DeclGroupPtrTy ParseObjCAtDirectives();
1257234353Sdim  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1258234353Sdim  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1259218893Sdim                                        ParsedAttributes &prefixAttrs);
1260296417Sdim  class ObjCTypeParamListScope;
1261288943Sdim  ObjCTypeParamList *parseObjCTypeParamList();
1262288943Sdim  ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs(
1263296417Sdim      ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
1264296417Sdim      SmallVectorImpl<IdentifierLocPair> &protocolIdents,
1265296417Sdim      SourceLocation &rAngleLoc, bool mayBeProtocolList = true);
1266288943Sdim
1267249423Sdim  void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1268249423Sdim                                        BalancedDelimiterTracker &T,
1269249423Sdim                                        SmallVectorImpl<Decl *> &AllIvarDecls,
1270249423Sdim                                        bool RBraceMissing);
1271212904Sdim  void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1272204643Srdivacky                                       tok::ObjCKeywordKind visibility,
1273193326Sed                                       SourceLocation atLoc);
1274226633Sdim  bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1275226633Sdim                                   SmallVectorImpl<SourceLocation> &PLocs,
1276198092Srdivacky                                   bool WarnOnDeclarations,
1277288943Sdim                                   bool ForObjCContainer,
1278198092Srdivacky                                   SourceLocation &LAngleLoc,
1279288943Sdim                                   SourceLocation &EndProtoLoc,
1280288943Sdim                                   bool consumeLastToken);
1281288943Sdim
1282288943Sdim  /// Parse the first angle-bracket-delimited clause for an
1283288943Sdim  /// Objective-C object or object pointer type, which may be either
1284288943Sdim  /// type arguments or protocol qualifiers.
1285288943Sdim  void parseObjCTypeArgsOrProtocolQualifiers(
1286288943Sdim         ParsedType baseType,
1287288943Sdim         SourceLocation &typeArgsLAngleLoc,
1288288943Sdim         SmallVectorImpl<ParsedType> &typeArgs,
1289288943Sdim         SourceLocation &typeArgsRAngleLoc,
1290288943Sdim         SourceLocation &protocolLAngleLoc,
1291288943Sdim         SmallVectorImpl<Decl *> &protocols,
1292288943Sdim         SmallVectorImpl<SourceLocation> &protocolLocs,
1293288943Sdim         SourceLocation &protocolRAngleLoc,
1294288943Sdim         bool consumeLastToken,
1295288943Sdim         bool warnOnIncompleteProtocols);
1296288943Sdim
1297288943Sdim  /// Parse either Objective-C type arguments or protocol qualifiers; if the
1298288943Sdim  /// former, also parse protocol qualifiers afterward.
1299288943Sdim  void parseObjCTypeArgsAndProtocolQualifiers(
1300288943Sdim         ParsedType baseType,
1301288943Sdim         SourceLocation &typeArgsLAngleLoc,
1302288943Sdim         SmallVectorImpl<ParsedType> &typeArgs,
1303288943Sdim         SourceLocation &typeArgsRAngleLoc,
1304288943Sdim         SourceLocation &protocolLAngleLoc,
1305288943Sdim         SmallVectorImpl<Decl *> &protocols,
1306288943Sdim         SmallVectorImpl<SourceLocation> &protocolLocs,
1307288943Sdim         SourceLocation &protocolRAngleLoc,
1308288943Sdim         bool consumeLastToken);
1309288943Sdim
1310288943Sdim  /// Parse a protocol qualifier type such as '<NSCopying>', which is
1311288943Sdim  /// an anachronistic way of writing 'id<NSCopying>'.
1312288943Sdim  TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc);
1313288943Sdim
1314288943Sdim  /// Parse Objective-C type arguments and protocol qualifiers, extending the
1315288943Sdim  /// current type with the parsed result.
1316288943Sdim  TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc,
1317288943Sdim                                                    ParsedType type,
1318288943Sdim                                                    bool consumeLastToken,
1319288943Sdim                                                    SourceLocation &endLoc);
1320288943Sdim
1321226633Sdim  void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1322226633Sdim                                  Decl *CDecl);
1323234353Sdim  DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1324234353Sdim                                                ParsedAttributes &prefixAttrs);
1325198092Srdivacky
1326234353Sdim  struct ObjCImplParsingDataRAII {
1327234353Sdim    Parser &P;
1328234353Sdim    Decl *Dcl;
1329239462Sdim    bool HasCFunction;
1330234353Sdim    typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1331234353Sdim    LateParsedObjCMethodContainer LateParsedObjCMethods;
1332193326Sed
1333234353Sdim    ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1334239462Sdim      : P(parser), Dcl(D), HasCFunction(false) {
1335234353Sdim      P.CurParsedObjCImpl = this;
1336234353Sdim      Finished = false;
1337234353Sdim    }
1338234353Sdim    ~ObjCImplParsingDataRAII();
1339234353Sdim
1340234353Sdim    void finish(SourceRange AtEnd);
1341234353Sdim    bool isFinished() const { return Finished; }
1342234353Sdim
1343234353Sdim  private:
1344234353Sdim    bool Finished;
1345234353Sdim  };
1346234353Sdim  ObjCImplParsingDataRAII *CurParsedObjCImpl;
1347239462Sdim  void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1348234353Sdim
1349234353Sdim  DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1350226633Sdim  DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1351212904Sdim  Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1352212904Sdim  Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1353212904Sdim  Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1354198092Srdivacky
1355193326Sed  IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1356193326Sed  // Definitions for Objective-c context sensitive keywords recognition.
1357193326Sed  enum ObjCTypeQual {
1358193326Sed    objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1359288943Sdim    objc_nonnull, objc_nullable, objc_null_unspecified,
1360193326Sed    objc_NumQuals
1361193326Sed  };
1362193326Sed  IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1363198092Srdivacky
1364193326Sed  bool isTokIdentifier_in() const;
1365193326Sed
1366226633Sdim  ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1367226633Sdim                               ParsedAttributes *ParamAttrs);
1368193326Sed  void ParseObjCMethodRequirement();
1369226633Sdim  Decl *ParseObjCMethodPrototype(
1370221345Sdim            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1371221345Sdim            bool MethodDefinition = true);
1372212904Sdim  Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1373221345Sdim            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1374221345Sdim            bool MethodDefinition=true);
1375226633Sdim  void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1376198092Srdivacky
1377212904Sdim  Decl *ParseObjCMethodDefinition();
1378198092Srdivacky
1379243830Sdimpublic:
1380193326Sed  //===--------------------------------------------------------------------===//
1381193326Sed  // C99 6.5: Expressions.
1382234353Sdim
1383234353Sdim  /// TypeCastState - State whether an expression is or may be a type cast.
1384234353Sdim  enum TypeCastState {
1385234353Sdim    NotTypeCast = 0,
1386234353Sdim    MaybeTypeCast,
1387234353Sdim    IsTypeCast
1388234353Sdim  };
1389234353Sdim
1390234353Sdim  ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1391234353Sdim  ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1392288943Sdim  ExprResult ParseConstraintExpression();
1393193326Sed  // Expr that doesn't include commas.
1394234353Sdim  ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1395193326Sed
1396251662Sdim  ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1397251662Sdim                                  unsigned &NumLineToksConsumed,
1398251662Sdim                                  void *Info,
1399251662Sdim                                  bool IsUnevaluated);
1400251662Sdim
1401243830Sdimprivate:
1402212904Sdim  ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1403193326Sed
1404212904Sdim  ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1405193326Sed
1406212904Sdim  ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1407221345Sdim                                        prec::Level MinPrec);
1408212904Sdim  ExprResult ParseCastExpression(bool isUnaryExpression,
1409221345Sdim                                 bool isAddressOfOperand,
1410221345Sdim                                 bool &NotCastExpr,
1411234353Sdim                                 TypeCastState isTypeCast);
1412212904Sdim  ExprResult ParseCastExpression(bool isUnaryExpression,
1413221345Sdim                                 bool isAddressOfOperand = false,
1414234353Sdim                                 TypeCastState isTypeCast = NotTypeCast);
1415198092Srdivacky
1416243830Sdim  /// Returns true if the next token cannot start an expression.
1417243830Sdim  bool isNotExpressionStart();
1418243830Sdim
1419212904Sdim  /// Returns true if the next token would start a postfix-expression
1420212904Sdim  /// suffix.
1421212904Sdim  bool isPostfixExpressionSuffixStart() {
1422212904Sdim    tok::TokenKind K = Tok.getKind();
1423212904Sdim    return (K == tok::l_square || K == tok::l_paren ||
1424212904Sdim            K == tok::period || K == tok::arrow ||
1425212904Sdim            K == tok::plusplus || K == tok::minusminus);
1426212904Sdim  }
1427212904Sdim
1428212904Sdim  ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1429221345Sdim  ExprResult ParseUnaryExprOrTypeTraitExpression();
1430212904Sdim  ExprResult ParseBuiltinPrimaryExpression();
1431212904Sdim
1432221345Sdim  ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1433193326Sed                                                     bool &isCastExpr,
1434212904Sdim                                                     ParsedType &CastTy,
1435193326Sed                                                     SourceRange &CastRange);
1436193326Sed
1437226633Sdim  typedef SmallVector<Expr*, 20> ExprListTy;
1438226633Sdim  typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1439193326Sed
1440193326Sed  /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1441288943Sdim  bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
1442288943Sdim                           SmallVectorImpl<SourceLocation> &CommaLocs,
1443288943Sdim                           std::function<void()> Completer = nullptr);
1444193326Sed
1445261991Sdim  /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1446261991Sdim  /// used for misc language extensions.
1447261991Sdim  bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1448261991Sdim                                 SmallVectorImpl<SourceLocation> &CommaLocs);
1449261991Sdim
1450261991Sdim
1451193326Sed  /// ParenParseOption - Control what ParseParenExpression will parse.
1452193326Sed  enum ParenParseOption {
1453193326Sed    SimpleExpr,      // Only parse '(' expression ')'
1454193326Sed    CompoundStmt,    // Also allow '(' compound-statement ')'
1455193326Sed    CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1456193326Sed    CastExpr         // Also allow '(' type-name ')' <anything>
1457193326Sed  };
1458212904Sdim  ExprResult ParseParenExpression(ParenParseOption &ExprType,
1459193326Sed                                        bool stopIfCastExpr,
1460224145Sdim                                        bool isTypeCast,
1461212904Sdim                                        ParsedType &CastTy,
1462193326Sed                                        SourceLocation &RParenLoc);
1463198092Srdivacky
1464276479Sdim  ExprResult ParseCXXAmbiguousParenExpression(
1465276479Sdim      ParenParseOption &ExprType, ParsedType &CastTy,
1466276479Sdim      BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt);
1467212904Sdim  ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1468193326Sed                                                  SourceLocation LParenLoc,
1469193326Sed                                                  SourceLocation RParenLoc);
1470198092Srdivacky
1471234353Sdim  ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1472193326Sed
1473221345Sdim  ExprResult ParseGenericSelectionExpression();
1474234353Sdim
1475234353Sdim  ExprResult ParseObjCBoolLiteral();
1476221345Sdim
1477280031Sdim  ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
1478280031Sdim
1479193326Sed  //===--------------------------------------------------------------------===//
1480193326Sed  // C++ Expressions
1481280031Sdim  ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
1482280031Sdim                                     Token &Replacement);
1483212904Sdim  ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1484193326Sed
1485239462Sdim  bool areTokensAdjacent(const Token &A, const Token &B);
1486239462Sdim
1487226633Sdim  void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1488226633Sdim                                  bool EnteringContext, IdentifierInfo &II,
1489226633Sdim                                  CXXScopeSpec &SS);
1490226633Sdim
1491198092Srdivacky  bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1492212904Sdim                                      ParsedType ObjectType,
1493204643Srdivacky                                      bool EnteringContext,
1494276479Sdim                                      bool *MayBePseudoDestructor = nullptr,
1495249423Sdim                                      bool IsTypename = false,
1496276479Sdim                                      IdentifierInfo **LastII = nullptr);
1497198092Srdivacky
1498243830Sdim  void CheckForLParenAfterColonColon();
1499243830Sdim
1500193326Sed  //===--------------------------------------------------------------------===//
1501226633Sdim  // C++0x 5.1.2: Lambda expressions
1502226633Sdim
1503226633Sdim  // [...] () -> type {...}
1504226633Sdim  ExprResult ParseLambdaExpression();
1505226633Sdim  ExprResult TryParseLambdaExpression();
1506261991Sdim  Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1507276479Sdim                                           bool *SkippedInits = nullptr);
1508226633Sdim  bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1509226633Sdim  ExprResult ParseLambdaExpressionAfterIntroducer(
1510226633Sdim               LambdaIntroducer &Intro);
1511226633Sdim
1512226633Sdim  //===--------------------------------------------------------------------===//
1513193326Sed  // C++ 5.2p1: C++ Casts
1514212904Sdim  ExprResult ParseCXXCasts();
1515193326Sed
1516193326Sed  //===--------------------------------------------------------------------===//
1517193326Sed  // C++ 5.2p1: C++ Type Identification
1518212904Sdim  ExprResult ParseCXXTypeid();
1519193326Sed
1520193326Sed  //===--------------------------------------------------------------------===//
1521218893Sdim  //  C++ : Microsoft __uuidof Expression
1522218893Sdim  ExprResult ParseCXXUuidof();
1523218893Sdim
1524218893Sdim  //===--------------------------------------------------------------------===//
1525204643Srdivacky  // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1526280031Sdim  ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1527204643Srdivacky                                            tok::TokenKind OpKind,
1528204643Srdivacky                                            CXXScopeSpec &SS,
1529212904Sdim                                            ParsedType ObjectType);
1530204643Srdivacky
1531204643Srdivacky  //===--------------------------------------------------------------------===//
1532193326Sed  // C++ 9.3.2: C++ 'this' pointer
1533212904Sdim  ExprResult ParseCXXThis();
1534193326Sed
1535193326Sed  //===--------------------------------------------------------------------===//
1536193326Sed  // C++ 15: C++ Throw Expression
1537212904Sdim  ExprResult ParseThrowExpression();
1538221345Sdim
1539234982Sdim  ExceptionSpecificationType tryParseExceptionSpecification(
1540280031Sdim                    bool Delayed,
1541221345Sdim                    SourceRange &SpecificationRange,
1542226633Sdim                    SmallVectorImpl<ParsedType> &DynamicExceptions,
1543226633Sdim                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1544280031Sdim                    ExprResult &NoexceptExpr,
1545280031Sdim                    CachedTokens *&ExceptionSpecTokens);
1546221345Sdim
1547193326Sed  // EndLoc is filled with the location of the last token of the specification.
1548221345Sdim  ExceptionSpecificationType ParseDynamicExceptionSpecification(
1549221345Sdim                                  SourceRange &SpecificationRange,
1550226633Sdim                                  SmallVectorImpl<ParsedType> &Exceptions,
1551226633Sdim                                  SmallVectorImpl<SourceRange> &Ranges);
1552193326Sed
1553193326Sed  //===--------------------------------------------------------------------===//
1554218893Sdim  // C++0x 8: Function declaration trailing-return-type
1555226633Sdim  TypeResult ParseTrailingReturnType(SourceRange &Range);
1556218893Sdim
1557218893Sdim  //===--------------------------------------------------------------------===//
1558193326Sed  // C++ 2.13.5: C++ Boolean Literals
1559212904Sdim  ExprResult ParseCXXBoolLiteral();
1560193326Sed
1561193326Sed  //===--------------------------------------------------------------------===//
1562193326Sed  // C++ 5.2.3: Explicit type conversion (functional notation)
1563212904Sdim  ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1564193326Sed
1565193326Sed  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1566193326Sed  /// This should only be called when the current token is known to be part of
1567193326Sed  /// simple-type-specifier.
1568193326Sed  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1569193326Sed
1570193326Sed  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1571193326Sed
1572193326Sed  //===--------------------------------------------------------------------===//
1573193326Sed  // C++ 5.3.4 and 5.3.5: C++ new and delete
1574226633Sdim  bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1575212904Sdim                                   Declarator &D);
1576193326Sed  void ParseDirectNewDeclarator(Declarator &D);
1577212904Sdim  ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1578212904Sdim  ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1579193326Sed                                            SourceLocation Start);
1580193326Sed
1581193326Sed  //===--------------------------------------------------------------------===//
1582199990Srdivacky  // C++ if/switch/while condition expression.
1583212904Sdim  bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1584208600Srdivacky                         SourceLocation Loc, bool ConvertToBoolean);
1585193326Sed
1586193326Sed  //===--------------------------------------------------------------------===//
1587296417Sdim  // C++ Coroutines
1588193326Sed
1589296417Sdim  ExprResult ParseCoyieldExpression();
1590296417Sdim
1591193326Sed  //===--------------------------------------------------------------------===//
1592193326Sed  // C99 6.7.8: Initialization.
1593198092Srdivacky
1594193326Sed  /// ParseInitializer
1595193326Sed  ///       initializer: [C99 6.7.8]
1596193326Sed  ///         assignment-expression
1597193326Sed  ///         '{' ...
1598212904Sdim  ExprResult ParseInitializer() {
1599193326Sed    if (Tok.isNot(tok::l_brace))
1600193326Sed      return ParseAssignmentExpression();
1601193326Sed    return ParseBraceInitializer();
1602193326Sed  }
1603234353Sdim  bool MayBeDesignationStart();
1604212904Sdim  ExprResult ParseBraceInitializer();
1605212904Sdim  ExprResult ParseInitializerWithPotentialDesignator();
1606193326Sed
1607193326Sed  //===--------------------------------------------------------------------===//
1608193326Sed  // clang Expressions
1609193326Sed
1610212904Sdim  ExprResult ParseBlockLiteralExpression();  // ^{...}
1611193326Sed
1612193326Sed  //===--------------------------------------------------------------------===//
1613193326Sed  // Objective-C Expressions
1614212904Sdim  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1615212904Sdim  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1616234353Sdim  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1617234353Sdim  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1618234353Sdim  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1619234353Sdim  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1620234353Sdim  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1621239462Sdim  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1622212904Sdim  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1623212904Sdim  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1624212904Sdim  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1625210299Sed  bool isSimpleObjCMessageExpression();
1626212904Sdim  ExprResult ParseObjCMessageExpression();
1627212904Sdim  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1628234353Sdim                                            SourceLocation SuperLoc,
1629234353Sdim                                            ParsedType ReceiverType,
1630280031Sdim                                            Expr *ReceiverExpr);
1631212904Sdim  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1632207619Srdivacky      SourceLocation LBracloc, SourceLocation SuperLoc,
1633280031Sdim      ParsedType ReceiverType, Expr *ReceiverExpr);
1634207619Srdivacky  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1635234353Sdim
1636193326Sed  //===--------------------------------------------------------------------===//
1637193326Sed  // C99 6.8: Statements and Blocks.
1638193326Sed
1639243830Sdim  /// A SmallVector of statements, with stack size 32 (as that is the only one
1640243830Sdim  /// used.)
1641243830Sdim  typedef SmallVector<Stmt*, 32> StmtVector;
1642243830Sdim  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1643243830Sdim  typedef SmallVector<Expr*, 12> ExprVector;
1644243830Sdim  /// A SmallVector of types.
1645243830Sdim  typedef SmallVector<ParsedType, 12> TypeVector;
1646243830Sdim
1647296417Sdim  StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
1648296417Sdim                            bool AllowOpenMPStandalone = false);
1649296417Sdim  enum AllowedContsructsKind {
1650296417Sdim    /// \brief Allow any declarations, statements, OpenMP directives.
1651296417Sdim    ACK_Any,
1652296417Sdim    /// \brief Allow only statements and non-standalone OpenMP directives.
1653296417Sdim    ACK_StatementsOpenMPNonStandalone,
1654296417Sdim    /// \brief Allow statements and all executable OpenMP directives
1655296417Sdim    ACK_StatementsOpenMPAnyExecutable
1656296417Sdim  };
1657276479Sdim  StmtResult
1658296417Sdim  ParseStatementOrDeclaration(StmtVector &Stmts, AllowedContsructsKind Allowed,
1659276479Sdim                              SourceLocation *TrailingElseLoc = nullptr);
1660234982Sdim  StmtResult ParseStatementOrDeclarationAfterAttributes(
1661234982Sdim                                         StmtVector &Stmts,
1662296417Sdim                                         AllowedContsructsKind Allowed,
1663234982Sdim                                         SourceLocation *TrailingElseLoc,
1664234982Sdim                                         ParsedAttributesWithRange &Attrs);
1665234982Sdim  StmtResult ParseExprStatement();
1666234982Sdim  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1667234982Sdim  StmtResult ParseCaseStatement(bool MissingCase = false,
1668221345Sdim                                ExprResult Expr = ExprResult());
1669234982Sdim  StmtResult ParseDefaultStatement();
1670234982Sdim  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1671234982Sdim  StmtResult ParseCompoundStatement(bool isStmtExpr,
1672224145Sdim                                    unsigned ScopeFlags);
1673243830Sdim  void ParseCompoundStatementLeadingPragmas();
1674212904Sdim  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1675212904Sdim  bool ParseParenExprOrCondition(ExprResult &ExprResult,
1676212904Sdim                                 Decl *&DeclResult,
1677208600Srdivacky                                 SourceLocation Loc,
1678208600Srdivacky                                 bool ConvertToBoolean);
1679234982Sdim  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1680234982Sdim  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1681234982Sdim  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1682234982Sdim  StmtResult ParseDoStatement();
1683234982Sdim  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1684234982Sdim  StmtResult ParseGotoStatement();
1685234982Sdim  StmtResult ParseContinueStatement();
1686234982Sdim  StmtResult ParseBreakStatement();
1687234982Sdim  StmtResult ParseReturnStatement();
1688212904Sdim  StmtResult ParseAsmStatement(bool &msAsm);
1689226633Sdim  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1690296417Sdim  StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
1691296417Sdim                                 AllowedContsructsKind Allowed,
1692276479Sdim                                 SourceLocation *TrailingElseLoc,
1693276479Sdim                                 ParsedAttributesWithRange &Attrs);
1694234353Sdim
1695234353Sdim  /// \brief Describes the behavior that should be taken for an __if_exists
1696234353Sdim  /// block.
1697234353Sdim  enum IfExistsBehavior {
1698234353Sdim    /// \brief Parse the block; this code is always used.
1699234353Sdim    IEB_Parse,
1700234353Sdim    /// \brief Skip the block entirely; this code is never used.
1701234353Sdim    IEB_Skip,
1702234353Sdim    /// \brief Parse the block as a dependent block, which may be used in
1703234353Sdim    /// some template instantiations but not others.
1704234353Sdim    IEB_Dependent
1705234353Sdim  };
1706234353Sdim
1707234353Sdim  /// \brief Describes the condition of a Microsoft __if_exists or
1708234353Sdim  /// __if_not_exists block.
1709234353Sdim  struct IfExistsCondition {
1710234353Sdim    /// \brief The location of the initial keyword.
1711234353Sdim    SourceLocation KeywordLoc;
1712234353Sdim    /// \brief Whether this is an __if_exists block (rather than an
1713234353Sdim    /// __if_not_exists block).
1714234353Sdim    bool IsIfExists;
1715234353Sdim
1716234353Sdim    /// \brief Nested-name-specifier preceding the name.
1717234353Sdim    CXXScopeSpec SS;
1718234353Sdim
1719234353Sdim    /// \brief The name we're looking for.
1720234353Sdim    UnqualifiedId Name;
1721234353Sdim
1722234353Sdim    /// \brief The behavior of this __if_exists or __if_not_exists block
1723234353Sdim    /// should.
1724234353Sdim    IfExistsBehavior Behavior;
1725234982Sdim  };
1726234353Sdim
1727234353Sdim  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1728223017Sdim  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1729223017Sdim  void ParseMicrosoftIfExistsExternalDeclaration();
1730223017Sdim  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1731223017Sdim                                              AccessSpecifier& CurAS);
1732234353Sdim  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1733234353Sdim                                              bool &InitExprsOk);
1734226633Sdim  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1735226633Sdim                           SmallVectorImpl<Expr *> &Constraints,
1736226633Sdim                           SmallVectorImpl<Expr *> &Exprs);
1737193326Sed
1738193326Sed  //===--------------------------------------------------------------------===//
1739193326Sed  // C++ 6: Statements and Blocks
1740193326Sed
1741234982Sdim  StmtResult ParseCXXTryBlock();
1742243830Sdim  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1743243830Sdim  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1744193326Sed
1745193326Sed  //===--------------------------------------------------------------------===//
1746221345Sdim  // MS: SEH Statements and Blocks
1747221345Sdim
1748234982Sdim  StmtResult ParseSEHTryBlock();
1749221345Sdim  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1750221345Sdim  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1751276479Sdim  StmtResult ParseSEHLeaveStatement();
1752221345Sdim
1753221345Sdim  //===--------------------------------------------------------------------===//
1754193326Sed  // Objective-C Statements
1755193326Sed
1756212904Sdim  StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1757212904Sdim  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1758212904Sdim  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1759212904Sdim  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1760224145Sdim  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1761193326Sed
1762193326Sed
1763193326Sed  //===--------------------------------------------------------------------===//
1764193326Sed  // C99 6.7: Declarations.
1765198092Srdivacky
1766198092Srdivacky  /// A context for parsing declaration specifiers.  TODO: flesh this
1767198092Srdivacky  /// out, there are other significant restrictions on specifiers than
1768198092Srdivacky  /// would be best implemented in the parser.
1769198092Srdivacky  enum DeclSpecContext {
1770198092Srdivacky    DSC_normal, // normal context
1771202379Srdivacky    DSC_class,  // class context, enables 'friend'
1772239462Sdim    DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1773234353Sdim    DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1774276479Sdim    DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration
1775276479Sdim    DSC_top_level, // top-level/namespace declaration context
1776288943Sdim    DSC_template_type_arg, // template type argument context
1777288943Sdim    DSC_objc_method_result, // ObjC method result context, enables 'instancetype'
1778288943Sdim    DSC_condition // condition declaration context
1779198092Srdivacky  };
1780198092Srdivacky
1781276479Sdim  /// Is this a context in which we are parsing just a type-specifier (or
1782276479Sdim  /// trailing-type-specifier)?
1783276479Sdim  static bool isTypeSpecifier(DeclSpecContext DSC) {
1784276479Sdim    switch (DSC) {
1785276479Sdim    case DSC_normal:
1786276479Sdim    case DSC_class:
1787276479Sdim    case DSC_top_level:
1788288943Sdim    case DSC_objc_method_result:
1789288943Sdim    case DSC_condition:
1790276479Sdim      return false;
1791276479Sdim
1792276479Sdim    case DSC_template_type_arg:
1793276479Sdim    case DSC_type_specifier:
1794276479Sdim    case DSC_trailing:
1795276479Sdim    case DSC_alias_declaration:
1796276479Sdim      return true;
1797276479Sdim    }
1798276479Sdim    llvm_unreachable("Missing DeclSpecContext case");
1799276479Sdim  }
1800276479Sdim
1801221345Sdim  /// Information on a C++0x for-range-initializer found while parsing a
1802221345Sdim  /// declaration which turns out to be a for-range-declaration.
1803221345Sdim  struct ForRangeInit {
1804221345Sdim    SourceLocation ColonLoc;
1805221345Sdim    ExprResult RangeExpr;
1806221345Sdim
1807221345Sdim    bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1808221345Sdim  };
1809221345Sdim
1810280031Sdim  DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
1811218893Sdim                                  ParsedAttributesWithRange &attrs);
1812280031Sdim  DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
1813199990Srdivacky                                        SourceLocation &DeclEnd,
1814239462Sdim                                        ParsedAttributesWithRange &attrs,
1815221345Sdim                                        bool RequireSemi,
1816276479Sdim                                        ForRangeInit *FRI = nullptr);
1817234353Sdim  bool MightBeDeclarator(unsigned Context);
1818198893Srdivacky  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1819276479Sdim                                SourceLocation *DeclEnd = nullptr,
1820276479Sdim                                ForRangeInit *FRI = nullptr);
1821212904Sdim  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1822195099Sed               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1823234353Sdim  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1824276479Sdim  Decl *ParseDeclarationAfterDeclaratorAndAttributes(
1825276479Sdim      Declarator &D,
1826276479Sdim      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1827276479Sdim      ForRangeInit *FRI = nullptr);
1828221345Sdim  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1829221345Sdim  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1830193326Sed
1831218893Sdim  /// \brief When in code-completion, skip parsing of the function/method body
1832218893Sdim  /// unless the body contains the code-completion point.
1833218893Sdim  ///
1834218893Sdim  /// \returns true if the function body was skipped.
1835234353Sdim  bool trySkippingFunctionBody();
1836218893Sdim
1837193326Sed  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1838193326Sed                        const ParsedTemplateInfo &TemplateInfo,
1839249423Sdim                        AccessSpecifier AS, DeclSpecContext DSC,
1840249423Sdim                        ParsedAttributesWithRange &Attrs);
1841202379Srdivacky  DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1842198092Srdivacky  void ParseDeclarationSpecifiers(DeclSpec &DS,
1843193326Sed                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1844198092Srdivacky                                  AccessSpecifier AS = AS_none,
1845234353Sdim                                  DeclSpecContext DSC = DSC_normal,
1846276479Sdim                                  LateParsedAttrList *LateAttrs = nullptr);
1847261991Sdim  bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1848276479Sdim                                       DeclSpecContext DSContext,
1849276479Sdim                                       LateParsedAttrList *LateAttrs = nullptr);
1850193326Sed
1851234353Sdim  void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1852234353Sdim                                   DeclSpecContext DSC = DSC_normal);
1853198092Srdivacky
1854226633Sdim  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1855226633Sdim                                  Declarator::TheContext Context);
1856193326Sed
1857193326Sed  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1858234353Sdim                          const ParsedTemplateInfo &TemplateInfo,
1859234353Sdim                          AccessSpecifier AS, DeclSpecContext DSC);
1860212904Sdim  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1861193326Sed  void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1862212904Sdim                            Decl *TagDecl);
1863198092Srdivacky
1864280031Sdim  void ParseStructDeclaration(
1865280031Sdim      ParsingDeclSpec &DS,
1866280031Sdim      llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
1867198893Srdivacky
1868218893Sdim  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1869193326Sed  bool isTypeSpecifierQualifier();
1870193326Sed  bool isTypeQualifier() const;
1871234353Sdim
1872204643Srdivacky  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1873204643Srdivacky  /// is definitely a type-specifier.  Return false if it isn't part of a type
1874204643Srdivacky  /// specifier or if we're not sure.
1875204643Srdivacky  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1876193326Sed
1877243830Sdim  /// \brief Return true if we know that we are definitely looking at a
1878243830Sdim  /// decl-specifier, and isn't part of an expression such as a function-style
1879243830Sdim  /// cast. Return false if it's no a decl-specifier, or we're not sure.
1880243830Sdim  bool isKnownToBeDeclarationSpecifier() {
1881243830Sdim    if (getLangOpts().CPlusPlus)
1882276479Sdim      return isCXXDeclarationSpecifier() == TPResult::True;
1883243830Sdim    return isDeclarationSpecifier(true);
1884243830Sdim  }
1885243830Sdim
1886193326Sed  /// isDeclarationStatement - Disambiguates between a declaration or an
1887193326Sed  /// expression statement, when parsing function bodies.
1888193326Sed  /// Returns true for declaration, false for expression.
1889193326Sed  bool isDeclarationStatement() {
1890234353Sdim    if (getLangOpts().CPlusPlus)
1891193326Sed      return isCXXDeclarationStatement();
1892218893Sdim    return isDeclarationSpecifier(true);
1893193326Sed  }
1894193326Sed
1895234353Sdim  /// isForInitDeclaration - Disambiguates between a declaration or an
1896234353Sdim  /// expression in the context of the C 'clause-1' or the C++
1897193326Sed  // 'for-init-statement' part of a 'for' statement.
1898193326Sed  /// Returns true for declaration, false for expression.
1899234353Sdim  bool isForInitDeclaration() {
1900234353Sdim    if (getLangOpts().CPlusPlus)
1901234353Sdim      return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1902218893Sdim    return isDeclarationSpecifier(true);
1903193326Sed  }
1904193326Sed
1905276479Sdim  /// \brief Determine whether this is a C++1z for-range-identifier.
1906276479Sdim  bool isForRangeIdentifier();
1907276479Sdim
1908218893Sdim  /// \brief Determine whether we are currently at the start of an Objective-C
1909218893Sdim  /// class message that appears to be missing the open bracket '['.
1910218893Sdim  bool isStartOfObjCClassMessageMissingOpenBracket();
1911234353Sdim
1912202379Srdivacky  /// \brief Starting with a scope specifier, identifier, or
1913202379Srdivacky  /// template-id that refers to the current class, determine whether
1914202379Srdivacky  /// this is a constructor declarator.
1915276479Sdim  bool isConstructorDeclarator(bool Unqualified);
1916202379Srdivacky
1917193326Sed  /// \brief Specifies the context in which type-id/expression
1918193326Sed  /// disambiguation will occur.
1919193326Sed  enum TentativeCXXTypeIdContext {
1920193326Sed    TypeIdInParens,
1921276479Sdim    TypeIdUnambiguous,
1922193326Sed    TypeIdAsTemplateArgument
1923193326Sed  };
1924193326Sed
1925193326Sed
1926193326Sed  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1927193326Sed  /// whether the parens contain an expression or a type-id.
1928193326Sed  /// Returns true for a type-id and false for an expression.
1929193326Sed  bool isTypeIdInParens(bool &isAmbiguous) {
1930234353Sdim    if (getLangOpts().CPlusPlus)
1931193326Sed      return isCXXTypeId(TypeIdInParens, isAmbiguous);
1932193326Sed    isAmbiguous = false;
1933193326Sed    return isTypeSpecifierQualifier();
1934193326Sed  }
1935193326Sed  bool isTypeIdInParens() {
1936193326Sed    bool isAmbiguous;
1937193326Sed    return isTypeIdInParens(isAmbiguous);
1938193326Sed  }
1939193326Sed
1940276479Sdim  /// \brief Checks if the current tokens form type-id or expression.
1941276479Sdim  /// It is similar to isTypeIdInParens but does not suppose that type-id
1942276479Sdim  /// is in parenthesis.
1943276479Sdim  bool isTypeIdUnambiguously() {
1944276479Sdim    bool IsAmbiguous;
1945276479Sdim    if (getLangOpts().CPlusPlus)
1946276479Sdim      return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous);
1947276479Sdim    return isTypeSpecifierQualifier();
1948276479Sdim  }
1949276479Sdim
1950193326Sed  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1951193326Sed  /// between a declaration or an expression statement, when parsing function
1952193326Sed  /// bodies. Returns true for declaration, false for expression.
1953193326Sed  bool isCXXDeclarationStatement();
1954193326Sed
1955193326Sed  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1956193326Sed  /// between a simple-declaration or an expression-statement.
1957193326Sed  /// If during the disambiguation process a parsing error is encountered,
1958193326Sed  /// the function returns true to let the declaration parsing code handle it.
1959193326Sed  /// Returns false if the statement is disambiguated as expression.
1960234353Sdim  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1961193326Sed
1962193326Sed  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1963193326Sed  /// a constructor-style initializer, when parsing declaration statements.
1964193326Sed  /// Returns true for function declarator and false for constructor-style
1965239462Sdim  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1966239462Sdim  /// might be a constructor-style initializer.
1967193326Sed  /// If during the disambiguation process a parsing error is encountered,
1968193326Sed  /// the function returns true to let the declaration parsing code handle it.
1969276479Sdim  bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr);
1970193326Sed
1971193326Sed  /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1972193326Sed  /// expression for a condition of a if/switch/while/for statement.
1973193326Sed  /// If during the disambiguation process a parsing error is encountered,
1974193326Sed  /// the function returns true to let the declaration parsing code handle it.
1975193326Sed  bool isCXXConditionDeclaration();
1976193326Sed
1977193326Sed  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1978193326Sed  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1979193326Sed    bool isAmbiguous;
1980193326Sed    return isCXXTypeId(Context, isAmbiguous);
1981193326Sed  }
1982193326Sed
1983193326Sed  /// TPResult - Used as the result value for functions whose purpose is to
1984193326Sed  /// disambiguate C++ constructs by "tentatively parsing" them.
1985276479Sdim  enum class TPResult {
1986276479Sdim    True, False, Ambiguous, Error
1987193326Sed  };
1988193326Sed
1989218893Sdim  /// \brief Based only on the given token kind, determine whether we know that
1990218893Sdim  /// we're at the start of an expression or a type-specifier-seq (which may
1991218893Sdim  /// be an expression, in C++).
1992218893Sdim  ///
1993218893Sdim  /// This routine does not attempt to resolve any of the trick cases, e.g.,
1994218893Sdim  /// those involving lookup of identifiers.
1995218893Sdim  ///
1996218893Sdim  /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1997218893Sdim  /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1998218893Sdim  /// tell.
1999218893Sdim  TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
2000218893Sdim
2001276479Sdim  /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
2002276479Sdim  /// declaration specifier, TPResult::False if it is not,
2003276479Sdim  /// TPResult::Ambiguous if it could be either a decl-specifier or a
2004276479Sdim  /// function-style cast, and TPResult::Error if a parsing error was
2005234353Sdim  /// encountered. If it could be a braced C++11 function-style cast, returns
2006234353Sdim  /// BracedCastResult.
2007193326Sed  /// Doesn't consume tokens.
2008234353Sdim  TPResult
2009276479Sdim  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
2010276479Sdim                            bool *HasMissingTypename = nullptr);
2011234353Sdim
2012261991Sdim  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
2013261991Sdim  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
2014261991Sdim  /// a type-specifier other than a cv-qualifier.
2015261991Sdim  bool isCXXDeclarationSpecifierAType();
2016261991Sdim
2017243830Sdim  /// \brief Determine whether an identifier has been tentatively declared as a
2018243830Sdim  /// non-type. Such tentative declarations should not be found to name a type
2019243830Sdim  /// during a tentative parse, but also should not be annotated as a non-type.
2020243830Sdim  bool isTentativelyDeclared(IdentifierInfo *II);
2021243830Sdim
2022193326Sed  // "Tentative parsing" functions, used for disambiguation. If a parsing error
2023276479Sdim  // is encountered they will return TPResult::Error.
2024276479Sdim  // Returning TPResult::True/False indicates that the ambiguity was
2025276479Sdim  // resolved and tentative parsing may stop. TPResult::Ambiguous indicates
2026193326Sed  // that more tentative parsing is necessary for disambiguation.
2027193326Sed  // They all consume tokens, so backtracking should be used after calling them.
2028193326Sed
2029234353Sdim  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
2030193326Sed  TPResult TryParseTypeofSpecifier();
2031218893Sdim  TPResult TryParseProtocolQualifiers();
2032261991Sdim  TPResult TryParsePtrOperatorSeq();
2033261991Sdim  TPResult TryParseOperatorId();
2034193326Sed  TPResult TryParseInitDeclaratorList();
2035193326Sed  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
2036276479Sdim  TPResult
2037276479Sdim  TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr,
2038276479Sdim                                     bool VersusTemplateArg = false);
2039193326Sed  TPResult TryParseFunctionDeclarator();
2040193326Sed  TPResult TryParseBracketDeclarator();
2041261991Sdim  TPResult TryConsumeDeclarationSpecifier();
2042193326Sed
2043243830Sdimpublic:
2044276479Sdim  TypeResult ParseTypeName(SourceRange *Range = nullptr,
2045218893Sdim                           Declarator::TheContext Context
2046224145Sdim                             = Declarator::TypeNameContext,
2047224145Sdim                           AccessSpecifier AS = AS_none,
2048276479Sdim                           Decl **OwnedType = nullptr,
2049276479Sdim                           ParsedAttributes *Attrs = nullptr);
2050243830Sdim
2051243830Sdimprivate:
2052239462Sdim  void ParseBlockId(SourceLocation CaretLoc);
2053218893Sdim
2054234353Sdim  // Check for the start of a C++11 attribute-specifier-seq in a context where
2055234353Sdim  // an attribute is not allowed.
2056234353Sdim  bool CheckProhibitedCXX11Attribute() {
2057234353Sdim    assert(Tok.is(tok::l_square));
2058249423Sdim    if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
2059234353Sdim      return false;
2060234353Sdim    return DiagnoseProhibitedCXX11Attribute();
2061234353Sdim  }
2062234353Sdim  bool DiagnoseProhibitedCXX11Attribute();
2063249423Sdim  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2064249423Sdim                                    SourceLocation CorrectLocation) {
2065249423Sdim    if (!getLangOpts().CPlusPlus11)
2066249423Sdim      return;
2067249423Sdim    if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
2068249423Sdim        Tok.isNot(tok::kw_alignas))
2069249423Sdim      return;
2070249423Sdim    DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
2071249423Sdim  }
2072249423Sdim  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
2073249423Sdim                                       SourceLocation CorrectLocation);
2074234353Sdim
2075288943Sdim  void handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
2076288943Sdim                                         DeclSpec &DS, Sema::TagUseKind TUK);
2077288943Sdim
2078218893Sdim  void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
2079218893Sdim    if (!attrs.Range.isValid()) return;
2080218893Sdim    DiagnoseProhibitedAttributes(attrs);
2081234982Sdim    attrs.clear();
2082218893Sdim  }
2083218893Sdim  void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
2084218893Sdim
2085243830Sdim  // Forbid C++11 attributes that appear on certain syntactic
2086243830Sdim  // locations which standard permits but we don't supported yet,
2087243830Sdim  // for example, attributes appertain to decl specifiers.
2088243830Sdim  void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
2089243830Sdim
2090276479Sdim  /// \brief Skip C++11 attributes and return the end location of the last one.
2091276479Sdim  /// \returns SourceLocation() if there are no attributes.
2092276479Sdim  SourceLocation SkipCXX11Attributes();
2093276479Sdim
2094261991Sdim  /// \brief Diagnose and skip C++11 attributes that appear in syntactic
2095261991Sdim  /// locations where attributes are not allowed.
2096261991Sdim  void DiagnoseAndSkipCXX11Attributes();
2097261991Sdim
2098276479Sdim  /// \brief Parses syntax-generic attribute arguments for attributes which are
2099276479Sdim  /// known to the implementation, and adds them to the given ParsedAttributes
2100276479Sdim  /// list with the given attribute syntax. Returns the number of arguments
2101276479Sdim  /// parsed for the attribute.
2102276479Sdim  unsigned
2103276479Sdim  ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
2104276479Sdim                           ParsedAttributes &Attrs, SourceLocation *EndLoc,
2105276479Sdim                           IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
2106276479Sdim                           AttributeList::Syntax Syntax);
2107276479Sdim
2108226633Sdim  void MaybeParseGNUAttributes(Declarator &D,
2109276479Sdim                               LateParsedAttrList *LateAttrs = nullptr) {
2110218893Sdim    if (Tok.is(tok::kw___attribute)) {
2111221345Sdim      ParsedAttributes attrs(AttrFactory);
2112218893Sdim      SourceLocation endLoc;
2113276479Sdim      ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
2114221345Sdim      D.takeAttributes(attrs, endLoc);
2115218893Sdim    }
2116218893Sdim  }
2117218893Sdim  void MaybeParseGNUAttributes(ParsedAttributes &attrs,
2118276479Sdim                               SourceLocation *endLoc = nullptr,
2119276479Sdim                               LateParsedAttrList *LateAttrs = nullptr) {
2120218893Sdim    if (Tok.is(tok::kw___attribute))
2121226633Sdim      ParseGNUAttributes(attrs, endLoc, LateAttrs);
2122218893Sdim  }
2123218893Sdim  void ParseGNUAttributes(ParsedAttributes &attrs,
2124276479Sdim                          SourceLocation *endLoc = nullptr,
2125276479Sdim                          LateParsedAttrList *LateAttrs = nullptr,
2126276479Sdim                          Declarator *D = nullptr);
2127226633Sdim  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
2128226633Sdim                             SourceLocation AttrNameLoc,
2129226633Sdim                             ParsedAttributes &Attrs,
2130243830Sdim                             SourceLocation *EndLoc,
2131243830Sdim                             IdentifierInfo *ScopeName,
2132243830Sdim                             SourceLocation ScopeLoc,
2133276479Sdim                             AttributeList::Syntax Syntax,
2134276479Sdim                             Declarator *D);
2135261991Sdim  IdentifierLoc *ParseIdentifierLoc();
2136218893Sdim
2137249423Sdim  void MaybeParseCXX11Attributes(Declarator &D) {
2138249423Sdim    if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2139221345Sdim      ParsedAttributesWithRange attrs(AttrFactory);
2140218893Sdim      SourceLocation endLoc;
2141234353Sdim      ParseCXX11Attributes(attrs, &endLoc);
2142221345Sdim      D.takeAttributes(attrs, endLoc);
2143218893Sdim    }
2144218893Sdim  }
2145249423Sdim  void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
2146276479Sdim                                 SourceLocation *endLoc = nullptr) {
2147249423Sdim    if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
2148221345Sdim      ParsedAttributesWithRange attrsWithRange(AttrFactory);
2149234353Sdim      ParseCXX11Attributes(attrsWithRange, endLoc);
2150221345Sdim      attrs.takeAllFrom(attrsWithRange);
2151218893Sdim    }
2152218893Sdim  }
2153249423Sdim  void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2154276479Sdim                                 SourceLocation *endLoc = nullptr,
2155234353Sdim                                 bool OuterMightBeMessageSend = false) {
2156249423Sdim    if (getLangOpts().CPlusPlus11 &&
2157234353Sdim        isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
2158234353Sdim      ParseCXX11Attributes(attrs, endLoc);
2159218893Sdim  }
2160226633Sdim
2161234353Sdim  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2162276479Sdim                                    SourceLocation *EndLoc = nullptr);
2163234353Sdim  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2164276479Sdim                            SourceLocation *EndLoc = nullptr);
2165276479Sdim  /// \brief Parses a C++-style attribute argument list. Returns true if this
2166276479Sdim  /// results in adding an attribute to the ParsedAttributes list.
2167276479Sdim  bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
2168276479Sdim                               SourceLocation AttrNameLoc,
2169276479Sdim                               ParsedAttributes &Attrs, SourceLocation *EndLoc,
2170276479Sdim                               IdentifierInfo *ScopeName,
2171276479Sdim                               SourceLocation ScopeLoc);
2172243830Sdim
2173234353Sdim  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
2174218893Sdim
2175218893Sdim  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
2176276479Sdim                                     SourceLocation *endLoc = nullptr) {
2177234353Sdim    if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
2178218893Sdim      ParseMicrosoftAttributes(attrs, endLoc);
2179218893Sdim  }
2180218893Sdim  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
2181276479Sdim                                SourceLocation *endLoc = nullptr);
2182288943Sdim  void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2183288943Sdim                                    SourceLocation *End = nullptr) {
2184288943Sdim    const auto &LO = getLangOpts();
2185296417Sdim    if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
2186288943Sdim      ParseMicrosoftDeclSpecs(Attrs, End);
2187288943Sdim  }
2188288943Sdim  void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
2189288943Sdim                               SourceLocation *End = nullptr);
2190276479Sdim  bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
2191276479Sdim                                  SourceLocation AttrNameLoc,
2192276479Sdim                                  ParsedAttributes &Attrs);
2193218893Sdim  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
2194280031Sdim  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2195280031Sdim  SourceLocation SkipExtendedMicrosoftTypeAttributes();
2196239462Sdim  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
2197218893Sdim  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
2198218893Sdim  void ParseOpenCLAttributes(ParsedAttributes &attrs);
2199276479Sdim  void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
2200288943Sdim  void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
2201218893Sdim
2202221345Sdim  VersionTuple ParseVersionTuple(SourceRange &Range);
2203221345Sdim  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
2204221345Sdim                                  SourceLocation AvailabilityLoc,
2205221345Sdim                                  ParsedAttributes &attrs,
2206276479Sdim                                  SourceLocation *endLoc,
2207276479Sdim                                  IdentifierInfo *ScopeName,
2208276479Sdim                                  SourceLocation ScopeLoc,
2209276479Sdim                                  AttributeList::Syntax Syntax);
2210221345Sdim
2211276479Sdim  void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
2212276479Sdim                                       SourceLocation ObjCBridgeRelatedLoc,
2213276479Sdim                                       ParsedAttributes &attrs,
2214276479Sdim                                       SourceLocation *endLoc,
2215276479Sdim                                       IdentifierInfo *ScopeName,
2216276479Sdim                                       SourceLocation ScopeLoc,
2217276479Sdim                                       AttributeList::Syntax Syntax);
2218226633Sdim
2219239462Sdim  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2220239462Sdim                                        SourceLocation AttrNameLoc,
2221239462Sdim                                        ParsedAttributes &Attrs,
2222276479Sdim                                        SourceLocation *EndLoc,
2223276479Sdim                                        IdentifierInfo *ScopeName,
2224276479Sdim                                        SourceLocation ScopeLoc,
2225276479Sdim                                        AttributeList::Syntax Syntax);
2226226633Sdim
2227261991Sdim  void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2228261991Sdim                                 SourceLocation AttrNameLoc,
2229261991Sdim                                 ParsedAttributes &Attrs,
2230276479Sdim                                 SourceLocation *EndLoc,
2231276479Sdim                                 IdentifierInfo *ScopeName,
2232276479Sdim                                 SourceLocation ScopeLoc,
2233276479Sdim                                 AttributeList::Syntax Syntax);
2234261991Sdim
2235193326Sed  void ParseTypeofSpecifier(DeclSpec &DS);
2236234353Sdim  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2237234982Sdim  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2238234353Sdim                                         SourceLocation StartLoc,
2239234353Sdim                                         SourceLocation EndLoc);
2240223017Sdim  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2241226633Sdim  void ParseAtomicSpecifier(DeclSpec &DS);
2242193326Sed
2243234353Sdim  ExprResult ParseAlignArgument(SourceLocation Start,
2244234353Sdim                                SourceLocation &EllipsisLoc);
2245226633Sdim  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2246276479Sdim                               SourceLocation *endLoc = nullptr);
2247226633Sdim
2248249423Sdim  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2249249423Sdim  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2250249423Sdim    return isCXX11VirtSpecifier(Tok);
2251234353Sdim  }
2252280031Sdim  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface,
2253280031Sdim                                          SourceLocation FriendLoc);
2254218893Sdim
2255249423Sdim  bool isCXX11FinalKeyword() const;
2256218893Sdim
2257193326Sed  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2258193326Sed  /// enter a new C++ declarator scope and exit it when the function is
2259193326Sed  /// finished.
2260193326Sed  class DeclaratorScopeObj {
2261193326Sed    Parser &P;
2262193326Sed    CXXScopeSpec &SS;
2263198092Srdivacky    bool EnteredScope;
2264199482Srdivacky    bool CreatedScope;
2265193326Sed  public:
2266198092Srdivacky    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2267199482Srdivacky      : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2268193326Sed
2269193326Sed    void EnterDeclaratorScope() {
2270198092Srdivacky      assert(!EnteredScope && "Already entered the scope!");
2271198092Srdivacky      assert(SS.isSet() && "C++ scope was not set!");
2272199482Srdivacky
2273199482Srdivacky      CreatedScope = true;
2274199482Srdivacky      P.EnterScope(0); // Not a decl scope.
2275199482Srdivacky
2276210299Sed      if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2277198092Srdivacky        EnteredScope = true;
2278193326Sed    }
2279193326Sed
2280193326Sed    ~DeclaratorScopeObj() {
2281198092Srdivacky      if (EnteredScope) {
2282198092Srdivacky        assert(SS.isSet() && "C++ scope was cleared ?");
2283210299Sed        P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2284198092Srdivacky      }
2285199482Srdivacky      if (CreatedScope)
2286199482Srdivacky        P.ExitScope();
2287193326Sed    }
2288193326Sed  };
2289198092Srdivacky
2290193326Sed  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2291193326Sed  void ParseDeclarator(Declarator &D);
2292193326Sed  /// A function that parses a variant of direct-declarator.
2293193326Sed  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2294193326Sed  void ParseDeclaratorInternal(Declarator &D,
2295193326Sed                               DirectDeclParseFunction DirectDeclParser);
2296218893Sdim
2297280031Sdim  enum AttrRequirements {
2298280031Sdim    AR_NoAttributesParsed = 0, ///< No attributes are diagnosed.
2299280031Sdim    AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes.
2300280031Sdim    AR_GNUAttributesParsed = 1 << 1,
2301280031Sdim    AR_CXX11AttributesParsed = 1 << 2,
2302280031Sdim    AR_DeclspecAttributesParsed = 1 << 3,
2303280031Sdim    AR_AllAttributesParsed = AR_GNUAttributesParsed |
2304280031Sdim                             AR_CXX11AttributesParsed |
2305280031Sdim                             AR_DeclspecAttributesParsed,
2306280031Sdim    AR_VendorAttributesParsed = AR_GNUAttributesParsed |
2307280031Sdim                                AR_DeclspecAttributesParsed
2308280031Sdim  };
2309280031Sdim
2310280031Sdim  void ParseTypeQualifierListOpt(DeclSpec &DS,
2311280031Sdim                                 unsigned AttrReqs = AR_AllAttributesParsed,
2312261991Sdim                                 bool AtomicAllowed = true,
2313261991Sdim                                 bool IdentifierRequired = false);
2314193326Sed  void ParseDirectDeclarator(Declarator &D);
2315193326Sed  void ParseParenDeclarator(Declarator &D);
2316226633Sdim  void ParseFunctionDeclarator(Declarator &D,
2317218893Sdim                               ParsedAttributes &attrs,
2318226633Sdim                               BalancedDelimiterTracker &Tracker,
2319239462Sdim                               bool IsAmbiguous,
2320193326Sed                               bool RequiresArg = false);
2321288943Sdim  bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
2322288943Sdim                         SourceLocation &RefQualifierLoc);
2323224145Sdim  bool isFunctionDeclaratorIdentifierList();
2324224145Sdim  void ParseFunctionDeclaratorIdentifierList(
2325224145Sdim         Declarator &D,
2326261991Sdim         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2327224145Sdim  void ParseParameterDeclarationClause(
2328224145Sdim         Declarator &D,
2329224145Sdim         ParsedAttributes &attrs,
2330261991Sdim         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2331224145Sdim         SourceLocation &EllipsisLoc);
2332193326Sed  void ParseBracketDeclarator(Declarator &D);
2333276479Sdim  void ParseMisplacedBracketDeclarator(Declarator &D);
2334198092Srdivacky
2335193326Sed  //===--------------------------------------------------------------------===//
2336193326Sed  // C++ 7: Declarations [dcl.dcl]
2337198092Srdivacky
2338234353Sdim  /// The kind of attribute specifier we have found.
2339234353Sdim  enum CXX11AttributeKind {
2340234353Sdim    /// This is not an attribute specifier.
2341234353Sdim    CAK_NotAttributeSpecifier,
2342234353Sdim    /// This should be treated as an attribute-specifier.
2343234353Sdim    CAK_AttributeSpecifier,
2344234353Sdim    /// The next tokens are '[[', but this is not an attribute-specifier. This
2345234353Sdim    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2346234353Sdim    CAK_InvalidAttributeSpecifier
2347234353Sdim  };
2348234353Sdim  CXX11AttributeKind
2349234353Sdim  isCXX11AttributeSpecifier(bool Disambiguate = false,
2350234353Sdim                            bool OuterMightBeMessageSend = false);
2351234353Sdim
2352261991Sdim  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2353261991Sdim
2354296417Sdim  DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2355296417Sdim                                SourceLocation InlineLoc = SourceLocation());
2356223017Sdim  void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2357223017Sdim                           std::vector<IdentifierInfo*>& Ident,
2358223017Sdim                           std::vector<SourceLocation>& NamespaceLoc,
2359223017Sdim                           unsigned int index, SourceLocation& InlineLoc,
2360226633Sdim                           ParsedAttributes& attrs,
2361226633Sdim                           BalancedDelimiterTracker &Tracker);
2362212904Sdim  Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2363212904Sdim  Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2364218893Sdim                                         const ParsedTemplateInfo &TemplateInfo,
2365212904Sdim                                         SourceLocation &DeclEnd,
2366224145Sdim                                         ParsedAttributesWithRange &attrs,
2367276479Sdim                                         Decl **OwnedType = nullptr);
2368218893Sdim  Decl *ParseUsingDirective(unsigned Context,
2369218893Sdim                            SourceLocation UsingLoc,
2370218893Sdim                            SourceLocation &DeclEnd,
2371218893Sdim                            ParsedAttributes &attrs);
2372218893Sdim  Decl *ParseUsingDeclaration(unsigned Context,
2373218893Sdim                              const ParsedTemplateInfo &TemplateInfo,
2374218893Sdim                              SourceLocation UsingLoc,
2375212904Sdim                              SourceLocation &DeclEnd,
2376224145Sdim                              AccessSpecifier AS = AS_none,
2377276479Sdim                              Decl **OwnedType = nullptr);
2378212904Sdim  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2379212904Sdim  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2380212904Sdim                            SourceLocation AliasLoc, IdentifierInfo *Alias,
2381212904Sdim                            SourceLocation &DeclEnd);
2382198092Srdivacky
2383193326Sed  //===--------------------------------------------------------------------===//
2384193326Sed  // C++ 9: classes [class] and C structs/unions.
2385239462Sdim  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2386193326Sed  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2387234353Sdim                           DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2388234353Sdim                           AccessSpecifier AS, bool EnteringContext,
2389249423Sdim                           DeclSpecContext DSC,
2390249423Sdim                           ParsedAttributesWithRange &Attributes);
2391288943Sdim  void SkipCXXMemberSpecification(SourceLocation StartLoc,
2392288943Sdim                                  SourceLocation AttrFixitLoc,
2393288943Sdim                                  unsigned TagType,
2394288943Sdim                                  Decl *TagDecl);
2395249423Sdim  void ParseCXXMemberSpecification(SourceLocation StartLoc,
2396249423Sdim                                   SourceLocation AttrFixitLoc,
2397249423Sdim                                   ParsedAttributesWithRange &Attrs,
2398249423Sdim                                   unsigned TagType,
2399212904Sdim                                   Decl *TagDecl);
2400234353Sdim  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2401223017Sdim                                       SourceLocation &EqualLoc);
2402288943Sdim  bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
2403276479Sdim                                                 VirtSpecifiers &VS,
2404276479Sdim                                                 ExprResult &BitfieldSize,
2405276479Sdim                                                 LateParsedAttrList &LateAttrs);
2406288943Sdim  void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D,
2407288943Sdim                                                               VirtSpecifiers &VS);
2408296417Sdim  DeclGroupPtrTy ParseCXXClassMemberDeclaration(
2409296417Sdim      AccessSpecifier AS, AttributeList *Attr,
2410296417Sdim      const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2411296417Sdim      ParsingDeclRAIIObject *DiagsFromTParams = nullptr);
2412296417Sdim  DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas(
2413296417Sdim      AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2414296417Sdim      DeclSpec::TST TagType, Decl *TagDecl);
2415212904Sdim  void ParseConstructorInitializer(Decl *ConstructorDecl);
2416212904Sdim  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2417234982Sdim  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2418234982Sdim                                      Decl *ThisDecl);
2419193326Sed
2420193326Sed  //===--------------------------------------------------------------------===//
2421193326Sed  // C++ 10: Derived classes [class.derived]
2422234353Sdim  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2423234353Sdim                                    SourceLocation &EndLocation);
2424212904Sdim  void ParseBaseClause(Decl *ClassDecl);
2425212904Sdim  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2426193326Sed  AccessSpecifier getAccessSpecifierIfPresent() const;
2427193326Sed
2428234353Sdim  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2429234353Sdim                                    SourceLocation TemplateKWLoc,
2430198893Srdivacky                                    IdentifierInfo *Name,
2431198893Srdivacky                                    SourceLocation NameLoc,
2432198893Srdivacky                                    bool EnteringContext,
2433212904Sdim                                    ParsedType ObjectType,
2434204643Srdivacky                                    UnqualifiedId &Id,
2435234353Sdim                                    bool AssumeTemplateId);
2436198893Srdivacky  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2437212904Sdim                                  ParsedType ObjectType,
2438198893Srdivacky                                  UnqualifiedId &Result);
2439243830Sdim
2440249423Sdim  //===--------------------------------------------------------------------===//
2441249423Sdim  // OpenMP: Directives and clauses.
2442261991Sdim  /// \brief Parses declarative OpenMP directives.
2443249423Sdim  DeclGroupPtrTy ParseOpenMPDeclarativeDirective();
2444261991Sdim  /// \brief Parses simple list of variables.
2445261991Sdim  ///
2446261991Sdim  /// \param Kind Kind of the directive.
2447261991Sdim  /// \param [out] VarList List of referenced variables.
2448261991Sdim  /// \param AllowScopeSpecifier true, if the variables can have fully
2449261991Sdim  /// qualified names.
2450261991Sdim  ///
2451249423Sdim  bool ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind,
2452261991Sdim                                SmallVectorImpl<Expr *> &VarList,
2453261991Sdim                                bool AllowScopeSpecifier);
2454261991Sdim  /// \brief Parses declarative or executable directive.
2455276479Sdim  ///
2456296417Sdim  /// \param Allowed ACK_Any, if any directives are allowed,
2457296417Sdim  /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
2458296417Sdim  /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
2459296417Sdim  /// executable directives are allowed.
2460276479Sdim  ///
2461276479Sdim  StmtResult
2462296417Sdim  ParseOpenMPDeclarativeOrExecutableDirective(AllowedContsructsKind Allowed);
2463261991Sdim  /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2464261991Sdim  ///
2465261991Sdim  /// \param DKind Kind of current directive.
2466261991Sdim  /// \param CKind Kind of current clause.
2467261991Sdim  /// \param FirstClause true, if this is the first clause of a kind \a CKind
2468261991Sdim  /// in current directive.
2469261991Sdim  ///
2470261991Sdim  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2471261991Sdim                               OpenMPClauseKind CKind, bool FirstClause);
2472261991Sdim  /// \brief Parses clause with a single expression of a kind \a Kind.
2473261991Sdim  ///
2474261991Sdim  /// \param Kind Kind of current clause.
2475261991Sdim  ///
2476261991Sdim  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2477261991Sdim  /// \brief Parses simple clause of a kind \a Kind.
2478261991Sdim  ///
2479261991Sdim  /// \param Kind Kind of current clause.
2480261991Sdim  ///
2481261991Sdim  OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2482276479Sdim  /// \brief Parses clause with a single expression and an additional argument
2483276479Sdim  /// of a kind \a Kind.
2484276479Sdim  ///
2485276479Sdim  /// \param Kind Kind of current clause.
2486276479Sdim  ///
2487276479Sdim  OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind);
2488276479Sdim  /// \brief Parses clause without any additional arguments.
2489276479Sdim  ///
2490276479Sdim  /// \param Kind Kind of current clause.
2491276479Sdim  ///
2492276479Sdim  OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind);
2493261991Sdim  /// \brief Parses clause with the list of variables of a kind \a Kind.
2494261991Sdim  ///
2495261991Sdim  /// \param Kind Kind of current clause.
2496261991Sdim  ///
2497296417Sdim  OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
2498296417Sdim                                      OpenMPClauseKind Kind);
2499296417Sdim
2500243830Sdimpublic:
2501198893Srdivacky  bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2502198893Srdivacky                          bool AllowDestructorName,
2503198893Srdivacky                          bool AllowConstructorName,
2504212904Sdim                          ParsedType ObjectType,
2505234353Sdim                          SourceLocation& TemplateKWLoc,
2506198893Srdivacky                          UnqualifiedId &Result);
2507234353Sdim
2508243830Sdimprivate:
2509193326Sed  //===--------------------------------------------------------------------===//
2510193326Sed  // C++ 14: Templates [temp]
2511193326Sed
2512193326Sed  // C++ 14.1: Template Parameters [temp.param]
2513212904Sdim  Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2514276479Sdim                                          SourceLocation &DeclEnd,
2515276479Sdim                                          AccessSpecifier AS = AS_none,
2516276479Sdim                                          AttributeList *AccessAttrs = nullptr);
2517226633Sdim  Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2518193326Sed                                                 SourceLocation &DeclEnd,
2519226633Sdim                                                 AccessSpecifier AS,
2520226633Sdim                                                 AttributeList *AccessAttrs);
2521212904Sdim  Decl *ParseSingleDeclarationAfterTemplate(
2522193326Sed                                       unsigned Context,
2523193326Sed                                       const ParsedTemplateInfo &TemplateInfo,
2524212904Sdim                                       ParsingDeclRAIIObject &DiagsFromParams,
2525193326Sed                                       SourceLocation &DeclEnd,
2526226633Sdim                                       AccessSpecifier AS=AS_none,
2527276479Sdim                                       AttributeList *AccessAttrs = nullptr);
2528198092Srdivacky  bool ParseTemplateParameters(unsigned Depth,
2529226633Sdim                               SmallVectorImpl<Decl*> &TemplateParams,
2530198092Srdivacky                               SourceLocation &LAngleLoc,
2531193326Sed                               SourceLocation &RAngleLoc);
2532193326Sed  bool ParseTemplateParameterList(unsigned Depth,
2533226633Sdim                                  SmallVectorImpl<Decl*> &TemplateParams);
2534199990Srdivacky  bool isStartOfTemplateTypeParameter();
2535212904Sdim  Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2536212904Sdim  Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2537212904Sdim  Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2538212904Sdim  Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2539276479Sdim  void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
2540276479Sdim                                 SourceLocation CorrectLoc,
2541276479Sdim                                 bool AlreadyHasEllipsis,
2542276479Sdim                                 bool IdentifierHasName);
2543276479Sdim  void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
2544276479Sdim                                             Declarator &D);
2545193326Sed  // C++ 14.3: Template arguments [temp.arg]
2546226633Sdim  typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2547193326Sed
2548249423Sdim  bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2549288943Sdim                                      bool ConsumeLastToken,
2550288943Sdim                                      bool ObjCGenericList);
2551193326Sed  bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2552198092Srdivacky                                        SourceLocation TemplateNameLoc,
2553221345Sdim                                        const CXXScopeSpec &SS,
2554193326Sed                                        bool ConsumeLastToken,
2555193326Sed                                        SourceLocation &LAngleLoc,
2556193326Sed                                        TemplateArgList &TemplateArgs,
2557193326Sed                                        SourceLocation &RAngleLoc);
2558193326Sed
2559195099Sed  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2560221345Sdim                               CXXScopeSpec &SS,
2561234353Sdim                               SourceLocation TemplateKWLoc,
2562198893Srdivacky                               UnqualifiedId &TemplateName,
2563193326Sed                               bool AllowTypeAnnotation = true);
2564221345Sdim  void AnnotateTemplateIdTokenAsType();
2565208600Srdivacky  bool IsTemplateArgumentList(unsigned Skip = 0);
2566199482Srdivacky  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2567199482Srdivacky  ParsedTemplateArgument ParseTemplateTemplateArgument();
2568199482Srdivacky  ParsedTemplateArgument ParseTemplateArgument();
2569234353Sdim  Decl *ParseExplicitInstantiation(unsigned Context,
2570234353Sdim                                   SourceLocation ExternLoc,
2571234353Sdim                                   SourceLocation TemplateLoc,
2572234353Sdim                                   SourceLocation &DeclEnd,
2573234353Sdim                                   AccessSpecifier AS = AS_none);
2574193326Sed
2575193326Sed  //===--------------------------------------------------------------------===//
2576226633Sdim  // Modules
2577234353Sdim  DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2578296417Sdim  bool parseMisplacedModuleImport();
2579296417Sdim  bool tryParseMisplacedModuleImport() {
2580296417Sdim    tok::TokenKind Kind = Tok.getKind();
2581296417Sdim    if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end ||
2582296417Sdim        Kind == tok::annot_module_include)
2583296417Sdim      return parseMisplacedModuleImport();
2584296417Sdim    return false;
2585296417Sdim  }
2586234353Sdim
2587226633Sdim  //===--------------------------------------------------------------------===//
2588276479Sdim  // C++11/G++: Type Traits [Type-Traits.html in the GCC manual]
2589234353Sdim  ExprResult ParseTypeTrait();
2590234353Sdim
2591212904Sdim  //===--------------------------------------------------------------------===//
2592221345Sdim  // Embarcadero: Arary and Expression Traits
2593221345Sdim  ExprResult ParseArrayTypeTrait();
2594221345Sdim  ExprResult ParseExpressionTrait();
2595221345Sdim
2596221345Sdim  //===--------------------------------------------------------------------===//
2597212904Sdim  // Preprocessor code-completion pass-through
2598276479Sdim  void CodeCompleteDirective(bool InConditional) override;
2599276479Sdim  void CodeCompleteInConditionalExclusion() override;
2600276479Sdim  void CodeCompleteMacroName(bool IsDefinition) override;
2601276479Sdim  void CodeCompletePreprocessorExpression() override;
2602276479Sdim  void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo,
2603276479Sdim                                 unsigned ArgumentIndex) override;
2604276479Sdim  void CodeCompleteNaturalLanguage() override;
2605193326Sed};
2606193326Sed
2607193326Sed}  // end namespace clang
2608193326Sed
2609193326Sed#endif
2610