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"
23212904Sdim#include "clang/Sema/Sema.h"
24193326Sed#include "llvm/ADT/OwningPtr.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"
29193326Sed#include <stack>
30193326Sed
31193326Sednamespace clang {
32193326Sed  class PragmaHandler;
33193326Sed  class Scope;
34239462Sdim  class BalancedDelimiterTracker;
35243830Sdim  class CorrectionCandidateCallback;
36212904Sdim  class DeclGroupRef;
37193326Sed  class DiagnosticBuilder;
38193326Sed  class Parser;
39239462Sdim  class ParsingDeclRAIIObject;
40239462Sdim  class ParsingDeclSpec;
41239462Sdim  class ParsingDeclarator;
42239462Sdim  class ParsingFieldDeclarator;
43193326Sed  class PragmaUnusedHandler;
44200583Srdivacky  class ColonProtectionRAIIObject;
45218893Sdim  class InMessageExpressionRAIIObject;
46221345Sdim  class PoisonSEHIdentifiersRAIIObject;
47221345Sdim  class VersionTuple;
48263508Sdim  class OMPClause;
49234353Sdim
50193326Sed/// Parser - This implements a parser for the C family of languages.  After
51193326Sed/// parsing units of the grammar, productions are invoked to handle whatever has
52193326Sed/// been read.
53193326Sed///
54212904Sdimclass Parser : public CodeCompletionHandler {
55193326Sed  friend class PragmaUnusedHandler;
56200583Srdivacky  friend class ColonProtectionRAIIObject;
57218893Sdim  friend class InMessageExpressionRAIIObject;
58221345Sdim  friend class PoisonSEHIdentifiersRAIIObject;
59239462Sdim  friend class ObjCDeclContextSwitch;
60210299Sed  friend class ParenBraceBracketBalancer;
61239462Sdim  friend class BalancedDelimiterTracker;
62198092Srdivacky
63193326Sed  Preprocessor &PP;
64198092Srdivacky
65193326Sed  /// Tok - The current token we are peeking ahead.  All parsing methods assume
66193326Sed  /// that this is valid.
67193326Sed  Token Tok;
68198092Srdivacky
69193326Sed  // PrevTokLocation - The location of the token we previously
70193326Sed  // consumed. This token is used for diagnostics where we expected to
71193326Sed  // see a token following another token (e.g., the ';' at the end of
72193326Sed  // a statement).
73193326Sed  SourceLocation PrevTokLocation;
74193326Sed
75193326Sed  unsigned short ParenCount, BracketCount, BraceCount;
76239462Sdim
77193326Sed  /// Actions - These are the callbacks we invoke as we parse various constructs
78234353Sdim  /// in the file.
79212904Sdim  Sema &Actions;
80198092Srdivacky
81226633Sdim  DiagnosticsEngine &Diags;
82198092Srdivacky
83193326Sed  /// ScopeCache - Cache scopes to reduce malloc traffic.
84193326Sed  enum { ScopeCacheSize = 16 };
85193326Sed  unsigned NumCachedScopes;
86193326Sed  Scope *ScopeCache[ScopeCacheSize];
87193326Sed
88221345Sdim  /// Identifiers used for SEH handling in Borland. These are only
89221345Sdim  /// allowed in particular circumstances
90234353Sdim  // __except block
91234353Sdim  IdentifierInfo *Ident__exception_code,
92234353Sdim                 *Ident___exception_code,
93234353Sdim                 *Ident_GetExceptionCode;
94234353Sdim  // __except filter expression
95234353Sdim  IdentifierInfo *Ident__exception_info,
96234353Sdim                 *Ident___exception_info,
97234353Sdim                 *Ident_GetExceptionInfo;
98234353Sdim  // __finally
99234353Sdim  IdentifierInfo *Ident__abnormal_termination,
100234353Sdim                 *Ident___abnormal_termination,
101234353Sdim                 *Ident_AbnormalTermination;
102221345Sdim
103234353Sdim  /// Contextual keywords for Microsoft extensions.
104234353Sdim  IdentifierInfo *Ident__except;
105263508Sdim  mutable IdentifierInfo *Ident_sealed;
106234353Sdim
107193326Sed  /// Ident_super - IdentifierInfo for "super", to support fast
108193326Sed  /// comparison.
109193326Sed  IdentifierInfo *Ident_super;
110263508Sdim  /// Ident_vector, Ident_pixel, Ident_bool - cached IdentifierInfo's
111263508Sdim  /// for "vector", "pixel", and "bool" fast comparison.  Only present
112263508Sdim  /// if AltiVec enabled.
113203955Srdivacky  IdentifierInfo *Ident_vector;
114203955Srdivacky  IdentifierInfo *Ident_pixel;
115263508Sdim  IdentifierInfo *Ident_bool;
116193326Sed
117226633Sdim  /// Objective-C contextual keywords.
118226633Sdim  mutable IdentifierInfo *Ident_instancetype;
119234353Sdim
120221345Sdim  /// \brief Identifier for "introduced".
121221345Sdim  IdentifierInfo *Ident_introduced;
122221345Sdim
123221345Sdim  /// \brief Identifier for "deprecated".
124221345Sdim  IdentifierInfo *Ident_deprecated;
125221345Sdim
126221345Sdim  /// \brief Identifier for "obsoleted".
127221345Sdim  IdentifierInfo *Ident_obsoleted;
128221345Sdim
129221345Sdim  /// \brief Identifier for "unavailable".
130221345Sdim  IdentifierInfo *Ident_unavailable;
131234353Sdim
132234353Sdim  /// \brief Identifier for "message".
133234353Sdim  IdentifierInfo *Ident_message;
134221345Sdim
135234353Sdim  /// C++0x contextual keywords.
136218893Sdim  mutable IdentifierInfo *Ident_final;
137218893Sdim  mutable IdentifierInfo *Ident_override;
138218893Sdim
139243830Sdim  // C++ type trait keywords that have can be reverted to identifiers and
140243830Sdim  // still used as type traits.
141243830Sdim  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertableTypeTraits;
142243830Sdim
143234353Sdim  OwningPtr<PragmaHandler> AlignHandler;
144234353Sdim  OwningPtr<PragmaHandler> GCCVisibilityHandler;
145234353Sdim  OwningPtr<PragmaHandler> OptionsHandler;
146234353Sdim  OwningPtr<PragmaHandler> PackHandler;
147234353Sdim  OwningPtr<PragmaHandler> MSStructHandler;
148234353Sdim  OwningPtr<PragmaHandler> UnusedHandler;
149234353Sdim  OwningPtr<PragmaHandler> WeakHandler;
150234353Sdim  OwningPtr<PragmaHandler> RedefineExtnameHandler;
151234353Sdim  OwningPtr<PragmaHandler> FPContractHandler;
152234353Sdim  OwningPtr<PragmaHandler> OpenCLExtensionHandler;
153239462Sdim  OwningPtr<CommentHandler> CommentSemaHandler;
154249423Sdim  OwningPtr<PragmaHandler> OpenMPHandler;
155251662Sdim  OwningPtr<PragmaHandler> MSCommentHandler;
156263508Sdim  OwningPtr<PragmaHandler> MSDetectMismatchHandler;
157198092Srdivacky
158193326Sed  /// Whether the '>' token acts as an operator or not. This will be
159193326Sed  /// true except when we are parsing an expression within a C++
160193326Sed  /// template argument list, where the '>' closes the template
161193326Sed  /// argument list.
162193326Sed  bool GreaterThanIsOperator;
163234353Sdim
164200583Srdivacky  /// ColonIsSacred - When this is false, we aggressively try to recover from
165200583Srdivacky  /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
166200583Srdivacky  /// safe in case statements and a few other things.  This is managed by the
167200583Srdivacky  /// ColonProtectionRAIIObject RAII object.
168200583Srdivacky  bool ColonIsSacred;
169193326Sed
170234353Sdim  /// \brief When true, we are directly inside an Objective-C messsage
171218893Sdim  /// send expression.
172218893Sdim  ///
173218893Sdim  /// This is managed by the \c InMessageExpressionRAIIObject class, and
174218893Sdim  /// should not be set directly.
175218893Sdim  bool InMessageExpression;
176234353Sdim
177198092Srdivacky  /// The "depth" of the template parameters currently being parsed.
178198092Srdivacky  unsigned TemplateParameterDepth;
179234353Sdim
180251662Sdim  /// \brief RAII class that manages the template parameter depth.
181251662Sdim  class TemplateParameterDepthRAII {
182251662Sdim    unsigned &Depth;
183251662Sdim    unsigned AddedLevels;
184251662Sdim  public:
185251662Sdim    explicit TemplateParameterDepthRAII(unsigned &Depth)
186251662Sdim      : Depth(Depth), AddedLevels(0) {}
187251662Sdim
188251662Sdim    ~TemplateParameterDepthRAII() {
189251662Sdim      Depth -= AddedLevels;
190251662Sdim    }
191251662Sdim
192251662Sdim    void operator++() {
193251662Sdim      ++Depth;
194251662Sdim      ++AddedLevels;
195251662Sdim    }
196251662Sdim    unsigned getDepth() const { return Depth; }
197251662Sdim  };
198251662Sdim
199218893Sdim  /// Factory object for creating AttributeList objects.
200221345Sdim  AttributeFactory AttrFactory;
201198092Srdivacky
202234982Sdim  /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
203234982Sdim  /// top-level declaration is finished.
204234982Sdim  SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
205224145Sdim
206243830Sdim  /// \brief Identifiers which have been declared within a tentative parse.
207243830Sdim  SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
208243830Sdim
209234353Sdim  IdentifierInfo *getSEHExceptKeyword();
210234353Sdim
211239462Sdim  /// True if we are within an Objective-C container while parsing C-like decls.
212239462Sdim  ///
213239462Sdim  /// This is necessary because Sema thinks we have left the container
214239462Sdim  /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
215239462Sdim  /// be NULL.
216239462Sdim  bool ParsingInObjCContainer;
217239462Sdim
218234353Sdim  bool SkipFunctionBodies;
219234353Sdim
220193326Sedpublic:
221234353Sdim  Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
222193326Sed  ~Parser();
223193326Sed
224234353Sdim  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
225199482Srdivacky  const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
226193326Sed  Preprocessor &getPreprocessor() const { return PP; }
227212904Sdim  Sema &getActions() const { return Actions; }
228239462Sdim  AttributeFactory &getAttrFactory() { return AttrFactory; }
229198092Srdivacky
230193326Sed  const Token &getCurToken() const { return Tok; }
231210299Sed  Scope *getCurScope() const { return Actions.getCurScope(); }
232234353Sdim
233226633Sdim  Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
234234353Sdim
235193326Sed  // Type forwarding.  All of these are statically 'void*', but they may all be
236193326Sed  // different actual classes based on the actions in place.
237212904Sdim  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
238212904Sdim  typedef OpaquePtr<TemplateName> TemplateTy;
239193326Sed
240226633Sdim  typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
241193326Sed
242212904Sdim  typedef clang::ExprResult        ExprResult;
243212904Sdim  typedef clang::StmtResult        StmtResult;
244212904Sdim  typedef clang::BaseResult        BaseResult;
245212904Sdim  typedef clang::MemInitResult     MemInitResult;
246212904Sdim  typedef clang::TypeResult        TypeResult;
247193326Sed
248212904Sdim  typedef Expr *ExprArg;
249243830Sdim  typedef llvm::MutableArrayRef<Stmt*> MultiStmtArg;
250212904Sdim  typedef Sema::FullExprArg FullExprArg;
251193326Sed
252212904Sdim  ExprResult ExprError() { return ExprResult(true); }
253212904Sdim  StmtResult StmtError() { return StmtResult(true); }
254193326Sed
255212904Sdim  ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
256212904Sdim  StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
257193326Sed
258212904Sdim  ExprResult ExprEmpty() { return ExprResult(false); }
259193326Sed
260193326Sed  // Parsing methods.
261198092Srdivacky
262193326Sed  /// Initialize - Warm up the parser.
263193326Sed  ///
264193326Sed  void Initialize();
265198092Srdivacky
266198092Srdivacky  /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
267193326Sed  /// the EOF was encountered.
268193326Sed  bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
269198092Srdivacky
270243830Sdim  /// ConsumeToken - Consume the current 'peek token' and lex the next one.
271243830Sdim  /// This does not work with all kinds of tokens: strings and specific other
272243830Sdim  /// tokens must be consumed with custom methods below.  This returns the
273243830Sdim  /// location of the consumed token.
274249423Sdim  SourceLocation ConsumeToken(bool ConsumeCodeCompletionTok = false) {
275243830Sdim    assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
276243830Sdim           !isTokenBrace() &&
277243830Sdim           "Should consume special tokens with Consume*Token");
278243830Sdim
279249423Sdim    if (!ConsumeCodeCompletionTok && Tok.is(tok::code_completion))
280243830Sdim      return handleUnexpectedCodeCompletionToken();
281243830Sdim
282243830Sdim    PrevTokLocation = Tok.getLocation();
283243830Sdim    PP.Lex(Tok);
284243830Sdim    return PrevTokLocation;
285243830Sdim  }
286243830Sdim
287193326Sedprivate:
288193326Sed  //===--------------------------------------------------------------------===//
289193326Sed  // Low-Level token peeking and consumption methods.
290193326Sed  //
291198092Srdivacky
292193326Sed  /// isTokenParen - Return true if the cur token is '(' or ')'.
293193326Sed  bool isTokenParen() const {
294193326Sed    return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
295193326Sed  }
296193326Sed  /// isTokenBracket - Return true if the cur token is '[' or ']'.
297193326Sed  bool isTokenBracket() const {
298193326Sed    return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
299193326Sed  }
300193326Sed  /// isTokenBrace - Return true if the cur token is '{' or '}'.
301193326Sed  bool isTokenBrace() const {
302193326Sed    return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
303193326Sed  }
304198092Srdivacky
305193326Sed  /// isTokenStringLiteral - True if this token is a string-literal.
306193326Sed  ///
307193326Sed  bool isTokenStringLiteral() const {
308249423Sdim    return tok::isStringLiteral(Tok.getKind());
309193326Sed  }
310193326Sed
311234353Sdim  /// \brief Returns true if the current token is '=' or is a type of '='.
312234353Sdim  /// For typos, give a fixit to '='
313234353Sdim  bool isTokenEqualOrEqualTypo();
314218893Sdim
315193326Sed  /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
316193326Sed  /// current token type.  This should only be used in cases where the type of
317193326Sed  /// the token really isn't known, e.g. in error recovery.
318249423Sdim  SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) {
319193326Sed    if (isTokenParen())
320193326Sed      return ConsumeParen();
321193326Sed    else if (isTokenBracket())
322193326Sed      return ConsumeBracket();
323193326Sed    else if (isTokenBrace())
324193326Sed      return ConsumeBrace();
325193326Sed    else if (isTokenStringLiteral())
326193326Sed      return ConsumeStringToken();
327193326Sed    else
328249423Sdim      return ConsumeToken(ConsumeCodeCompletionTok);
329193326Sed  }
330198092Srdivacky
331193326Sed  /// ConsumeParen - This consume method keeps the paren count up-to-date.
332193326Sed  ///
333193326Sed  SourceLocation ConsumeParen() {
334193326Sed    assert(isTokenParen() && "wrong consume method");
335193326Sed    if (Tok.getKind() == tok::l_paren)
336193326Sed      ++ParenCount;
337193326Sed    else if (ParenCount)
338193326Sed      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
339193326Sed    PrevTokLocation = Tok.getLocation();
340193326Sed    PP.Lex(Tok);
341193326Sed    return PrevTokLocation;
342193326Sed  }
343198092Srdivacky
344193326Sed  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
345193326Sed  ///
346193326Sed  SourceLocation ConsumeBracket() {
347193326Sed    assert(isTokenBracket() && "wrong consume method");
348193326Sed    if (Tok.getKind() == tok::l_square)
349193326Sed      ++BracketCount;
350193326Sed    else if (BracketCount)
351193326Sed      --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
352198092Srdivacky
353193326Sed    PrevTokLocation = Tok.getLocation();
354193326Sed    PP.Lex(Tok);
355193326Sed    return PrevTokLocation;
356193326Sed  }
357198092Srdivacky
358193326Sed  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
359193326Sed  ///
360193326Sed  SourceLocation ConsumeBrace() {
361193326Sed    assert(isTokenBrace() && "wrong consume method");
362193326Sed    if (Tok.getKind() == tok::l_brace)
363193326Sed      ++BraceCount;
364193326Sed    else if (BraceCount)
365193326Sed      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
366198092Srdivacky
367193326Sed    PrevTokLocation = Tok.getLocation();
368193326Sed    PP.Lex(Tok);
369193326Sed    return PrevTokLocation;
370193326Sed  }
371198092Srdivacky
372193326Sed  /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
373193326Sed  /// and returning the token kind.  This method is specific to strings, as it
374193326Sed  /// handles string literal concatenation, as per C99 5.1.1.2, translation
375193326Sed  /// phase #6.
376193326Sed  SourceLocation ConsumeStringToken() {
377193326Sed    assert(isTokenStringLiteral() &&
378193326Sed           "Should only consume string literals with this method");
379193326Sed    PrevTokLocation = Tok.getLocation();
380193326Sed    PP.Lex(Tok);
381193326Sed    return PrevTokLocation;
382193326Sed  }
383198092Srdivacky
384208600Srdivacky  /// \brief Consume the current code-completion token.
385208600Srdivacky  ///
386208600Srdivacky  /// This routine should be called to consume the code-completion token once
387208600Srdivacky  /// a code-completion action has already been invoked.
388208600Srdivacky  SourceLocation ConsumeCodeCompletionToken() {
389208600Srdivacky    assert(Tok.is(tok::code_completion));
390208600Srdivacky    PrevTokLocation = Tok.getLocation();
391208600Srdivacky    PP.Lex(Tok);
392234353Sdim    return PrevTokLocation;
393208600Srdivacky  }
394234353Sdim
395226633Sdim  ///\ brief When we are consuming a code-completion token without having
396208600Srdivacky  /// matched specific position in the grammar, provide code-completion results
397208600Srdivacky  /// based on context.
398226633Sdim  ///
399226633Sdim  /// \returns the source location of the code-completion token.
400226633Sdim  SourceLocation handleUnexpectedCodeCompletionToken();
401208600Srdivacky
402226633Sdim  /// \brief Abruptly cut off parsing; mainly used when we have reached the
403226633Sdim  /// code-completion point.
404226633Sdim  void cutOffParsing() {
405263508Sdim    if (PP.isCodeCompletionEnabled())
406263508Sdim      PP.setCodeCompletionReached();
407226633Sdim    // Cut off parsing by acting as if we reached the end-of-file.
408226633Sdim    Tok.setKind(tok::eof);
409226633Sdim  }
410226633Sdim
411218893Sdim  /// \brief Handle the annotation token produced for #pragma unused(...)
412218893Sdim  void HandlePragmaUnused();
413218893Sdim
414234353Sdim  /// \brief Handle the annotation token produced for
415234353Sdim  /// #pragma GCC visibility...
416234353Sdim  void HandlePragmaVisibility();
417234353Sdim
418234353Sdim  /// \brief Handle the annotation token produced for
419234353Sdim  /// #pragma pack...
420234353Sdim  void HandlePragmaPack();
421234353Sdim
422243830Sdim  /// \brief Handle the annotation token produced for
423243830Sdim  /// #pragma ms_struct...
424243830Sdim  void HandlePragmaMSStruct();
425243830Sdim
426243830Sdim  /// \brief Handle the annotation token produced for
427263508Sdim  /// #pragma comment...
428263508Sdim  void HandlePragmaMSComment();
429263508Sdim
430263508Sdim  /// \brief Handle the annotation token produced for
431243830Sdim  /// #pragma align...
432243830Sdim  void HandlePragmaAlign();
433243830Sdim
434243830Sdim  /// \brief Handle the annotation token produced for
435243830Sdim  /// #pragma weak id...
436243830Sdim  void HandlePragmaWeak();
437243830Sdim
438243830Sdim  /// \brief Handle the annotation token produced for
439243830Sdim  /// #pragma weak id = id...
440243830Sdim  void HandlePragmaWeakAlias();
441243830Sdim
442243830Sdim  /// \brief Handle the annotation token produced for
443243830Sdim  /// #pragma redefine_extname...
444243830Sdim  void HandlePragmaRedefineExtname();
445243830Sdim
446243830Sdim  /// \brief Handle the annotation token produced for
447243830Sdim  /// #pragma STDC FP_CONTRACT...
448243830Sdim  void HandlePragmaFPContract();
449243830Sdim
450243830Sdim  /// \brief Handle the annotation token produced for
451243830Sdim  /// #pragma OPENCL EXTENSION...
452243830Sdim  void HandlePragmaOpenCLExtension();
453243830Sdim
454251662Sdim  /// \brief Handle the annotation token produced for
455251662Sdim  /// #pragma clang __debug captured
456251662Sdim  StmtResult HandlePragmaCaptured();
457251662Sdim
458193326Sed  /// GetLookAheadToken - This peeks ahead N tokens and returns that token
459193326Sed  /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
460193326Sed  /// returns the token after Tok, etc.
461193326Sed  ///
462193326Sed  /// Note that this differs from the Preprocessor's LookAhead method, because
463193326Sed  /// the Parser always has one token lexed that the preprocessor doesn't.
464193326Sed  ///
465193326Sed  const Token &GetLookAheadToken(unsigned N) {
466193326Sed    if (N == 0 || Tok.is(tok::eof)) return Tok;
467193326Sed    return PP.LookAhead(N-1);
468193326Sed  }
469193326Sed
470243830Sdimpublic:
471193326Sed  /// NextToken - This peeks ahead one token and returns it without
472193326Sed  /// consuming it.
473193326Sed  const Token &NextToken() {
474193326Sed    return PP.LookAhead(0);
475193326Sed  }
476193326Sed
477212904Sdim  /// getTypeAnnotation - Read a parsed type out of an annotation token.
478212904Sdim  static ParsedType getTypeAnnotation(Token &Tok) {
479212904Sdim    return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
480212904Sdim  }
481212904Sdim
482243830Sdimprivate:
483212904Sdim  static void setTypeAnnotation(Token &Tok, ParsedType T) {
484212904Sdim    Tok.setAnnotationValue(T.getAsOpaquePtr());
485212904Sdim  }
486234353Sdim
487221345Sdim  /// \brief Read an already-translated primary expression out of an annotation
488221345Sdim  /// token.
489221345Sdim  static ExprResult getExprAnnotation(Token &Tok) {
490251662Sdim    return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue());
491221345Sdim  }
492234353Sdim
493221345Sdim  /// \brief Set the primary expression corresponding to the given annotation
494221345Sdim  /// token.
495221345Sdim  static void setExprAnnotation(Token &Tok, ExprResult ER) {
496251662Sdim    Tok.setAnnotationValue(ER.getAsOpaquePointer());
497221345Sdim  }
498212904Sdim
499243830Sdimpublic:
500226633Sdim  // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
501226633Sdim  // find a type name by attempting typo correction.
502226633Sdim  bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
503226633Sdim                                   bool NeedType = false);
504243830Sdim  bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
505243830Sdim                                                 bool NeedType,
506243830Sdim                                                 CXXScopeSpec &SS,
507243830Sdim                                                 bool IsNewScope);
508198092Srdivacky  bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
509193326Sed
510243830Sdimprivate:
511243830Sdim  enum AnnotatedNameKind {
512243830Sdim    /// Annotation has failed and emitted an error.
513243830Sdim    ANK_Error,
514243830Sdim    /// The identifier is a tentatively-declared name.
515243830Sdim    ANK_TentativeDecl,
516243830Sdim    /// The identifier is a template name. FIXME: Add an annotation for that.
517243830Sdim    ANK_TemplateName,
518243830Sdim    /// The identifier can't be resolved.
519243830Sdim    ANK_Unresolved,
520243830Sdim    /// Annotation was successful.
521243830Sdim    ANK_Success
522243830Sdim  };
523243830Sdim  AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand,
524243830Sdim                                    CorrectionCandidateCallback *CCC = 0);
525243830Sdim
526243830Sdim  /// Push a tok::annot_cxxscope token onto the token stream.
527243830Sdim  void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
528243830Sdim
529203955Srdivacky  /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
530203955Srdivacky  /// replacing them with the non-context-sensitive keywords.  This returns
531203955Srdivacky  /// true if the token was replaced.
532203955Srdivacky  bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
533204643Srdivacky                       const char *&PrevSpec, unsigned &DiagID,
534204643Srdivacky                       bool &isInvalid) {
535234353Sdim    if (!getLangOpts().AltiVec ||
536204643Srdivacky        (Tok.getIdentifierInfo() != Ident_vector &&
537263508Sdim         Tok.getIdentifierInfo() != Ident_pixel &&
538263508Sdim         Tok.getIdentifierInfo() != Ident_bool))
539204643Srdivacky      return false;
540234353Sdim
541204643Srdivacky    return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
542203955Srdivacky  }
543203955Srdivacky
544203955Srdivacky  /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
545203955Srdivacky  /// identifier token, replacing it with the non-context-sensitive __vector.
546203955Srdivacky  /// This returns true if the token was replaced.
547203955Srdivacky  bool TryAltiVecVectorToken() {
548234353Sdim    if (!getLangOpts().AltiVec ||
549204643Srdivacky        Tok.getIdentifierInfo() != Ident_vector) return false;
550204643Srdivacky    return TryAltiVecVectorTokenOutOfLine();
551203955Srdivacky  }
552234353Sdim
553204643Srdivacky  bool TryAltiVecVectorTokenOutOfLine();
554204643Srdivacky  bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
555204643Srdivacky                                const char *&PrevSpec, unsigned &DiagID,
556204643Srdivacky                                bool &isInvalid);
557224145Sdim
558263508Sdim  /// TryKeywordIdentFallback - For compatibility with system headers using
559263508Sdim  /// keywords as identifiers, attempt to convert the current token to an
560263508Sdim  /// identifier and optionally disable the keyword for the remainder of the
561263508Sdim  /// translation unit. This returns false if the token was not replaced,
562263508Sdim  /// otherwise emits a diagnostic and returns true.
563263508Sdim  bool TryKeywordIdentFallback(bool DisableKeyword);
564263508Sdim
565234982Sdim  /// \brief Get the TemplateIdAnnotation from the token.
566224145Sdim  TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
567224145Sdim
568193326Sed  /// TentativeParsingAction - An object that is used as a kind of "tentative
569193326Sed  /// parsing transaction". It gets instantiated to mark the token position and
570193326Sed  /// after the token consumption is done, Commit() or Revert() is called to
571193326Sed  /// either "commit the consumed tokens" or revert to the previously marked
572193326Sed  /// token position. Example:
573193326Sed  ///
574199482Srdivacky  ///   TentativeParsingAction TPA(*this);
575193326Sed  ///   ConsumeToken();
576193326Sed  ///   ....
577193326Sed  ///   TPA.Revert();
578193326Sed  ///
579193326Sed  class TentativeParsingAction {
580193326Sed    Parser &P;
581193326Sed    Token PrevTok;
582243830Sdim    size_t PrevTentativelyDeclaredIdentifierCount;
583235864Sdim    unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
584193326Sed    bool isActive;
585193326Sed
586193326Sed  public:
587193326Sed    explicit TentativeParsingAction(Parser& p) : P(p) {
588193326Sed      PrevTok = P.Tok;
589243830Sdim      PrevTentativelyDeclaredIdentifierCount =
590243830Sdim          P.TentativelyDeclaredIdentifiers.size();
591235864Sdim      PrevParenCount = P.ParenCount;
592235864Sdim      PrevBracketCount = P.BracketCount;
593235864Sdim      PrevBraceCount = P.BraceCount;
594193326Sed      P.PP.EnableBacktrackAtThisPos();
595193326Sed      isActive = true;
596193326Sed    }
597193326Sed    void Commit() {
598193326Sed      assert(isActive && "Parsing action was finished!");
599243830Sdim      P.TentativelyDeclaredIdentifiers.resize(
600243830Sdim          PrevTentativelyDeclaredIdentifierCount);
601193326Sed      P.PP.CommitBacktrackedTokens();
602193326Sed      isActive = false;
603193326Sed    }
604193326Sed    void Revert() {
605193326Sed      assert(isActive && "Parsing action was finished!");
606193326Sed      P.PP.Backtrack();
607193326Sed      P.Tok = PrevTok;
608243830Sdim      P.TentativelyDeclaredIdentifiers.resize(
609243830Sdim          PrevTentativelyDeclaredIdentifierCount);
610235864Sdim      P.ParenCount = PrevParenCount;
611235864Sdim      P.BracketCount = PrevBracketCount;
612235864Sdim      P.BraceCount = PrevBraceCount;
613193326Sed      isActive = false;
614193326Sed    }
615193326Sed    ~TentativeParsingAction() {
616193326Sed      assert(!isActive && "Forgot to call Commit or Revert!");
617193326Sed    }
618193326Sed  };
619263508Sdim  class UnannotatedTentativeParsingAction;
620198092Srdivacky
621226633Sdim  /// ObjCDeclContextSwitch - An object used to switch context from
622226633Sdim  /// an objective-c decl context to its enclosing decl context and
623226633Sdim  /// back.
624226633Sdim  class ObjCDeclContextSwitch {
625226633Sdim    Parser &P;
626226633Sdim    Decl *DC;
627239462Sdim    SaveAndRestore<bool> WithinObjCContainer;
628226633Sdim  public:
629239462Sdim    explicit ObjCDeclContextSwitch(Parser &p)
630239462Sdim      : P(p), DC(p.getObjCDeclContext()),
631239462Sdim        WithinObjCContainer(P.ParsingInObjCContainer, DC != 0) {
632226633Sdim      if (DC)
633234353Sdim        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
634226633Sdim    }
635226633Sdim    ~ObjCDeclContextSwitch() {
636226633Sdim      if (DC)
637234353Sdim        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
638226633Sdim    }
639226633Sdim  };
640198092Srdivacky
641193326Sed  /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
642193326Sed  /// input.  If so, it is consumed and false is returned.
643193326Sed  ///
644193326Sed  /// If the input is malformed, this emits the specified diagnostic.  Next, if
645193326Sed  /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
646193326Sed  /// returned.
647193326Sed  bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
648193326Sed                        const char *DiagMsg = "",
649193326Sed                        tok::TokenKind SkipToTok = tok::unknown);
650193326Sed
651218893Sdim  /// \brief The parser expects a semicolon and, if present, will consume it.
652218893Sdim  ///
653218893Sdim  /// If the next token is not a semicolon, this emits the specified diagnostic,
654218893Sdim  /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
655218893Sdim  /// to the semicolon, consumes that extra token.
656218893Sdim  bool ExpectAndConsumeSemi(unsigned DiagID);
657234353Sdim
658239462Sdim  /// \brief The kind of extra semi diagnostic to emit.
659239462Sdim  enum ExtraSemiKind {
660239462Sdim    OutsideFunction = 0,
661239462Sdim    InsideStruct = 1,
662239462Sdim    InstanceVariableList = 2,
663239462Sdim    AfterMemberFunctionDefinition = 3
664239462Sdim  };
665239462Sdim
666239462Sdim  /// \brief Consume any extra semi-colons until the end of the line.
667239462Sdim  void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
668239462Sdim
669243830Sdimpublic:
670193326Sed  //===--------------------------------------------------------------------===//
671193326Sed  // Scope manipulation
672198092Srdivacky
673193326Sed  /// ParseScope - Introduces a new scope for parsing. The kind of
674193326Sed  /// scope is determined by ScopeFlags. Objects of this type should
675193326Sed  /// be created on the stack to coincide with the position where the
676193326Sed  /// parser enters the new scope, and this object's constructor will
677193326Sed  /// create that new scope. Similarly, once the object is destroyed
678193326Sed  /// the parser will exit the scope.
679193326Sed  class ParseScope {
680193326Sed    Parser *Self;
681243830Sdim    ParseScope(const ParseScope &) LLVM_DELETED_FUNCTION;
682243830Sdim    void operator=(const ParseScope &) LLVM_DELETED_FUNCTION;
683193326Sed
684193326Sed  public:
685193326Sed    // ParseScope - Construct a new object to manage a scope in the
686193326Sed    // parser Self where the new Scope is created with the flags
687193326Sed    // ScopeFlags, but only when ManageScope is true (the default). If
688193326Sed    // ManageScope is false, this object does nothing.
689198092Srdivacky    ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
690193326Sed      : Self(Self) {
691193326Sed      if (ManageScope)
692193326Sed        Self->EnterScope(ScopeFlags);
693193326Sed      else
694193326Sed        this->Self = 0;
695193326Sed    }
696193326Sed
697193326Sed    // Exit - Exit the scope associated with this object now, rather
698193326Sed    // than waiting until the object is destroyed.
699193326Sed    void Exit() {
700193326Sed      if (Self) {
701193326Sed        Self->ExitScope();
702193326Sed        Self = 0;
703193326Sed      }
704193326Sed    }
705193326Sed
706193326Sed    ~ParseScope() {
707193326Sed      Exit();
708193326Sed    }
709193326Sed  };
710193326Sed
711193326Sed  /// EnterScope - Start a new scope.
712193326Sed  void EnterScope(unsigned ScopeFlags);
713198092Srdivacky
714193326Sed  /// ExitScope - Pop a scope off the scope stack.
715193326Sed  void ExitScope();
716193326Sed
717243830Sdimprivate:
718223017Sdim  /// \brief RAII object used to modify the scope flags for the current scope.
719223017Sdim  class ParseScopeFlags {
720223017Sdim    Scope *CurScope;
721223017Sdim    unsigned OldFlags;
722243830Sdim    ParseScopeFlags(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
723243830Sdim    void operator=(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
724223017Sdim
725223017Sdim  public:
726223017Sdim    ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
727223017Sdim    ~ParseScopeFlags();
728223017Sdim  };
729223017Sdim
730193326Sed  //===--------------------------------------------------------------------===//
731193326Sed  // Diagnostic Emission and Error recovery.
732193326Sed
733207619Srdivackypublic:
734193326Sed  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
735193326Sed  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
736239462Sdim  DiagnosticBuilder Diag(unsigned DiagID) {
737239462Sdim    return Diag(Tok, DiagID);
738239462Sdim  }
739193326Sed
740207619Srdivackyprivate:
741198092Srdivacky  void SuggestParentheses(SourceLocation Loc, unsigned DK,
742193326Sed                          SourceRange ParenRange);
743234353Sdim  void CheckNestedObjCContexts(SourceLocation AtLoc);
744193326Sed
745243830Sdimpublic:
746263508Sdim
747263508Sdim  /// \brief Control flags for SkipUntil functions.
748263508Sdim  enum SkipUntilFlags {
749263508Sdim    StopAtSemi = 1 << 0,  ///< Stop skipping at semicolon
750263508Sdim    /// \brief Stop skipping at specified token, but don't skip the token itself
751263508Sdim    StopBeforeMatch = 1 << 1,
752263508Sdim    StopAtCodeCompletion = 1 << 2 ///< Stop at code completion
753263508Sdim  };
754263508Sdim
755263508Sdim  friend LLVM_CONSTEXPR SkipUntilFlags operator|(SkipUntilFlags L,
756263508Sdim                                                 SkipUntilFlags R) {
757263508Sdim    return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) |
758263508Sdim                                       static_cast<unsigned>(R));
759263508Sdim  }
760263508Sdim
761193326Sed  /// SkipUntil - Read tokens until we get to the specified token, then consume
762263508Sdim  /// it (unless StopBeforeMatch is specified).  Because we cannot guarantee
763263508Sdim  /// that the token will ever occur, this skips to the next token, or to some
764263508Sdim  /// likely good stopping point.  If Flags has StopAtSemi flag, skipping will
765263508Sdim  /// stop at a ';' character.
766198092Srdivacky  ///
767193326Sed  /// If SkipUntil finds the specified token, it returns true, otherwise it
768198092Srdivacky  /// returns false.
769263508Sdim  bool SkipUntil(tok::TokenKind T,
770263508Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
771263508Sdim    return SkipUntil(llvm::makeArrayRef(T), Flags);
772193326Sed  }
773263508Sdim  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
774263508Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
775193326Sed    tok::TokenKind TokArray[] = {T1, T2};
776263508Sdim    return SkipUntil(TokArray, Flags);
777193326Sed  }
778234353Sdim  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
779263508Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
780234353Sdim    tok::TokenKind TokArray[] = {T1, T2, T3};
781263508Sdim    return SkipUntil(TokArray, Flags);
782234353Sdim  }
783263508Sdim  bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
784263508Sdim                 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
785193326Sed
786234353Sdim  /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
787234353Sdim  /// point for skipping past a simple-declaration.
788234353Sdim  void SkipMalformedDecl();
789234353Sdim
790243830Sdimprivate:
791193326Sed  //===--------------------------------------------------------------------===//
792193326Sed  // Lexing and parsing of C++ inline methods.
793193326Sed
794218893Sdim  struct ParsingClass;
795218893Sdim
796218893Sdim  /// [class.mem]p1: "... the class is regarded as complete within
797218893Sdim  /// - function bodies
798218893Sdim  /// - default arguments
799218893Sdim  /// - exception-specifications (TODO: C++0x)
800223017Sdim  /// - and brace-or-equal-initializers for non-static data members
801223017Sdim  /// (including such things in nested classes)."
802218893Sdim  /// LateParsedDeclarations build the tree of those elements so they can
803218893Sdim  /// be parsed after parsing the top-level class.
804218893Sdim  class LateParsedDeclaration {
805218893Sdim  public:
806218893Sdim    virtual ~LateParsedDeclaration();
807218893Sdim
808218893Sdim    virtual void ParseLexedMethodDeclarations();
809223017Sdim    virtual void ParseLexedMemberInitializers();
810218893Sdim    virtual void ParseLexedMethodDefs();
811226633Sdim    virtual void ParseLexedAttributes();
812218893Sdim  };
813218893Sdim
814218893Sdim  /// Inner node of the LateParsedDeclaration tree that parses
815218893Sdim  /// all its members recursively.
816218893Sdim  class LateParsedClass : public LateParsedDeclaration {
817218893Sdim  public:
818218893Sdim    LateParsedClass(Parser *P, ParsingClass *C);
819218893Sdim    virtual ~LateParsedClass();
820218893Sdim
821218893Sdim    virtual void ParseLexedMethodDeclarations();
822223017Sdim    virtual void ParseLexedMemberInitializers();
823218893Sdim    virtual void ParseLexedMethodDefs();
824226633Sdim    virtual void ParseLexedAttributes();
825218893Sdim
826218893Sdim  private:
827218893Sdim    Parser *Self;
828218893Sdim    ParsingClass *Class;
829218893Sdim  };
830218893Sdim
831234353Sdim  /// Contains the lexed tokens of an attribute with arguments that
832234353Sdim  /// may reference member variables and so need to be parsed at the
833234353Sdim  /// end of the class declaration after parsing all other member
834226633Sdim  /// member declarations.
835226633Sdim  /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
836226633Sdim  /// LateParsedTokens.
837226633Sdim  struct LateParsedAttribute : public LateParsedDeclaration {
838226633Sdim    Parser *Self;
839226633Sdim    CachedTokens Toks;
840226633Sdim    IdentifierInfo &AttrName;
841226633Sdim    SourceLocation AttrNameLoc;
842234353Sdim    SmallVector<Decl*, 2> Decls;
843226633Sdim
844234353Sdim    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
845226633Sdim                                 SourceLocation Loc)
846234353Sdim      : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
847226633Sdim
848226633Sdim    virtual void ParseLexedAttributes();
849226633Sdim
850234353Sdim    void addDecl(Decl *D) { Decls.push_back(D); }
851226633Sdim  };
852226633Sdim
853243830Sdim  // A list of late-parsed attributes.  Used by ParseGNUAttributes.
854249423Sdim  class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
855243830Sdim  public:
856243830Sdim    LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
857226633Sdim
858243830Sdim    bool parseSoon() { return ParseSoon; }
859226633Sdim
860243830Sdim  private:
861243830Sdim    bool ParseSoon;  // Are we planning to parse these shortly after creation?
862243830Sdim  };
863243830Sdim
864218893Sdim  /// Contains the lexed tokens of a member function definition
865218893Sdim  /// which needs to be parsed at the end of the class declaration
866218893Sdim  /// after parsing all other member declarations.
867218893Sdim  struct LexedMethod : public LateParsedDeclaration {
868218893Sdim    Parser *Self;
869212904Sdim    Decl *D;
870193326Sed    CachedTokens Toks;
871198092Srdivacky
872198092Srdivacky    /// \brief Whether this member function had an associated template
873198092Srdivacky    /// scope. When true, D is a template declaration.
874249423Sdim    /// otherwise, it is a member function declaration.
875198092Srdivacky    bool TemplateScope;
876198092Srdivacky
877218893Sdim    explicit LexedMethod(Parser* P, Decl *MD)
878218893Sdim      : Self(P), D(MD), TemplateScope(false) {}
879218893Sdim
880218893Sdim    virtual void ParseLexedMethodDefs();
881193326Sed  };
882193326Sed
883193326Sed  /// LateParsedDefaultArgument - Keeps track of a parameter that may
884193326Sed  /// have a default argument that cannot be parsed yet because it
885193326Sed  /// occurs within a member function declaration inside the class
886193326Sed  /// (C++ [class.mem]p2).
887193326Sed  struct LateParsedDefaultArgument {
888212904Sdim    explicit LateParsedDefaultArgument(Decl *P,
889193326Sed                                       CachedTokens *Toks = 0)
890193326Sed      : Param(P), Toks(Toks) { }
891193326Sed
892193326Sed    /// Param - The parameter declaration for this parameter.
893212904Sdim    Decl *Param;
894193326Sed
895193326Sed    /// Toks - The sequence of tokens that comprises the default
896193326Sed    /// argument expression, not including the '=' or the terminating
897193326Sed    /// ')' or ','. This will be NULL for parameters that have no
898193326Sed    /// default argument.
899193326Sed    CachedTokens *Toks;
900193326Sed  };
901198092Srdivacky
902193326Sed  /// LateParsedMethodDeclaration - A method declaration inside a class that
903193326Sed  /// contains at least one entity whose parsing needs to be delayed
904193326Sed  /// until the class itself is completely-defined, such as a default
905193326Sed  /// argument (C++ [class.mem]p2).
906218893Sdim  struct LateParsedMethodDeclaration : public LateParsedDeclaration {
907218893Sdim    explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
908234982Sdim      : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { }
909193326Sed
910218893Sdim    virtual void ParseLexedMethodDeclarations();
911218893Sdim
912218893Sdim    Parser* Self;
913218893Sdim
914193326Sed    /// Method - The method declaration.
915212904Sdim    Decl *Method;
916193326Sed
917198092Srdivacky    /// \brief Whether this member function had an associated template
918198092Srdivacky    /// scope. When true, D is a template declaration.
919198092Srdivacky    /// othewise, it is a member function declaration.
920198092Srdivacky    bool TemplateScope;
921198092Srdivacky
922193326Sed    /// DefaultArgs - Contains the parameters of the function and
923193326Sed    /// their default arguments. At least one of the parameters will
924193326Sed    /// have a default argument, but all of the parameters of the
925193326Sed    /// method will be stored so that they can be reintroduced into
926198092Srdivacky    /// scope at the appropriate times.
927226633Sdim    SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
928234982Sdim
929234982Sdim    /// \brief The set of tokens that make up an exception-specification that
930234982Sdim    /// has not yet been parsed.
931234982Sdim    CachedTokens *ExceptionSpecTokens;
932193326Sed  };
933193326Sed
934223017Sdim  /// LateParsedMemberInitializer - An initializer for a non-static class data
935223017Sdim  /// member whose parsing must to be delayed until the class is completely
936223017Sdim  /// defined (C++11 [class.mem]p2).
937223017Sdim  struct LateParsedMemberInitializer : public LateParsedDeclaration {
938223017Sdim    LateParsedMemberInitializer(Parser *P, Decl *FD)
939223017Sdim      : Self(P), Field(FD) { }
940223017Sdim
941223017Sdim    virtual void ParseLexedMemberInitializers();
942223017Sdim
943223017Sdim    Parser *Self;
944223017Sdim
945223017Sdim    /// Field - The field declaration.
946223017Sdim    Decl *Field;
947223017Sdim
948223017Sdim    /// CachedTokens - The sequence of tokens that comprises the initializer,
949223017Sdim    /// including any leading '='.
950223017Sdim    CachedTokens Toks;
951223017Sdim  };
952223017Sdim
953218893Sdim  /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
954218893Sdim  /// C++ class, its method declarations that contain parts that won't be
955221345Sdim  /// parsed until after the definition is completed (C++ [class.mem]p2),
956218893Sdim  /// the method declarations and possibly attached inline definitions
957234353Sdim  /// will be stored here with the tokens that will be parsed to create those
958234353Sdim  /// entities.
959234353Sdim  typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
960193326Sed
961193326Sed  /// \brief Representation of a class that has been parsed, including
962193326Sed  /// any member function declarations or definitions that need to be
963193326Sed  /// parsed after the corresponding top-level class is complete.
964193326Sed  struct ParsingClass {
965243830Sdim    ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
966198092Srdivacky      : TopLevelClass(TopLevelClass), TemplateScope(false),
967243830Sdim        IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
968193326Sed
969193326Sed    /// \brief Whether this is a "top-level" class, meaning that it is
970193326Sed    /// not nested within another class.
971193326Sed    bool TopLevelClass : 1;
972193326Sed
973193326Sed    /// \brief Whether this class had an associated template
974193326Sed    /// scope. When true, TagOrTemplate is a template declaration;
975193326Sed    /// othewise, it is a tag declaration.
976193326Sed    bool TemplateScope : 1;
977193326Sed
978243830Sdim    /// \brief Whether this class is an __interface.
979243830Sdim    bool IsInterface : 1;
980243830Sdim
981193326Sed    /// \brief The class or class template whose definition we are parsing.
982212904Sdim    Decl *TagOrTemplate;
983193326Sed
984218893Sdim    /// LateParsedDeclarations - Method declarations, inline definitions and
985218893Sdim    /// nested classes that contain pieces whose parsing will be delayed until
986218893Sdim    /// the top-level class is fully defined.
987218893Sdim    LateParsedDeclarationsContainer LateParsedDeclarations;
988193326Sed  };
989193326Sed
990193326Sed  /// \brief The stack of classes that is currently being
991193326Sed  /// parsed. Nested and local classes will be pushed onto this stack
992193326Sed  /// when they are parsed, and removed afterward.
993193326Sed  std::stack<ParsingClass *> ClassStack;
994193326Sed
995193326Sed  ParsingClass &getCurrentClass() {
996193326Sed    assert(!ClassStack.empty() && "No lexed method stacks!");
997193326Sed    return *ClassStack.top();
998193326Sed  }
999193326Sed
1000239462Sdim  /// \brief RAII object used to manage the parsing of a class definition.
1001193326Sed  class ParsingClassDefinition {
1002193326Sed    Parser &P;
1003193326Sed    bool Popped;
1004218893Sdim    Sema::ParsingClassState State;
1005193326Sed
1006193326Sed  public:
1007243830Sdim    ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
1008243830Sdim                           bool IsInterface)
1009218893Sdim      : P(P), Popped(false),
1010243830Sdim        State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
1011193326Sed    }
1012193326Sed
1013193326Sed    /// \brief Pop this class of the stack.
1014198092Srdivacky    void Pop() {
1015193326Sed      assert(!Popped && "Nested class has already been popped");
1016193326Sed      Popped = true;
1017218893Sdim      P.PopParsingClass(State);
1018193326Sed    }
1019193326Sed
1020198092Srdivacky    ~ParsingClassDefinition() {
1021193326Sed      if (!Popped)
1022218893Sdim        P.PopParsingClass(State);
1023193326Sed    }
1024193326Sed  };
1025193326Sed
1026193326Sed  /// \brief Contains information about any template-specific
1027193326Sed  /// information that has been parsed prior to parsing declaration
1028193326Sed  /// specifiers.
1029193326Sed  struct ParsedTemplateInfo {
1030198092Srdivacky    ParsedTemplateInfo()
1031193326Sed      : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
1032193326Sed
1033193326Sed    ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
1034198893Srdivacky                       bool isSpecialization,
1035198893Srdivacky                       bool lastParameterListWasEmpty = false)
1036193326Sed      : Kind(isSpecialization? ExplicitSpecialization : Template),
1037234353Sdim        TemplateParams(TemplateParams),
1038198893Srdivacky        LastParameterListWasEmpty(lastParameterListWasEmpty) { }
1039193326Sed
1040198092Srdivacky    explicit ParsedTemplateInfo(SourceLocation ExternLoc,
1041198092Srdivacky                                SourceLocation TemplateLoc)
1042198092Srdivacky      : Kind(ExplicitInstantiation), TemplateParams(0),
1043198893Srdivacky        ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
1044198893Srdivacky        LastParameterListWasEmpty(false){ }
1045193326Sed
1046193326Sed    /// \brief The kind of template we are parsing.
1047193326Sed    enum {
1048193326Sed      /// \brief We are not parsing a template at all.
1049193326Sed      NonTemplate = 0,
1050193326Sed      /// \brief We are parsing a template declaration.
1051193326Sed      Template,
1052193326Sed      /// \brief We are parsing an explicit specialization.
1053193326Sed      ExplicitSpecialization,
1054193326Sed      /// \brief We are parsing an explicit instantiation.
1055193326Sed      ExplicitInstantiation
1056193326Sed    } Kind;
1057193326Sed
1058193326Sed    /// \brief The template parameter lists, for template declarations
1059193326Sed    /// and explicit specializations.
1060193326Sed    TemplateParameterLists *TemplateParams;
1061193326Sed
1062198092Srdivacky    /// \brief The location of the 'extern' keyword, if any, for an explicit
1063198092Srdivacky    /// instantiation
1064198092Srdivacky    SourceLocation ExternLoc;
1065198092Srdivacky
1066193326Sed    /// \brief The location of the 'template' keyword, for an explicit
1067193326Sed    /// instantiation.
1068193326Sed    SourceLocation TemplateLoc;
1069234353Sdim
1070198893Srdivacky    /// \brief Whether the last template parameter list was empty.
1071198893Srdivacky    bool LastParameterListWasEmpty;
1072218893Sdim
1073234353Sdim    SourceRange getSourceRange() const LLVM_READONLY;
1074193326Sed  };
1075193326Sed
1076221345Sdim  void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
1077263508Sdim  void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
1078221345Sdim
1079263508Sdim  static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
1080221345Sdim
1081218893Sdim  Sema::ParsingClassState
1082243830Sdim  PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
1083198092Srdivacky  void DeallocateParsedClasses(ParsingClass *Class);
1084218893Sdim  void PopParsingClass(Sema::ParsingClassState);
1085198092Srdivacky
1086263508Sdim  enum CachedInitKind {
1087263508Sdim    CIK_DefaultArgument,
1088263508Sdim    CIK_DefaultInitializer
1089263508Sdim  };
1090263508Sdim
1091249423Sdim  NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
1092249423Sdim                                AttributeList *AccessAttrs,
1093226633Sdim                                ParsingDeclarator &D,
1094218893Sdim                                const ParsedTemplateInfo &TemplateInfo,
1095234353Sdim                                const VirtSpecifiers& VS,
1096234353Sdim                                FunctionDefinitionKind DefinitionKind,
1097234353Sdim                                ExprResult& Init);
1098223017Sdim  void ParseCXXNonStaticMemberInitializer(Decl *VarD);
1099226633Sdim  void ParseLexedAttributes(ParsingClass &Class);
1100234353Sdim  void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1101234353Sdim                               bool EnterScope, bool OnDefinition);
1102234353Sdim  void ParseLexedAttribute(LateParsedAttribute &LA,
1103234353Sdim                           bool EnterScope, bool OnDefinition);
1104198092Srdivacky  void ParseLexedMethodDeclarations(ParsingClass &Class);
1105218893Sdim  void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
1106198092Srdivacky  void ParseLexedMethodDefs(ParsingClass &Class);
1107218893Sdim  void ParseLexedMethodDef(LexedMethod &LM);
1108223017Sdim  void ParseLexedMemberInitializers(ParsingClass &Class);
1109223017Sdim  void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1110239462Sdim  void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
1111226633Sdim  bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
1112263508Sdim  bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK);
1113263508Sdim  bool ConsumeAndStoreConditional(CachedTokens &Toks);
1114207619Srdivacky  bool ConsumeAndStoreUntil(tok::TokenKind T1,
1115207619Srdivacky                            CachedTokens &Toks,
1116207619Srdivacky                            bool StopAtSemi = true,
1117207619Srdivacky                            bool ConsumeFinalToken = true) {
1118207619Srdivacky    return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1119207619Srdivacky  }
1120198092Srdivacky  bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1121198092Srdivacky                            CachedTokens &Toks,
1122207619Srdivacky                            bool StopAtSemi = true,
1123198092Srdivacky                            bool ConsumeFinalToken = true);
1124198092Srdivacky
1125193326Sed  //===--------------------------------------------------------------------===//
1126193326Sed  // C99 6.9: External Definitions.
1127218893Sdim  struct ParsedAttributesWithRange : ParsedAttributes {
1128221345Sdim    ParsedAttributesWithRange(AttributeFactory &factory)
1129221345Sdim      : ParsedAttributes(factory) {}
1130221345Sdim
1131218893Sdim    SourceRange Range;
1132218893Sdim  };
1133218893Sdim
1134218893Sdim  DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1135212904Sdim                                          ParsingDeclSpec *DS = 0);
1136223017Sdim  bool isDeclarationAfterDeclarator();
1137210299Sed  bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1138239462Sdim  DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
1139239462Sdim                                                  ParsedAttributesWithRange &attrs,
1140239462Sdim                                                  ParsingDeclSpec *DS = 0,
1141218893Sdim                                                  AccessSpecifier AS = AS_none);
1142239462Sdim  DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1143239462Sdim                                                ParsingDeclSpec &DS,
1144239462Sdim                                                AccessSpecifier AS);
1145234353Sdim
1146212904Sdim  Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1147234353Sdim                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1148234353Sdim                 LateParsedAttrList *LateParsedAttrs = 0);
1149193326Sed  void ParseKNRParamDeclarations(Declarator &D);
1150193326Sed  // EndLoc, if non-NULL, is filled with the location of the last token of
1151193326Sed  // the simple-asm.
1152212904Sdim  ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
1153212904Sdim  ExprResult ParseAsmStringLiteral();
1154193326Sed
1155193326Sed  // Objective-C External Declarations
1156249423Sdim  void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
1157234353Sdim  DeclGroupPtrTy ParseObjCAtDirectives();
1158234353Sdim  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
1159234353Sdim  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
1160218893Sdim                                        ParsedAttributes &prefixAttrs);
1161249423Sdim  void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1162249423Sdim                                        BalancedDelimiterTracker &T,
1163249423Sdim                                        SmallVectorImpl<Decl *> &AllIvarDecls,
1164249423Sdim                                        bool RBraceMissing);
1165212904Sdim  void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1166204643Srdivacky                                       tok::ObjCKeywordKind visibility,
1167193326Sed                                       SourceLocation atLoc);
1168226633Sdim  bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
1169226633Sdim                                   SmallVectorImpl<SourceLocation> &PLocs,
1170198092Srdivacky                                   bool WarnOnDeclarations,
1171198092Srdivacky                                   SourceLocation &LAngleLoc,
1172193326Sed                                   SourceLocation &EndProtoLoc);
1173218893Sdim  bool ParseObjCProtocolQualifiers(DeclSpec &DS);
1174226633Sdim  void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
1175226633Sdim                                  Decl *CDecl);
1176234353Sdim  DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1177234353Sdim                                                ParsedAttributes &prefixAttrs);
1178198092Srdivacky
1179234353Sdim  struct ObjCImplParsingDataRAII {
1180234353Sdim    Parser &P;
1181234353Sdim    Decl *Dcl;
1182239462Sdim    bool HasCFunction;
1183234353Sdim    typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
1184234353Sdim    LateParsedObjCMethodContainer LateParsedObjCMethods;
1185193326Sed
1186234353Sdim    ObjCImplParsingDataRAII(Parser &parser, Decl *D)
1187239462Sdim      : P(parser), Dcl(D), HasCFunction(false) {
1188234353Sdim      P.CurParsedObjCImpl = this;
1189234353Sdim      Finished = false;
1190234353Sdim    }
1191234353Sdim    ~ObjCImplParsingDataRAII();
1192234353Sdim
1193234353Sdim    void finish(SourceRange AtEnd);
1194234353Sdim    bool isFinished() const { return Finished; }
1195234353Sdim
1196234353Sdim  private:
1197234353Sdim    bool Finished;
1198234353Sdim  };
1199234353Sdim  ObjCImplParsingDataRAII *CurParsedObjCImpl;
1200239462Sdim  void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
1201234353Sdim
1202234353Sdim  DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
1203226633Sdim  DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
1204212904Sdim  Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1205212904Sdim  Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1206212904Sdim  Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1207198092Srdivacky
1208193326Sed  IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1209193326Sed  // Definitions for Objective-c context sensitive keywords recognition.
1210193326Sed  enum ObjCTypeQual {
1211193326Sed    objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1212193326Sed    objc_NumQuals
1213193326Sed  };
1214193326Sed  IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1215198092Srdivacky
1216193326Sed  bool isTokIdentifier_in() const;
1217193326Sed
1218226633Sdim  ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
1219226633Sdim                               ParsedAttributes *ParamAttrs);
1220193326Sed  void ParseObjCMethodRequirement();
1221226633Sdim  Decl *ParseObjCMethodPrototype(
1222221345Sdim            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1223221345Sdim            bool MethodDefinition = true);
1224212904Sdim  Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1225221345Sdim            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1226221345Sdim            bool MethodDefinition=true);
1227226633Sdim  void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
1228198092Srdivacky
1229212904Sdim  Decl *ParseObjCMethodDefinition();
1230198092Srdivacky
1231243830Sdimpublic:
1232193326Sed  //===--------------------------------------------------------------------===//
1233193326Sed  // C99 6.5: Expressions.
1234234353Sdim
1235234353Sdim  /// TypeCastState - State whether an expression is or may be a type cast.
1236234353Sdim  enum TypeCastState {
1237234353Sdim    NotTypeCast = 0,
1238234353Sdim    MaybeTypeCast,
1239234353Sdim    IsTypeCast
1240234353Sdim  };
1241234353Sdim
1242234353Sdim  ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
1243234353Sdim  ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
1244193326Sed  // Expr that doesn't include commas.
1245234353Sdim  ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
1246193326Sed
1247251662Sdim  ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
1248251662Sdim                                  unsigned &NumLineToksConsumed,
1249251662Sdim                                  void *Info,
1250251662Sdim                                  bool IsUnevaluated);
1251251662Sdim
1252243830Sdimprivate:
1253212904Sdim  ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1254193326Sed
1255212904Sdim  ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1256193326Sed
1257212904Sdim  ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1258221345Sdim                                        prec::Level MinPrec);
1259212904Sdim  ExprResult ParseCastExpression(bool isUnaryExpression,
1260221345Sdim                                 bool isAddressOfOperand,
1261221345Sdim                                 bool &NotCastExpr,
1262234353Sdim                                 TypeCastState isTypeCast);
1263212904Sdim  ExprResult ParseCastExpression(bool isUnaryExpression,
1264221345Sdim                                 bool isAddressOfOperand = false,
1265234353Sdim                                 TypeCastState isTypeCast = NotTypeCast);
1266198092Srdivacky
1267243830Sdim  /// Returns true if the next token cannot start an expression.
1268243830Sdim  bool isNotExpressionStart();
1269243830Sdim
1270212904Sdim  /// Returns true if the next token would start a postfix-expression
1271212904Sdim  /// suffix.
1272212904Sdim  bool isPostfixExpressionSuffixStart() {
1273212904Sdim    tok::TokenKind K = Tok.getKind();
1274212904Sdim    return (K == tok::l_square || K == tok::l_paren ||
1275212904Sdim            K == tok::period || K == tok::arrow ||
1276212904Sdim            K == tok::plusplus || K == tok::minusminus);
1277212904Sdim  }
1278212904Sdim
1279212904Sdim  ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1280221345Sdim  ExprResult ParseUnaryExprOrTypeTraitExpression();
1281212904Sdim  ExprResult ParseBuiltinPrimaryExpression();
1282212904Sdim
1283221345Sdim  ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1284193326Sed                                                     bool &isCastExpr,
1285212904Sdim                                                     ParsedType &CastTy,
1286193326Sed                                                     SourceRange &CastRange);
1287193326Sed
1288226633Sdim  typedef SmallVector<Expr*, 20> ExprListTy;
1289226633Sdim  typedef SmallVector<SourceLocation, 20> CommaLocsTy;
1290193326Sed
1291193326Sed  /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1292226633Sdim  bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
1293226633Sdim                           SmallVectorImpl<SourceLocation> &CommaLocs,
1294212904Sdim                           void (Sema::*Completer)(Scope *S,
1295212904Sdim                                                   Expr *Data,
1296249423Sdim                                                   ArrayRef<Expr *> Args) = 0,
1297212904Sdim                           Expr *Data = 0);
1298193326Sed
1299263508Sdim  /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
1300263508Sdim  /// used for misc language extensions.
1301263508Sdim  bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
1302263508Sdim                                 SmallVectorImpl<SourceLocation> &CommaLocs);
1303263508Sdim
1304263508Sdim
1305193326Sed  /// ParenParseOption - Control what ParseParenExpression will parse.
1306193326Sed  enum ParenParseOption {
1307193326Sed    SimpleExpr,      // Only parse '(' expression ')'
1308193326Sed    CompoundStmt,    // Also allow '(' compound-statement ')'
1309193326Sed    CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1310193326Sed    CastExpr         // Also allow '(' type-name ')' <anything>
1311193326Sed  };
1312212904Sdim  ExprResult ParseParenExpression(ParenParseOption &ExprType,
1313193326Sed                                        bool stopIfCastExpr,
1314224145Sdim                                        bool isTypeCast,
1315212904Sdim                                        ParsedType &CastTy,
1316193326Sed                                        SourceLocation &RParenLoc);
1317198092Srdivacky
1318212904Sdim  ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1319226633Sdim                                            ParsedType &CastTy,
1320226633Sdim                                            BalancedDelimiterTracker &Tracker);
1321212904Sdim  ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1322193326Sed                                                  SourceLocation LParenLoc,
1323193326Sed                                                  SourceLocation RParenLoc);
1324198092Srdivacky
1325234353Sdim  ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
1326193326Sed
1327221345Sdim  ExprResult ParseGenericSelectionExpression();
1328234353Sdim
1329234353Sdim  ExprResult ParseObjCBoolLiteral();
1330221345Sdim
1331193326Sed  //===--------------------------------------------------------------------===//
1332193326Sed  // C++ Expressions
1333212904Sdim  ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1334193326Sed
1335239462Sdim  bool areTokensAdjacent(const Token &A, const Token &B);
1336239462Sdim
1337226633Sdim  void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
1338226633Sdim                                  bool EnteringContext, IdentifierInfo &II,
1339226633Sdim                                  CXXScopeSpec &SS);
1340226633Sdim
1341198092Srdivacky  bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1342212904Sdim                                      ParsedType ObjectType,
1343204643Srdivacky                                      bool EnteringContext,
1344221345Sdim                                      bool *MayBePseudoDestructor = 0,
1345249423Sdim                                      bool IsTypename = false,
1346249423Sdim                                      IdentifierInfo **LastII = 0);
1347198092Srdivacky
1348243830Sdim  void CheckForLParenAfterColonColon();
1349243830Sdim
1350193326Sed  //===--------------------------------------------------------------------===//
1351226633Sdim  // C++0x 5.1.2: Lambda expressions
1352226633Sdim
1353226633Sdim  // [...] () -> type {...}
1354226633Sdim  ExprResult ParseLambdaExpression();
1355226633Sdim  ExprResult TryParseLambdaExpression();
1356263508Sdim  Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
1357263508Sdim                                           bool *SkippedInits = 0);
1358226633Sdim  bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
1359226633Sdim  ExprResult ParseLambdaExpressionAfterIntroducer(
1360226633Sdim               LambdaIntroducer &Intro);
1361226633Sdim
1362226633Sdim  //===--------------------------------------------------------------------===//
1363193326Sed  // C++ 5.2p1: C++ Casts
1364212904Sdim  ExprResult ParseCXXCasts();
1365193326Sed
1366193326Sed  //===--------------------------------------------------------------------===//
1367193326Sed  // C++ 5.2p1: C++ Type Identification
1368212904Sdim  ExprResult ParseCXXTypeid();
1369193326Sed
1370193326Sed  //===--------------------------------------------------------------------===//
1371218893Sdim  //  C++ : Microsoft __uuidof Expression
1372218893Sdim  ExprResult ParseCXXUuidof();
1373218893Sdim
1374218893Sdim  //===--------------------------------------------------------------------===//
1375204643Srdivacky  // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1376212904Sdim  ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1377204643Srdivacky                                            tok::TokenKind OpKind,
1378204643Srdivacky                                            CXXScopeSpec &SS,
1379212904Sdim                                            ParsedType ObjectType);
1380204643Srdivacky
1381204643Srdivacky  //===--------------------------------------------------------------------===//
1382193326Sed  // C++ 9.3.2: C++ 'this' pointer
1383212904Sdim  ExprResult ParseCXXThis();
1384193326Sed
1385193326Sed  //===--------------------------------------------------------------------===//
1386193326Sed  // C++ 15: C++ Throw Expression
1387212904Sdim  ExprResult ParseThrowExpression();
1388221345Sdim
1389234982Sdim  ExceptionSpecificationType tryParseExceptionSpecification(
1390221345Sdim                    SourceRange &SpecificationRange,
1391226633Sdim                    SmallVectorImpl<ParsedType> &DynamicExceptions,
1392226633Sdim                    SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1393235864Sdim                    ExprResult &NoexceptExpr);
1394221345Sdim
1395193326Sed  // EndLoc is filled with the location of the last token of the specification.
1396221345Sdim  ExceptionSpecificationType ParseDynamicExceptionSpecification(
1397221345Sdim                                  SourceRange &SpecificationRange,
1398226633Sdim                                  SmallVectorImpl<ParsedType> &Exceptions,
1399226633Sdim                                  SmallVectorImpl<SourceRange> &Ranges);
1400193326Sed
1401193326Sed  //===--------------------------------------------------------------------===//
1402218893Sdim  // C++0x 8: Function declaration trailing-return-type
1403226633Sdim  TypeResult ParseTrailingReturnType(SourceRange &Range);
1404218893Sdim
1405218893Sdim  //===--------------------------------------------------------------------===//
1406193326Sed  // C++ 2.13.5: C++ Boolean Literals
1407212904Sdim  ExprResult ParseCXXBoolLiteral();
1408193326Sed
1409193326Sed  //===--------------------------------------------------------------------===//
1410193326Sed  // C++ 5.2.3: Explicit type conversion (functional notation)
1411212904Sdim  ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1412193326Sed
1413193326Sed  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1414193326Sed  /// This should only be called when the current token is known to be part of
1415193326Sed  /// simple-type-specifier.
1416193326Sed  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1417193326Sed
1418193326Sed  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1419193326Sed
1420193326Sed  //===--------------------------------------------------------------------===//
1421193326Sed  // C++ 5.3.4 and 5.3.5: C++ new and delete
1422226633Sdim  bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
1423212904Sdim                                   Declarator &D);
1424193326Sed  void ParseDirectNewDeclarator(Declarator &D);
1425212904Sdim  ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1426212904Sdim  ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1427193326Sed                                            SourceLocation Start);
1428193326Sed
1429193326Sed  //===--------------------------------------------------------------------===//
1430199990Srdivacky  // C++ if/switch/while condition expression.
1431212904Sdim  bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1432208600Srdivacky                         SourceLocation Loc, bool ConvertToBoolean);
1433193326Sed
1434193326Sed  //===--------------------------------------------------------------------===//
1435193326Sed  // C++ types
1436193326Sed
1437193326Sed  //===--------------------------------------------------------------------===//
1438193326Sed  // C99 6.7.8: Initialization.
1439198092Srdivacky
1440193326Sed  /// ParseInitializer
1441193326Sed  ///       initializer: [C99 6.7.8]
1442193326Sed  ///         assignment-expression
1443193326Sed  ///         '{' ...
1444212904Sdim  ExprResult ParseInitializer() {
1445193326Sed    if (Tok.isNot(tok::l_brace))
1446193326Sed      return ParseAssignmentExpression();
1447193326Sed    return ParseBraceInitializer();
1448193326Sed  }
1449234353Sdim  bool MayBeDesignationStart();
1450212904Sdim  ExprResult ParseBraceInitializer();
1451212904Sdim  ExprResult ParseInitializerWithPotentialDesignator();
1452193326Sed
1453193326Sed  //===--------------------------------------------------------------------===//
1454193326Sed  // clang Expressions
1455193326Sed
1456212904Sdim  ExprResult ParseBlockLiteralExpression();  // ^{...}
1457193326Sed
1458193326Sed  //===--------------------------------------------------------------------===//
1459193326Sed  // Objective-C Expressions
1460212904Sdim  ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1461212904Sdim  ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1462234353Sdim  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
1463234353Sdim  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
1464234353Sdim  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
1465234353Sdim  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
1466234353Sdim  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
1467239462Sdim  ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
1468212904Sdim  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1469212904Sdim  ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1470212904Sdim  ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1471210299Sed  bool isSimpleObjCMessageExpression();
1472212904Sdim  ExprResult ParseObjCMessageExpression();
1473212904Sdim  ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1474234353Sdim                                            SourceLocation SuperLoc,
1475234353Sdim                                            ParsedType ReceiverType,
1476234353Sdim                                            ExprArg ReceiverExpr);
1477212904Sdim  ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1478207619Srdivacky      SourceLocation LBracloc, SourceLocation SuperLoc,
1479212904Sdim      ParsedType ReceiverType, ExprArg ReceiverExpr);
1480207619Srdivacky  bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1481234353Sdim
1482193326Sed  //===--------------------------------------------------------------------===//
1483193326Sed  // C99 6.8: Statements and Blocks.
1484193326Sed
1485243830Sdim  /// A SmallVector of statements, with stack size 32 (as that is the only one
1486243830Sdim  /// used.)
1487243830Sdim  typedef SmallVector<Stmt*, 32> StmtVector;
1488243830Sdim  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
1489243830Sdim  typedef SmallVector<Expr*, 12> ExprVector;
1490243830Sdim  /// A SmallVector of types.
1491243830Sdim  typedef SmallVector<ParsedType, 12> TypeVector;
1492243830Sdim
1493263508Sdim  StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0);
1494234982Sdim  StmtResult ParseStatementOrDeclaration(StmtVector &Stmts,
1495234353Sdim                                         bool OnlyStatement,
1496234982Sdim                                         SourceLocation *TrailingElseLoc = 0);
1497234982Sdim  StmtResult ParseStatementOrDeclarationAfterAttributes(
1498234982Sdim                                         StmtVector &Stmts,
1499234982Sdim                                         bool OnlyStatement,
1500234982Sdim                                         SourceLocation *TrailingElseLoc,
1501234982Sdim                                         ParsedAttributesWithRange &Attrs);
1502234982Sdim  StmtResult ParseExprStatement();
1503234982Sdim  StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
1504234982Sdim  StmtResult ParseCaseStatement(bool MissingCase = false,
1505221345Sdim                                ExprResult Expr = ExprResult());
1506234982Sdim  StmtResult ParseDefaultStatement();
1507234982Sdim  StmtResult ParseCompoundStatement(bool isStmtExpr = false);
1508234982Sdim  StmtResult ParseCompoundStatement(bool isStmtExpr,
1509224145Sdim                                    unsigned ScopeFlags);
1510243830Sdim  void ParseCompoundStatementLeadingPragmas();
1511212904Sdim  StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1512212904Sdim  bool ParseParenExprOrCondition(ExprResult &ExprResult,
1513212904Sdim                                 Decl *&DeclResult,
1514208600Srdivacky                                 SourceLocation Loc,
1515208600Srdivacky                                 bool ConvertToBoolean);
1516234982Sdim  StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
1517234982Sdim  StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
1518234982Sdim  StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
1519234982Sdim  StmtResult ParseDoStatement();
1520234982Sdim  StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
1521234982Sdim  StmtResult ParseGotoStatement();
1522234982Sdim  StmtResult ParseContinueStatement();
1523234982Sdim  StmtResult ParseBreakStatement();
1524234982Sdim  StmtResult ParseReturnStatement();
1525212904Sdim  StmtResult ParseAsmStatement(bool &msAsm);
1526226633Sdim  StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1527234353Sdim
1528234353Sdim  /// \brief Describes the behavior that should be taken for an __if_exists
1529234353Sdim  /// block.
1530234353Sdim  enum IfExistsBehavior {
1531234353Sdim    /// \brief Parse the block; this code is always used.
1532234353Sdim    IEB_Parse,
1533234353Sdim    /// \brief Skip the block entirely; this code is never used.
1534234353Sdim    IEB_Skip,
1535234353Sdim    /// \brief Parse the block as a dependent block, which may be used in
1536234353Sdim    /// some template instantiations but not others.
1537234353Sdim    IEB_Dependent
1538234353Sdim  };
1539234353Sdim
1540234353Sdim  /// \brief Describes the condition of a Microsoft __if_exists or
1541234353Sdim  /// __if_not_exists block.
1542234353Sdim  struct IfExistsCondition {
1543234353Sdim    /// \brief The location of the initial keyword.
1544234353Sdim    SourceLocation KeywordLoc;
1545234353Sdim    /// \brief Whether this is an __if_exists block (rather than an
1546234353Sdim    /// __if_not_exists block).
1547234353Sdim    bool IsIfExists;
1548234353Sdim
1549234353Sdim    /// \brief Nested-name-specifier preceding the name.
1550234353Sdim    CXXScopeSpec SS;
1551234353Sdim
1552234353Sdim    /// \brief The name we're looking for.
1553234353Sdim    UnqualifiedId Name;
1554234353Sdim
1555234353Sdim    /// \brief The behavior of this __if_exists or __if_not_exists block
1556234353Sdim    /// should.
1557234353Sdim    IfExistsBehavior Behavior;
1558234982Sdim  };
1559234353Sdim
1560234353Sdim  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
1561223017Sdim  void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1562223017Sdim  void ParseMicrosoftIfExistsExternalDeclaration();
1563223017Sdim  void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1564223017Sdim                                              AccessSpecifier& CurAS);
1565234353Sdim  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
1566234353Sdim                                              bool &InitExprsOk);
1567226633Sdim  bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
1568226633Sdim                           SmallVectorImpl<Expr *> &Constraints,
1569226633Sdim                           SmallVectorImpl<Expr *> &Exprs);
1570193326Sed
1571193326Sed  //===--------------------------------------------------------------------===//
1572193326Sed  // C++ 6: Statements and Blocks
1573193326Sed
1574234982Sdim  StmtResult ParseCXXTryBlock();
1575243830Sdim  StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
1576243830Sdim  StmtResult ParseCXXCatchBlock(bool FnCatch = false);
1577193326Sed
1578193326Sed  //===--------------------------------------------------------------------===//
1579221345Sdim  // MS: SEH Statements and Blocks
1580221345Sdim
1581234982Sdim  StmtResult ParseSEHTryBlock();
1582221345Sdim  StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
1583221345Sdim  StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1584221345Sdim  StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1585221345Sdim
1586221345Sdim  //===--------------------------------------------------------------------===//
1587193326Sed  // Objective-C Statements
1588193326Sed
1589212904Sdim  StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1590212904Sdim  StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1591212904Sdim  StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1592212904Sdim  StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1593224145Sdim  StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1594193326Sed
1595193326Sed
1596193326Sed  //===--------------------------------------------------------------------===//
1597193326Sed  // C99 6.7: Declarations.
1598198092Srdivacky
1599198092Srdivacky  /// A context for parsing declaration specifiers.  TODO: flesh this
1600198092Srdivacky  /// out, there are other significant restrictions on specifiers than
1601198092Srdivacky  /// would be best implemented in the parser.
1602198092Srdivacky  enum DeclSpecContext {
1603198092Srdivacky    DSC_normal, // normal context
1604202379Srdivacky    DSC_class,  // class context, enables 'friend'
1605239462Sdim    DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
1606234353Sdim    DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
1607202379Srdivacky    DSC_top_level // top-level/namespace declaration context
1608198092Srdivacky  };
1609198092Srdivacky
1610221345Sdim  /// Information on a C++0x for-range-initializer found while parsing a
1611221345Sdim  /// declaration which turns out to be a for-range-declaration.
1612221345Sdim  struct ForRangeInit {
1613221345Sdim    SourceLocation ColonLoc;
1614221345Sdim    ExprResult RangeExpr;
1615221345Sdim
1616221345Sdim    bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1617221345Sdim  };
1618221345Sdim
1619218893Sdim  DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
1620218893Sdim                                  unsigned Context, SourceLocation &DeclEnd,
1621218893Sdim                                  ParsedAttributesWithRange &attrs);
1622218893Sdim  DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
1623218893Sdim                                        unsigned Context,
1624199990Srdivacky                                        SourceLocation &DeclEnd,
1625239462Sdim                                        ParsedAttributesWithRange &attrs,
1626221345Sdim                                        bool RequireSemi,
1627221345Sdim                                        ForRangeInit *FRI = 0);
1628234353Sdim  bool MightBeDeclarator(unsigned Context);
1629198893Srdivacky  DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1630198893Srdivacky                                bool AllowFunctionDefinitions,
1631221345Sdim                                SourceLocation *DeclEnd = 0,
1632221345Sdim                                ForRangeInit *FRI = 0);
1633212904Sdim  Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1634195099Sed               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1635234353Sdim  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
1636221345Sdim  Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1637221345Sdim               const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1638221345Sdim  Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1639221345Sdim  Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1640193326Sed
1641218893Sdim  /// \brief When in code-completion, skip parsing of the function/method body
1642218893Sdim  /// unless the body contains the code-completion point.
1643218893Sdim  ///
1644218893Sdim  /// \returns true if the function body was skipped.
1645234353Sdim  bool trySkippingFunctionBody();
1646218893Sdim
1647193326Sed  bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1648193326Sed                        const ParsedTemplateInfo &TemplateInfo,
1649249423Sdim                        AccessSpecifier AS, DeclSpecContext DSC,
1650249423Sdim                        ParsedAttributesWithRange &Attrs);
1651202379Srdivacky  DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1652198092Srdivacky  void ParseDeclarationSpecifiers(DeclSpec &DS,
1653193326Sed                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1654198092Srdivacky                                  AccessSpecifier AS = AS_none,
1655234353Sdim                                  DeclSpecContext DSC = DSC_normal,
1656234353Sdim                                  LateParsedAttrList *LateAttrs = 0);
1657263508Sdim  bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
1658263508Sdim                                             DeclSpecContext DSContext,
1659263508Sdim                                             LateParsedAttrList *LateAttrs = 0);
1660193326Sed
1661234353Sdim  void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
1662234353Sdim                                   DeclSpecContext DSC = DSC_normal);
1663198092Srdivacky
1664226633Sdim  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1665226633Sdim                                  Declarator::TheContext Context);
1666193326Sed
1667193326Sed  void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1668234353Sdim                          const ParsedTemplateInfo &TemplateInfo,
1669234353Sdim                          AccessSpecifier AS, DeclSpecContext DSC);
1670212904Sdim  void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1671193326Sed  void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1672212904Sdim                            Decl *TagDecl);
1673198092Srdivacky
1674198893Srdivacky  struct FieldCallback {
1675239462Sdim    virtual void invoke(ParsingFieldDeclarator &Field) = 0;
1676198893Srdivacky    virtual ~FieldCallback() {}
1677198893Srdivacky
1678198893Srdivacky  private:
1679198893Srdivacky    virtual void _anchor();
1680198893Srdivacky  };
1681200583Srdivacky  struct ObjCPropertyCallback;
1682198893Srdivacky
1683239462Sdim  void ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Callback);
1684198893Srdivacky
1685218893Sdim  bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1686193326Sed  bool isTypeSpecifierQualifier();
1687193326Sed  bool isTypeQualifier() const;
1688234353Sdim
1689204643Srdivacky  /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1690204643Srdivacky  /// is definitely a type-specifier.  Return false if it isn't part of a type
1691204643Srdivacky  /// specifier or if we're not sure.
1692204643Srdivacky  bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1693193326Sed
1694243830Sdim  /// \brief Return true if we know that we are definitely looking at a
1695243830Sdim  /// decl-specifier, and isn't part of an expression such as a function-style
1696243830Sdim  /// cast. Return false if it's no a decl-specifier, or we're not sure.
1697243830Sdim  bool isKnownToBeDeclarationSpecifier() {
1698243830Sdim    if (getLangOpts().CPlusPlus)
1699243830Sdim      return isCXXDeclarationSpecifier() == TPResult::True();
1700243830Sdim    return isDeclarationSpecifier(true);
1701243830Sdim  }
1702243830Sdim
1703193326Sed  /// isDeclarationStatement - Disambiguates between a declaration or an
1704193326Sed  /// expression statement, when parsing function bodies.
1705193326Sed  /// Returns true for declaration, false for expression.
1706193326Sed  bool isDeclarationStatement() {
1707234353Sdim    if (getLangOpts().CPlusPlus)
1708193326Sed      return isCXXDeclarationStatement();
1709218893Sdim    return isDeclarationSpecifier(true);
1710193326Sed  }
1711193326Sed
1712234353Sdim  /// isForInitDeclaration - Disambiguates between a declaration or an
1713234353Sdim  /// expression in the context of the C 'clause-1' or the C++
1714193326Sed  // 'for-init-statement' part of a 'for' statement.
1715193326Sed  /// Returns true for declaration, false for expression.
1716234353Sdim  bool isForInitDeclaration() {
1717234353Sdim    if (getLangOpts().CPlusPlus)
1718234353Sdim      return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
1719218893Sdim    return isDeclarationSpecifier(true);
1720193326Sed  }
1721193326Sed
1722218893Sdim  /// \brief Determine whether we are currently at the start of an Objective-C
1723218893Sdim  /// class message that appears to be missing the open bracket '['.
1724218893Sdim  bool isStartOfObjCClassMessageMissingOpenBracket();
1725234353Sdim
1726202379Srdivacky  /// \brief Starting with a scope specifier, identifier, or
1727202379Srdivacky  /// template-id that refers to the current class, determine whether
1728202379Srdivacky  /// this is a constructor declarator.
1729202379Srdivacky  bool isConstructorDeclarator();
1730202379Srdivacky
1731193326Sed  /// \brief Specifies the context in which type-id/expression
1732193326Sed  /// disambiguation will occur.
1733193326Sed  enum TentativeCXXTypeIdContext {
1734193326Sed    TypeIdInParens,
1735193326Sed    TypeIdAsTemplateArgument
1736193326Sed  };
1737193326Sed
1738193326Sed
1739193326Sed  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1740193326Sed  /// whether the parens contain an expression or a type-id.
1741193326Sed  /// Returns true for a type-id and false for an expression.
1742193326Sed  bool isTypeIdInParens(bool &isAmbiguous) {
1743234353Sdim    if (getLangOpts().CPlusPlus)
1744193326Sed      return isCXXTypeId(TypeIdInParens, isAmbiguous);
1745193326Sed    isAmbiguous = false;
1746193326Sed    return isTypeSpecifierQualifier();
1747193326Sed  }
1748193326Sed  bool isTypeIdInParens() {
1749193326Sed    bool isAmbiguous;
1750193326Sed    return isTypeIdInParens(isAmbiguous);
1751193326Sed  }
1752193326Sed
1753193326Sed  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1754193326Sed  /// between a declaration or an expression statement, when parsing function
1755193326Sed  /// bodies. Returns true for declaration, false for expression.
1756193326Sed  bool isCXXDeclarationStatement();
1757193326Sed
1758193326Sed  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1759193326Sed  /// between a simple-declaration or an expression-statement.
1760193326Sed  /// If during the disambiguation process a parsing error is encountered,
1761193326Sed  /// the function returns true to let the declaration parsing code handle it.
1762193326Sed  /// Returns false if the statement is disambiguated as expression.
1763234353Sdim  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
1764193326Sed
1765193326Sed  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1766193326Sed  /// a constructor-style initializer, when parsing declaration statements.
1767193326Sed  /// Returns true for function declarator and false for constructor-style
1768239462Sdim  /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
1769239462Sdim  /// might be a constructor-style initializer.
1770193326Sed  /// If during the disambiguation process a parsing error is encountered,
1771193326Sed  /// the function returns true to let the declaration parsing code handle it.
1772239462Sdim  bool isCXXFunctionDeclarator(bool *IsAmbiguous = 0);
1773193326Sed
1774193326Sed  /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1775193326Sed  /// expression for a condition of a if/switch/while/for statement.
1776193326Sed  /// If during the disambiguation process a parsing error is encountered,
1777193326Sed  /// the function returns true to let the declaration parsing code handle it.
1778193326Sed  bool isCXXConditionDeclaration();
1779193326Sed
1780193326Sed  bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1781193326Sed  bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1782193326Sed    bool isAmbiguous;
1783193326Sed    return isCXXTypeId(Context, isAmbiguous);
1784193326Sed  }
1785193326Sed
1786193326Sed  /// TPResult - Used as the result value for functions whose purpose is to
1787193326Sed  /// disambiguate C++ constructs by "tentatively parsing" them.
1788193326Sed  /// This is a class instead of a simple enum because the implicit enum-to-bool
1789193326Sed  /// conversions may cause subtle bugs.
1790193326Sed  class TPResult {
1791193326Sed    enum Result {
1792193326Sed      TPR_true,
1793193326Sed      TPR_false,
1794193326Sed      TPR_ambiguous,
1795193326Sed      TPR_error
1796193326Sed    };
1797193326Sed    Result Res;
1798193326Sed    TPResult(Result result) : Res(result) {}
1799193326Sed  public:
1800193326Sed    static TPResult True() { return TPR_true; }
1801193326Sed    static TPResult False() { return TPR_false; }
1802193326Sed    static TPResult Ambiguous() { return TPR_ambiguous; }
1803193326Sed    static TPResult Error() { return TPR_error; }
1804193326Sed
1805193326Sed    bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
1806193326Sed    bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
1807193326Sed  };
1808193326Sed
1809218893Sdim  /// \brief Based only on the given token kind, determine whether we know that
1810218893Sdim  /// we're at the start of an expression or a type-specifier-seq (which may
1811218893Sdim  /// be an expression, in C++).
1812218893Sdim  ///
1813218893Sdim  /// This routine does not attempt to resolve any of the trick cases, e.g.,
1814218893Sdim  /// those involving lookup of identifiers.
1815218893Sdim  ///
1816218893Sdim  /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1817218893Sdim  /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1818218893Sdim  /// tell.
1819218893Sdim  TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
1820218893Sdim
1821193326Sed  /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
1822193326Sed  /// declaration specifier, TPResult::False() if it is not,
1823193326Sed  /// TPResult::Ambiguous() if it could be either a decl-specifier or a
1824193326Sed  /// function-style cast, and TPResult::Error() if a parsing error was
1825234353Sdim  /// encountered. If it could be a braced C++11 function-style cast, returns
1826234353Sdim  /// BracedCastResult.
1827193326Sed  /// Doesn't consume tokens.
1828234353Sdim  TPResult
1829239462Sdim  isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False(),
1830239462Sdim                            bool *HasMissingTypename = 0);
1831234353Sdim
1832263508Sdim  /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
1833263508Sdim  /// \c TPResult::Ambiguous, determine whether the decl-specifier would be
1834263508Sdim  /// a type-specifier other than a cv-qualifier.
1835263508Sdim  bool isCXXDeclarationSpecifierAType();
1836263508Sdim
1837243830Sdim  /// \brief Determine whether an identifier has been tentatively declared as a
1838243830Sdim  /// non-type. Such tentative declarations should not be found to name a type
1839243830Sdim  /// during a tentative parse, but also should not be annotated as a non-type.
1840243830Sdim  bool isTentativelyDeclared(IdentifierInfo *II);
1841243830Sdim
1842193326Sed  // "Tentative parsing" functions, used for disambiguation. If a parsing error
1843193326Sed  // is encountered they will return TPResult::Error().
1844193326Sed  // Returning TPResult::True()/False() indicates that the ambiguity was
1845193326Sed  // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
1846193326Sed  // that more tentative parsing is necessary for disambiguation.
1847193326Sed  // They all consume tokens, so backtracking should be used after calling them.
1848193326Sed
1849234353Sdim  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
1850193326Sed  TPResult TryParseTypeofSpecifier();
1851218893Sdim  TPResult TryParseProtocolQualifiers();
1852263508Sdim  TPResult TryParsePtrOperatorSeq();
1853263508Sdim  TPResult TryParseOperatorId();
1854193326Sed  TPResult TryParseInitDeclaratorList();
1855193326Sed  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
1856263508Sdim  TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = 0,
1857263508Sdim                                              bool VersusTemplateArg = false);
1858193326Sed  TPResult TryParseFunctionDeclarator();
1859193326Sed  TPResult TryParseBracketDeclarator();
1860263508Sdim  TPResult TryConsumeDeclarationSpecifier();
1861193326Sed
1862243830Sdimpublic:
1863218893Sdim  TypeResult ParseTypeName(SourceRange *Range = 0,
1864218893Sdim                           Declarator::TheContext Context
1865224145Sdim                             = Declarator::TypeNameContext,
1866224145Sdim                           AccessSpecifier AS = AS_none,
1867249423Sdim                           Decl **OwnedType = 0,
1868249423Sdim                           ParsedAttributes *Attrs = 0);
1869243830Sdim
1870243830Sdimprivate:
1871239462Sdim  void ParseBlockId(SourceLocation CaretLoc);
1872218893Sdim
1873234353Sdim  // Check for the start of a C++11 attribute-specifier-seq in a context where
1874234353Sdim  // an attribute is not allowed.
1875234353Sdim  bool CheckProhibitedCXX11Attribute() {
1876234353Sdim    assert(Tok.is(tok::l_square));
1877249423Sdim    if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
1878234353Sdim      return false;
1879234353Sdim    return DiagnoseProhibitedCXX11Attribute();
1880234353Sdim  }
1881234353Sdim  bool DiagnoseProhibitedCXX11Attribute();
1882249423Sdim  void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1883249423Sdim                                    SourceLocation CorrectLocation) {
1884249423Sdim    if (!getLangOpts().CPlusPlus11)
1885249423Sdim      return;
1886249423Sdim    if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
1887249423Sdim        Tok.isNot(tok::kw_alignas))
1888249423Sdim      return;
1889249423Sdim    DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
1890249423Sdim  }
1891249423Sdim  void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1892249423Sdim                                       SourceLocation CorrectLocation);
1893234353Sdim
1894218893Sdim  void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
1895218893Sdim    if (!attrs.Range.isValid()) return;
1896218893Sdim    DiagnoseProhibitedAttributes(attrs);
1897234982Sdim    attrs.clear();
1898218893Sdim  }
1899218893Sdim  void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
1900218893Sdim
1901243830Sdim  // Forbid C++11 attributes that appear on certain syntactic
1902243830Sdim  // locations which standard permits but we don't supported yet,
1903243830Sdim  // for example, attributes appertain to decl specifiers.
1904243830Sdim  void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
1905243830Sdim
1906263508Sdim  /// \brief Diagnose and skip C++11 attributes that appear in syntactic
1907263508Sdim  /// locations where attributes are not allowed.
1908263508Sdim  void DiagnoseAndSkipCXX11Attributes();
1909263508Sdim
1910226633Sdim  void MaybeParseGNUAttributes(Declarator &D,
1911226633Sdim                               LateParsedAttrList *LateAttrs = 0) {
1912218893Sdim    if (Tok.is(tok::kw___attribute)) {
1913221345Sdim      ParsedAttributes attrs(AttrFactory);
1914218893Sdim      SourceLocation endLoc;
1915226633Sdim      ParseGNUAttributes(attrs, &endLoc, LateAttrs);
1916221345Sdim      D.takeAttributes(attrs, endLoc);
1917218893Sdim    }
1918218893Sdim  }
1919218893Sdim  void MaybeParseGNUAttributes(ParsedAttributes &attrs,
1920226633Sdim                               SourceLocation *endLoc = 0,
1921226633Sdim                               LateParsedAttrList *LateAttrs = 0) {
1922218893Sdim    if (Tok.is(tok::kw___attribute))
1923226633Sdim      ParseGNUAttributes(attrs, endLoc, LateAttrs);
1924218893Sdim  }
1925218893Sdim  void ParseGNUAttributes(ParsedAttributes &attrs,
1926226633Sdim                          SourceLocation *endLoc = 0,
1927226633Sdim                          LateParsedAttrList *LateAttrs = 0);
1928226633Sdim  void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
1929226633Sdim                             SourceLocation AttrNameLoc,
1930226633Sdim                             ParsedAttributes &Attrs,
1931243830Sdim                             SourceLocation *EndLoc,
1932243830Sdim                             IdentifierInfo *ScopeName,
1933243830Sdim                             SourceLocation ScopeLoc,
1934243830Sdim                             AttributeList::Syntax Syntax);
1935263508Sdim  IdentifierLoc *ParseIdentifierLoc();
1936218893Sdim
1937249423Sdim  void MaybeParseCXX11Attributes(Declarator &D) {
1938249423Sdim    if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
1939221345Sdim      ParsedAttributesWithRange attrs(AttrFactory);
1940218893Sdim      SourceLocation endLoc;
1941234353Sdim      ParseCXX11Attributes(attrs, &endLoc);
1942221345Sdim      D.takeAttributes(attrs, endLoc);
1943218893Sdim    }
1944218893Sdim  }
1945249423Sdim  void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
1946218893Sdim                                 SourceLocation *endLoc = 0) {
1947249423Sdim    if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
1948221345Sdim      ParsedAttributesWithRange attrsWithRange(AttrFactory);
1949234353Sdim      ParseCXX11Attributes(attrsWithRange, endLoc);
1950221345Sdim      attrs.takeAllFrom(attrsWithRange);
1951218893Sdim    }
1952218893Sdim  }
1953249423Sdim  void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1954234353Sdim                                 SourceLocation *endLoc = 0,
1955234353Sdim                                 bool OuterMightBeMessageSend = false) {
1956249423Sdim    if (getLangOpts().CPlusPlus11 &&
1957234353Sdim        isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
1958234353Sdim      ParseCXX11Attributes(attrs, endLoc);
1959218893Sdim  }
1960226633Sdim
1961234353Sdim  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
1962226633Sdim                                    SourceLocation *EndLoc = 0);
1963234353Sdim  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
1964218893Sdim                            SourceLocation *EndLoc = 0);
1965243830Sdim
1966234353Sdim  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
1967218893Sdim
1968218893Sdim  void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
1969218893Sdim                                     SourceLocation *endLoc = 0) {
1970234353Sdim    if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
1971218893Sdim      ParseMicrosoftAttributes(attrs, endLoc);
1972218893Sdim  }
1973218893Sdim  void ParseMicrosoftAttributes(ParsedAttributes &attrs,
1974218893Sdim                                SourceLocation *endLoc = 0);
1975239462Sdim  void ParseMicrosoftDeclSpec(ParsedAttributes &Attrs);
1976239462Sdim  bool IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident);
1977239462Sdim  void ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
1978239462Sdim                                     SourceLocation Loc,
1979239462Sdim                                     ParsedAttributes &Attrs);
1980239462Sdim  void ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
1981239462Sdim                                           SourceLocation AttrNameLoc,
1982239462Sdim                                           ParsedAttributes &Attrs);
1983218893Sdim  void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
1984239462Sdim  void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
1985218893Sdim  void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
1986218893Sdim  void ParseOpenCLAttributes(ParsedAttributes &attrs);
1987221345Sdim  void ParseOpenCLQualifiers(DeclSpec &DS);
1988218893Sdim
1989221345Sdim  VersionTuple ParseVersionTuple(SourceRange &Range);
1990221345Sdim  void ParseAvailabilityAttribute(IdentifierInfo &Availability,
1991221345Sdim                                  SourceLocation AvailabilityLoc,
1992221345Sdim                                  ParsedAttributes &attrs,
1993221345Sdim                                  SourceLocation *endLoc);
1994221345Sdim
1995249423Sdim  bool IsThreadSafetyAttribute(StringRef AttrName);
1996226633Sdim  void ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1997226633Sdim                                  SourceLocation AttrNameLoc,
1998226633Sdim                                  ParsedAttributes &Attrs,
1999226633Sdim                                  SourceLocation *EndLoc);
2000226633Sdim
2001239462Sdim  void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
2002239462Sdim                                        SourceLocation AttrNameLoc,
2003239462Sdim                                        ParsedAttributes &Attrs,
2004239462Sdim                                        SourceLocation *EndLoc);
2005226633Sdim
2006263508Sdim  void ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
2007263508Sdim                                 SourceLocation AttrNameLoc,
2008263508Sdim                                 ParsedAttributes &Attrs,
2009263508Sdim                                 SourceLocation *EndLoc);
2010263508Sdim
2011193326Sed  void ParseTypeofSpecifier(DeclSpec &DS);
2012234353Sdim  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
2013234982Sdim  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
2014234353Sdim                                         SourceLocation StartLoc,
2015234353Sdim                                         SourceLocation EndLoc);
2016223017Sdim  void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
2017226633Sdim  void ParseAtomicSpecifier(DeclSpec &DS);
2018193326Sed
2019234353Sdim  ExprResult ParseAlignArgument(SourceLocation Start,
2020234353Sdim                                SourceLocation &EllipsisLoc);
2021226633Sdim  void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2022226633Sdim                               SourceLocation *endLoc = 0);
2023226633Sdim
2024249423Sdim  VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
2025249423Sdim  VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
2026249423Sdim    return isCXX11VirtSpecifier(Tok);
2027234353Sdim  }
2028249423Sdim  void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface);
2029218893Sdim
2030249423Sdim  bool isCXX11FinalKeyword() const;
2031218893Sdim
2032193326Sed  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
2033193326Sed  /// enter a new C++ declarator scope and exit it when the function is
2034193326Sed  /// finished.
2035193326Sed  class DeclaratorScopeObj {
2036193326Sed    Parser &P;
2037193326Sed    CXXScopeSpec &SS;
2038198092Srdivacky    bool EnteredScope;
2039199482Srdivacky    bool CreatedScope;
2040193326Sed  public:
2041198092Srdivacky    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
2042199482Srdivacky      : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
2043193326Sed
2044193326Sed    void EnterDeclaratorScope() {
2045198092Srdivacky      assert(!EnteredScope && "Already entered the scope!");
2046198092Srdivacky      assert(SS.isSet() && "C++ scope was not set!");
2047199482Srdivacky
2048199482Srdivacky      CreatedScope = true;
2049199482Srdivacky      P.EnterScope(0); // Not a decl scope.
2050199482Srdivacky
2051210299Sed      if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
2052198092Srdivacky        EnteredScope = true;
2053193326Sed    }
2054193326Sed
2055193326Sed    ~DeclaratorScopeObj() {
2056198092Srdivacky      if (EnteredScope) {
2057198092Srdivacky        assert(SS.isSet() && "C++ scope was cleared ?");
2058210299Sed        P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
2059198092Srdivacky      }
2060199482Srdivacky      if (CreatedScope)
2061199482Srdivacky        P.ExitScope();
2062193326Sed    }
2063193326Sed  };
2064198092Srdivacky
2065193326Sed  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
2066193326Sed  void ParseDeclarator(Declarator &D);
2067193326Sed  /// A function that parses a variant of direct-declarator.
2068193326Sed  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
2069193326Sed  void ParseDeclaratorInternal(Declarator &D,
2070193326Sed                               DirectDeclParseFunction DirectDeclParser);
2071218893Sdim
2072199990Srdivacky  void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
2073249423Sdim                                 bool CXX11AttributesAllowed = true,
2074263508Sdim                                 bool AtomicAllowed = true,
2075263508Sdim                                 bool IdentifierRequired = false);
2076193326Sed  void ParseDirectDeclarator(Declarator &D);
2077193326Sed  void ParseParenDeclarator(Declarator &D);
2078226633Sdim  void ParseFunctionDeclarator(Declarator &D,
2079218893Sdim                               ParsedAttributes &attrs,
2080226633Sdim                               BalancedDelimiterTracker &Tracker,
2081239462Sdim                               bool IsAmbiguous,
2082193326Sed                               bool RequiresArg = false);
2083224145Sdim  bool isFunctionDeclaratorIdentifierList();
2084224145Sdim  void ParseFunctionDeclaratorIdentifierList(
2085224145Sdim         Declarator &D,
2086263508Sdim         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
2087224145Sdim  void ParseParameterDeclarationClause(
2088224145Sdim         Declarator &D,
2089224145Sdim         ParsedAttributes &attrs,
2090263508Sdim         SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
2091224145Sdim         SourceLocation &EllipsisLoc);
2092193326Sed  void ParseBracketDeclarator(Declarator &D);
2093198092Srdivacky
2094193326Sed  //===--------------------------------------------------------------------===//
2095193326Sed  // C++ 7: Declarations [dcl.dcl]
2096198092Srdivacky
2097234353Sdim  /// The kind of attribute specifier we have found.
2098234353Sdim  enum CXX11AttributeKind {
2099234353Sdim    /// This is not an attribute specifier.
2100234353Sdim    CAK_NotAttributeSpecifier,
2101234353Sdim    /// This should be treated as an attribute-specifier.
2102234353Sdim    CAK_AttributeSpecifier,
2103234353Sdim    /// The next tokens are '[[', but this is not an attribute-specifier. This
2104234353Sdim    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
2105234353Sdim    CAK_InvalidAttributeSpecifier
2106234353Sdim  };
2107234353Sdim  CXX11AttributeKind
2108234353Sdim  isCXX11AttributeSpecifier(bool Disambiguate = false,
2109234353Sdim                            bool OuterMightBeMessageSend = false);
2110234353Sdim
2111263508Sdim  void DiagnoseUnexpectedNamespace(NamedDecl *Context);
2112263508Sdim
2113212904Sdim  Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
2114212904Sdim                       SourceLocation InlineLoc = SourceLocation());
2115223017Sdim  void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
2116223017Sdim                           std::vector<IdentifierInfo*>& Ident,
2117223017Sdim                           std::vector<SourceLocation>& NamespaceLoc,
2118223017Sdim                           unsigned int index, SourceLocation& InlineLoc,
2119226633Sdim                           ParsedAttributes& attrs,
2120226633Sdim                           BalancedDelimiterTracker &Tracker);
2121212904Sdim  Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
2122212904Sdim  Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
2123218893Sdim                                         const ParsedTemplateInfo &TemplateInfo,
2124212904Sdim                                         SourceLocation &DeclEnd,
2125224145Sdim                                         ParsedAttributesWithRange &attrs,
2126224145Sdim                                         Decl **OwnedType = 0);
2127218893Sdim  Decl *ParseUsingDirective(unsigned Context,
2128218893Sdim                            SourceLocation UsingLoc,
2129218893Sdim                            SourceLocation &DeclEnd,
2130218893Sdim                            ParsedAttributes &attrs);
2131218893Sdim  Decl *ParseUsingDeclaration(unsigned Context,
2132218893Sdim                              const ParsedTemplateInfo &TemplateInfo,
2133218893Sdim                              SourceLocation UsingLoc,
2134212904Sdim                              SourceLocation &DeclEnd,
2135224145Sdim                              AccessSpecifier AS = AS_none,
2136224145Sdim                              Decl **OwnedType = 0);
2137212904Sdim  Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
2138212904Sdim  Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
2139212904Sdim                            SourceLocation AliasLoc, IdentifierInfo *Alias,
2140212904Sdim                            SourceLocation &DeclEnd);
2141198092Srdivacky
2142193326Sed  //===--------------------------------------------------------------------===//
2143193326Sed  // C++ 9: classes [class] and C structs/unions.
2144239462Sdim  bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
2145193326Sed  void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
2146234353Sdim                           DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
2147234353Sdim                           AccessSpecifier AS, bool EnteringContext,
2148249423Sdim                           DeclSpecContext DSC,
2149249423Sdim                           ParsedAttributesWithRange &Attributes);
2150249423Sdim  void ParseCXXMemberSpecification(SourceLocation StartLoc,
2151249423Sdim                                   SourceLocation AttrFixitLoc,
2152249423Sdim                                   ParsedAttributesWithRange &Attrs,
2153249423Sdim                                   unsigned TagType,
2154212904Sdim                                   Decl *TagDecl);
2155234353Sdim  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2156223017Sdim                                       SourceLocation &EqualLoc);
2157226633Sdim  void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *Attr,
2158212904Sdim                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
2159212904Sdim                                 ParsingDeclRAIIObject *DiagsFromTParams = 0);
2160212904Sdim  void ParseConstructorInitializer(Decl *ConstructorDecl);
2161212904Sdim  MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
2162234982Sdim  void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2163234982Sdim                                      Decl *ThisDecl);
2164193326Sed
2165193326Sed  //===--------------------------------------------------------------------===//
2166193326Sed  // C++ 10: Derived classes [class.derived]
2167234353Sdim  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
2168234353Sdim                                    SourceLocation &EndLocation);
2169212904Sdim  void ParseBaseClause(Decl *ClassDecl);
2170212904Sdim  BaseResult ParseBaseSpecifier(Decl *ClassDecl);
2171193326Sed  AccessSpecifier getAccessSpecifierIfPresent() const;
2172193326Sed
2173234353Sdim  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2174234353Sdim                                    SourceLocation TemplateKWLoc,
2175198893Srdivacky                                    IdentifierInfo *Name,
2176198893Srdivacky                                    SourceLocation NameLoc,
2177198893Srdivacky                                    bool EnteringContext,
2178212904Sdim                                    ParsedType ObjectType,
2179204643Srdivacky                                    UnqualifiedId &Id,
2180234353Sdim                                    bool AssumeTemplateId);
2181198893Srdivacky  bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2182212904Sdim                                  ParsedType ObjectType,
2183198893Srdivacky                                  UnqualifiedId &Result);
2184243830Sdim
2185249423Sdim  //===--------------------------------------------------------------------===//
2186249423Sdim  // OpenMP: Directives and clauses.
2187263508Sdim  /// \brief Parses declarative OpenMP directives.
2188249423Sdim  DeclGroupPtrTy ParseOpenMPDeclarativeDirective();
2189263508Sdim  /// \brief Parses simple list of variables.
2190263508Sdim  ///
2191263508Sdim  /// \param Kind Kind of the directive.
2192263508Sdim  /// \param [out] VarList List of referenced variables.
2193263508Sdim  /// \param AllowScopeSpecifier true, if the variables can have fully
2194263508Sdim  /// qualified names.
2195263508Sdim  ///
2196249423Sdim  bool ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind,
2197263508Sdim                                SmallVectorImpl<Expr *> &VarList,
2198263508Sdim                                bool AllowScopeSpecifier);
2199263508Sdim  /// \brief Parses declarative or executable directive.
2200263508Sdim  StmtResult ParseOpenMPDeclarativeOrExecutableDirective();
2201263508Sdim  /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind.
2202263508Sdim  ///
2203263508Sdim  /// \param DKind Kind of current directive.
2204263508Sdim  /// \param CKind Kind of current clause.
2205263508Sdim  /// \param FirstClause true, if this is the first clause of a kind \a CKind
2206263508Sdim  /// in current directive.
2207263508Sdim  ///
2208263508Sdim  OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind,
2209263508Sdim                               OpenMPClauseKind CKind, bool FirstClause);
2210263508Sdim  /// \brief Parses clause with a single expression of a kind \a Kind.
2211263508Sdim  ///
2212263508Sdim  /// \param Kind Kind of current clause.
2213263508Sdim  ///
2214263508Sdim  OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind);
2215263508Sdim  /// \brief Parses simple clause of a kind \a Kind.
2216263508Sdim  ///
2217263508Sdim  /// \param Kind Kind of current clause.
2218263508Sdim  ///
2219263508Sdim  OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind);
2220263508Sdim  /// \brief Parses clause with the list of variables of a kind \a Kind.
2221263508Sdim  ///
2222263508Sdim  /// \param Kind Kind of current clause.
2223263508Sdim  ///
2224263508Sdim  OMPClause *ParseOpenMPVarListClause(OpenMPClauseKind Kind);
2225243830Sdimpublic:
2226198893Srdivacky  bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2227198893Srdivacky                          bool AllowDestructorName,
2228198893Srdivacky                          bool AllowConstructorName,
2229212904Sdim                          ParsedType ObjectType,
2230234353Sdim                          SourceLocation& TemplateKWLoc,
2231198893Srdivacky                          UnqualifiedId &Result);
2232234353Sdim
2233243830Sdimprivate:
2234193326Sed  //===--------------------------------------------------------------------===//
2235193326Sed  // C++ 14: Templates [temp]
2236193326Sed
2237193326Sed  // C++ 14.1: Template Parameters [temp.param]
2238212904Sdim  Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
2239226633Sdim                                             SourceLocation &DeclEnd,
2240226633Sdim                                             AccessSpecifier AS = AS_none,
2241226633Sdim                                             AttributeList *AccessAttrs = 0);
2242226633Sdim  Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
2243193326Sed                                                 SourceLocation &DeclEnd,
2244226633Sdim                                                 AccessSpecifier AS,
2245226633Sdim                                                 AttributeList *AccessAttrs);
2246212904Sdim  Decl *ParseSingleDeclarationAfterTemplate(
2247193326Sed                                       unsigned Context,
2248193326Sed                                       const ParsedTemplateInfo &TemplateInfo,
2249212904Sdim                                       ParsingDeclRAIIObject &DiagsFromParams,
2250193326Sed                                       SourceLocation &DeclEnd,
2251226633Sdim                                       AccessSpecifier AS=AS_none,
2252226633Sdim                                       AttributeList *AccessAttrs = 0);
2253198092Srdivacky  bool ParseTemplateParameters(unsigned Depth,
2254226633Sdim                               SmallVectorImpl<Decl*> &TemplateParams,
2255198092Srdivacky                               SourceLocation &LAngleLoc,
2256193326Sed                               SourceLocation &RAngleLoc);
2257193326Sed  bool ParseTemplateParameterList(unsigned Depth,
2258226633Sdim                                  SmallVectorImpl<Decl*> &TemplateParams);
2259199990Srdivacky  bool isStartOfTemplateTypeParameter();
2260212904Sdim  Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
2261212904Sdim  Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
2262212904Sdim  Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
2263212904Sdim  Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
2264193326Sed  // C++ 14.3: Template arguments [temp.arg]
2265226633Sdim  typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
2266193326Sed
2267249423Sdim  bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
2268249423Sdim                                      bool ConsumeLastToken);
2269193326Sed  bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
2270198092Srdivacky                                        SourceLocation TemplateNameLoc,
2271221345Sdim                                        const CXXScopeSpec &SS,
2272193326Sed                                        bool ConsumeLastToken,
2273193326Sed                                        SourceLocation &LAngleLoc,
2274193326Sed                                        TemplateArgList &TemplateArgs,
2275193326Sed                                        SourceLocation &RAngleLoc);
2276193326Sed
2277195099Sed  bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
2278221345Sdim                               CXXScopeSpec &SS,
2279234353Sdim                               SourceLocation TemplateKWLoc,
2280198893Srdivacky                               UnqualifiedId &TemplateName,
2281193326Sed                               bool AllowTypeAnnotation = true);
2282221345Sdim  void AnnotateTemplateIdTokenAsType();
2283208600Srdivacky  bool IsTemplateArgumentList(unsigned Skip = 0);
2284199482Srdivacky  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
2285199482Srdivacky  ParsedTemplateArgument ParseTemplateTemplateArgument();
2286199482Srdivacky  ParsedTemplateArgument ParseTemplateArgument();
2287234353Sdim  Decl *ParseExplicitInstantiation(unsigned Context,
2288234353Sdim                                   SourceLocation ExternLoc,
2289234353Sdim                                   SourceLocation TemplateLoc,
2290234353Sdim                                   SourceLocation &DeclEnd,
2291234353Sdim                                   AccessSpecifier AS = AS_none);
2292193326Sed
2293193326Sed  //===--------------------------------------------------------------------===//
2294226633Sdim  // Modules
2295234353Sdim  DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
2296234353Sdim
2297226633Sdim  //===--------------------------------------------------------------------===//
2298193326Sed  // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
2299212904Sdim  ExprResult ParseUnaryTypeTrait();
2300218893Sdim  ExprResult ParseBinaryTypeTrait();
2301234353Sdim  ExprResult ParseTypeTrait();
2302234353Sdim
2303212904Sdim  //===--------------------------------------------------------------------===//
2304221345Sdim  // Embarcadero: Arary and Expression Traits
2305221345Sdim  ExprResult ParseArrayTypeTrait();
2306221345Sdim  ExprResult ParseExpressionTrait();
2307221345Sdim
2308221345Sdim  //===--------------------------------------------------------------------===//
2309212904Sdim  // Preprocessor code-completion pass-through
2310212904Sdim  virtual void CodeCompleteDirective(bool InConditional);
2311212904Sdim  virtual void CodeCompleteInConditionalExclusion();
2312212904Sdim  virtual void CodeCompleteMacroName(bool IsDefinition);
2313212904Sdim  virtual void CodeCompletePreprocessorExpression();
2314212904Sdim  virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
2315212904Sdim                                         MacroInfo *MacroInfo,
2316212904Sdim                                         unsigned ArgumentIndex);
2317212904Sdim  virtual void CodeCompleteNaturalLanguage();
2318193326Sed};
2319193326Sed
2320193326Sed}  // end namespace clang
2321193326Sed
2322193326Sed#endif
2323