]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/include/clang/Parse/Parser.h
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / include / clang / Parse / Parser.h
1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the Parser interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_PARSE_PARSER_H
15 #define LLVM_CLANG_PARSE_PARSER_H
16
17 #include "clang/Basic/Specifiers.h"
18 #include "clang/Basic/DelayedCleanupPool.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/CodeCompletionHandler.h"
21 #include "clang/Sema/Sema.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include <stack>
26
27 namespace clang {
28   class PragmaHandler;
29   class Scope;
30   class DeclGroupRef;
31   class DiagnosticBuilder;
32   class Parser;
33   class PragmaUnusedHandler;
34   class ColonProtectionRAIIObject;
35   class InMessageExpressionRAIIObject;
36   class PoisonSEHIdentifiersRAIIObject;
37   class VersionTuple;
38   
39 /// PrettyStackTraceParserEntry - If a crash happens while the parser is active,
40 /// an entry is printed for it.
41 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
42   const Parser &P;
43 public:
44   PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
45   virtual void print(llvm::raw_ostream &OS) const;
46 };
47
48 /// PrecedenceLevels - These are precedences for the binary/ternary
49 /// operators in the C99 grammar.  These have been named to relate
50 /// with the C99 grammar productions.  Low precedences numbers bind
51 /// more weakly than high numbers.
52 namespace prec {
53   enum Level {
54     Unknown         = 0,    // Not binary operator.
55     Comma           = 1,    // ,
56     Assignment      = 2,    // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
57     Conditional     = 3,    // ?
58     LogicalOr       = 4,    // ||
59     LogicalAnd      = 5,    // &&
60     InclusiveOr     = 6,    // |
61     ExclusiveOr     = 7,    // ^
62     And             = 8,    // &
63     Equality        = 9,    // ==, !=
64     Relational      = 10,   //  >=, <=, >, <
65     Shift           = 11,   // <<, >>
66     Additive        = 12,   // -, +
67     Multiplicative  = 13,   // *, /, %
68     PointerToMember = 14    // .*, ->*
69   };
70 }
71
72 /// Parser - This implements a parser for the C family of languages.  After
73 /// parsing units of the grammar, productions are invoked to handle whatever has
74 /// been read.
75 ///
76 class Parser : public CodeCompletionHandler {
77   friend class PragmaUnusedHandler;
78   friend class ColonProtectionRAIIObject;
79   friend class InMessageExpressionRAIIObject;
80   friend class PoisonSEHIdentifiersRAIIObject;
81   friend class ParenBraceBracketBalancer;
82
83   Preprocessor &PP;
84
85   /// Tok - The current token we are peeking ahead.  All parsing methods assume
86   /// that this is valid.
87   Token Tok;
88
89   // PrevTokLocation - The location of the token we previously
90   // consumed. This token is used for diagnostics where we expected to
91   // see a token following another token (e.g., the ';' at the end of
92   // a statement).
93   SourceLocation PrevTokLocation;
94
95   unsigned short ParenCount, BracketCount, BraceCount;
96
97   /// Actions - These are the callbacks we invoke as we parse various constructs
98   /// in the file. 
99   Sema &Actions;
100
101   Diagnostic &Diags;
102
103   /// ScopeCache - Cache scopes to reduce malloc traffic.
104   enum { ScopeCacheSize = 16 };
105   unsigned NumCachedScopes;
106   Scope *ScopeCache[ScopeCacheSize];
107
108   /// Identifiers used for SEH handling in Borland. These are only
109   /// allowed in particular circumstances
110   IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except block
111   IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __except filter expression
112   IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; // __finally
113
114   /// Ident_super - IdentifierInfo for "super", to support fast
115   /// comparison.
116   IdentifierInfo *Ident_super;
117   /// Ident_vector and Ident_pixel - cached IdentifierInfo's for
118   /// "vector" and "pixel" fast comparison.  Only present if
119   /// AltiVec enabled.
120   IdentifierInfo *Ident_vector;
121   IdentifierInfo *Ident_pixel;
122
123   /// \brief Identifier for "introduced".
124   IdentifierInfo *Ident_introduced;
125
126   /// \brief Identifier for "deprecated".
127   IdentifierInfo *Ident_deprecated;
128
129   /// \brief Identifier for "obsoleted".
130   IdentifierInfo *Ident_obsoleted;
131
132   /// \brief Identifier for "unavailable".
133   IdentifierInfo *Ident_unavailable;
134
135   /// C++0x contextual keywords. 
136   mutable IdentifierInfo *Ident_final;
137   mutable IdentifierInfo *Ident_override;
138
139   llvm::OwningPtr<PragmaHandler> AlignHandler;
140   llvm::OwningPtr<PragmaHandler> GCCVisibilityHandler;
141   llvm::OwningPtr<PragmaHandler> OptionsHandler;
142   llvm::OwningPtr<PragmaHandler> PackHandler;
143   llvm::OwningPtr<PragmaHandler> MSStructHandler;
144   llvm::OwningPtr<PragmaHandler> UnusedHandler;
145   llvm::OwningPtr<PragmaHandler> WeakHandler;
146   llvm::OwningPtr<PragmaHandler> FPContractHandler;
147   llvm::OwningPtr<PragmaHandler> OpenCLExtensionHandler;
148
149   /// Whether the '>' token acts as an operator or not. This will be
150   /// true except when we are parsing an expression within a C++
151   /// template argument list, where the '>' closes the template
152   /// argument list.
153   bool GreaterThanIsOperator;
154   
155   /// ColonIsSacred - When this is false, we aggressively try to recover from
156   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
157   /// safe in case statements and a few other things.  This is managed by the
158   /// ColonProtectionRAIIObject RAII object.
159   bool ColonIsSacred;
160
161   /// \brief When true, we are directly inside an Objective-C messsage 
162   /// send expression.
163   ///
164   /// This is managed by the \c InMessageExpressionRAIIObject class, and
165   /// should not be set directly.
166   bool InMessageExpression;
167   
168   /// The "depth" of the template parameters currently being parsed.
169   unsigned TemplateParameterDepth;
170   
171   /// Factory object for creating AttributeList objects.
172   AttributeFactory AttrFactory;
173
174   /// \brief Gathers and cleans up objects when parsing of a top-level
175   /// declaration is finished.
176   DelayedCleanupPool TopLevelDeclCleanupPool;
177
178 public:
179   Parser(Preprocessor &PP, Sema &Actions);
180   ~Parser();
181
182   const LangOptions &getLang() const { return PP.getLangOptions(); }
183   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
184   Preprocessor &getPreprocessor() const { return PP; }
185   Sema &getActions() const { return Actions; }
186
187   const Token &getCurToken() const { return Tok; }
188   Scope *getCurScope() const { return Actions.getCurScope(); }
189   
190   // Type forwarding.  All of these are statically 'void*', but they may all be
191   // different actual classes based on the actions in place.
192   typedef Expr ExprTy;
193   typedef Stmt StmtTy;
194   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
195   typedef CXXBaseSpecifier BaseTy;
196   typedef CXXCtorInitializer MemInitTy;
197   typedef NestedNameSpecifier CXXScopeTy;
198   typedef TemplateParameterList TemplateParamsTy;
199   typedef OpaquePtr<TemplateName> TemplateTy;
200
201   typedef llvm::SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
202
203   typedef clang::ExprResult        ExprResult;
204   typedef clang::StmtResult        StmtResult;
205   typedef clang::BaseResult        BaseResult;
206   typedef clang::MemInitResult     MemInitResult;
207   typedef clang::TypeResult        TypeResult;
208
209   typedef Expr *ExprArg;
210   typedef ASTMultiPtr<Stmt*> MultiStmtArg;
211   typedef Sema::FullExprArg FullExprArg;
212
213   /// Adorns a ExprResult with Actions to make it an ExprResult
214   ExprResult Owned(ExprResult res) {
215     return ExprResult(res);
216   }
217   /// Adorns a StmtResult with Actions to make it an StmtResult
218   StmtResult Owned(StmtResult res) {
219     return StmtResult(res);
220   }
221
222   ExprResult ExprError() { return ExprResult(true); }
223   StmtResult StmtError() { return StmtResult(true); }
224
225   ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
226   StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
227
228   ExprResult ExprEmpty() { return ExprResult(false); }
229
230   // Parsing methods.
231
232   /// ParseTranslationUnit - All in one method that initializes parses, and
233   /// shuts down the parser.
234   void ParseTranslationUnit();
235
236   /// Initialize - Warm up the parser.
237   ///
238   void Initialize();
239
240   /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
241   /// the EOF was encountered.
242   bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
243
244   DeclGroupPtrTy FinishPendingObjCActions();
245
246 private:
247   //===--------------------------------------------------------------------===//
248   // Low-Level token peeking and consumption methods.
249   //
250
251   /// isTokenParen - Return true if the cur token is '(' or ')'.
252   bool isTokenParen() const {
253     return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
254   }
255   /// isTokenBracket - Return true if the cur token is '[' or ']'.
256   bool isTokenBracket() const {
257     return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
258   }
259   /// isTokenBrace - Return true if the cur token is '{' or '}'.
260   bool isTokenBrace() const {
261     return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
262   }
263
264   /// isTokenStringLiteral - True if this token is a string-literal.
265   ///
266   bool isTokenStringLiteral() const {
267     return Tok.getKind() == tok::string_literal ||
268            Tok.getKind() == tok::wide_string_literal;
269   }
270
271   /// \brief Returns true if the current token is a '=' or '==' and
272   /// false otherwise. If it's '==', we assume that it's a typo and we emit
273   /// DiagID and a fixit hint to turn '==' -> '='.
274   bool isTokenEqualOrMistypedEqualEqual(unsigned DiagID);
275
276   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
277   /// This does not work with all kinds of tokens: strings and specific other
278   /// tokens must be consumed with custom methods below.  This returns the
279   /// location of the consumed token.
280   SourceLocation ConsumeToken() {
281     assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
282            !isTokenBrace() &&
283            "Should consume special tokens with Consume*Token");
284     if (Tok.is(tok::code_completion)) {
285       CodeCompletionRecovery();
286       return ConsumeCodeCompletionToken();
287     }
288     
289     PrevTokLocation = Tok.getLocation();
290     PP.Lex(Tok);
291     return PrevTokLocation;
292   }
293
294   /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
295   /// current token type.  This should only be used in cases where the type of
296   /// the token really isn't known, e.g. in error recovery.
297   SourceLocation ConsumeAnyToken() {
298     if (isTokenParen())
299       return ConsumeParen();
300     else if (isTokenBracket())
301       return ConsumeBracket();
302     else if (isTokenBrace())
303       return ConsumeBrace();
304     else if (isTokenStringLiteral())
305       return ConsumeStringToken();
306     else
307       return ConsumeToken();
308   }
309
310   /// ConsumeParen - This consume method keeps the paren count up-to-date.
311   ///
312   SourceLocation ConsumeParen() {
313     assert(isTokenParen() && "wrong consume method");
314     if (Tok.getKind() == tok::l_paren)
315       ++ParenCount;
316     else if (ParenCount)
317       --ParenCount;       // Don't let unbalanced )'s drive the count negative.
318     PrevTokLocation = Tok.getLocation();
319     PP.Lex(Tok);
320     return PrevTokLocation;
321   }
322
323   /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
324   ///
325   SourceLocation ConsumeBracket() {
326     assert(isTokenBracket() && "wrong consume method");
327     if (Tok.getKind() == tok::l_square)
328       ++BracketCount;
329     else if (BracketCount)
330       --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
331
332     PrevTokLocation = Tok.getLocation();
333     PP.Lex(Tok);
334     return PrevTokLocation;
335   }
336
337   /// ConsumeBrace - This consume method keeps the brace count up-to-date.
338   ///
339   SourceLocation ConsumeBrace() {
340     assert(isTokenBrace() && "wrong consume method");
341     if (Tok.getKind() == tok::l_brace)
342       ++BraceCount;
343     else if (BraceCount)
344       --BraceCount;     // Don't let unbalanced }'s drive the count negative.
345
346     PrevTokLocation = Tok.getLocation();
347     PP.Lex(Tok);
348     return PrevTokLocation;
349   }
350
351   /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
352   /// and returning the token kind.  This method is specific to strings, as it
353   /// handles string literal concatenation, as per C99 5.1.1.2, translation
354   /// phase #6.
355   SourceLocation ConsumeStringToken() {
356     assert(isTokenStringLiteral() &&
357            "Should only consume string literals with this method");
358     PrevTokLocation = Tok.getLocation();
359     PP.Lex(Tok);
360     return PrevTokLocation;
361   }
362
363   /// \brief Consume the current code-completion token.
364   ///
365   /// This routine should be called to consume the code-completion token once
366   /// a code-completion action has already been invoked.
367   SourceLocation ConsumeCodeCompletionToken() {
368     assert(Tok.is(tok::code_completion));
369     PrevTokLocation = Tok.getLocation();
370     PP.Lex(Tok);
371     return PrevTokLocation;    
372   }
373   
374   ///\ brief When we are consuming a code-completion token within having 
375   /// matched specific position in the grammar, provide code-completion results
376   /// based on context.
377   void CodeCompletionRecovery();
378
379   /// \brief Handle the annotation token produced for #pragma unused(...)
380   void HandlePragmaUnused();
381
382   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
383   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
384   /// returns the token after Tok, etc.
385   ///
386   /// Note that this differs from the Preprocessor's LookAhead method, because
387   /// the Parser always has one token lexed that the preprocessor doesn't.
388   ///
389   const Token &GetLookAheadToken(unsigned N) {
390     if (N == 0 || Tok.is(tok::eof)) return Tok;
391     return PP.LookAhead(N-1);
392   }
393
394   /// NextToken - This peeks ahead one token and returns it without
395   /// consuming it.
396   const Token &NextToken() {
397     return PP.LookAhead(0);
398   }
399
400   /// getTypeAnnotation - Read a parsed type out of an annotation token.
401   static ParsedType getTypeAnnotation(Token &Tok) {
402     return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
403   }
404
405   static void setTypeAnnotation(Token &Tok, ParsedType T) {
406     Tok.setAnnotationValue(T.getAsOpaquePtr());
407   }
408   
409   /// \brief Read an already-translated primary expression out of an annotation
410   /// token.
411   static ExprResult getExprAnnotation(Token &Tok) {
412     if (Tok.getAnnotationValue())
413       return ExprResult((Expr *)Tok.getAnnotationValue());
414     
415     return ExprResult(true);
416   }
417   
418   /// \brief Set the primary expression corresponding to the given annotation
419   /// token.
420   static void setExprAnnotation(Token &Tok, ExprResult ER) {
421     if (ER.isInvalid())
422       Tok.setAnnotationValue(0);
423     else
424       Tok.setAnnotationValue(ER.get());
425   }
426
427   bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false);
428   bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
429
430   /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
431   /// replacing them with the non-context-sensitive keywords.  This returns
432   /// true if the token was replaced.
433   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
434                        const char *&PrevSpec, unsigned &DiagID,
435                        bool &isInvalid) {
436     if (!getLang().AltiVec ||
437         (Tok.getIdentifierInfo() != Ident_vector &&
438          Tok.getIdentifierInfo() != Ident_pixel))
439       return false;
440     
441     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
442   }
443
444   /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
445   /// identifier token, replacing it with the non-context-sensitive __vector.
446   /// This returns true if the token was replaced.
447   bool TryAltiVecVectorToken() {
448     if (!getLang().AltiVec ||
449         Tok.getIdentifierInfo() != Ident_vector) return false;
450     return TryAltiVecVectorTokenOutOfLine();
451   }
452   
453   bool TryAltiVecVectorTokenOutOfLine();
454   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
455                                 const char *&PrevSpec, unsigned &DiagID,
456                                 bool &isInvalid);
457
458   /// \brief Get the TemplateIdAnnotation from the token and put it in the
459   /// cleanup pool so that it gets destroyed when parsing the current top level
460   /// declaration is finished.
461   TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
462
463   /// TentativeParsingAction - An object that is used as a kind of "tentative
464   /// parsing transaction". It gets instantiated to mark the token position and
465   /// after the token consumption is done, Commit() or Revert() is called to
466   /// either "commit the consumed tokens" or revert to the previously marked
467   /// token position. Example:
468   ///
469   ///   TentativeParsingAction TPA(*this);
470   ///   ConsumeToken();
471   ///   ....
472   ///   TPA.Revert();
473   ///
474   class TentativeParsingAction {
475     Parser &P;
476     Token PrevTok;
477     bool isActive;
478
479   public:
480     explicit TentativeParsingAction(Parser& p) : P(p) {
481       PrevTok = P.Tok;
482       P.PP.EnableBacktrackAtThisPos();
483       isActive = true;
484     }
485     void Commit() {
486       assert(isActive && "Parsing action was finished!");
487       P.PP.CommitBacktrackedTokens();
488       isActive = false;
489     }
490     void Revert() {
491       assert(isActive && "Parsing action was finished!");
492       P.PP.Backtrack();
493       P.Tok = PrevTok;
494       isActive = false;
495     }
496     ~TentativeParsingAction() {
497       assert(!isActive && "Forgot to call Commit or Revert!");
498     }
499   };
500
501
502   SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok,
503                                      SourceLocation LHSLoc);
504
505   /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
506   /// input.  If so, it is consumed and false is returned.
507   ///
508   /// If the input is malformed, this emits the specified diagnostic.  Next, if
509   /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
510   /// returned.
511   bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
512                         const char *DiagMsg = "",
513                         tok::TokenKind SkipToTok = tok::unknown);
514
515   /// \brief The parser expects a semicolon and, if present, will consume it.
516   ///
517   /// If the next token is not a semicolon, this emits the specified diagnostic,
518   /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
519   /// to the semicolon, consumes that extra token.
520   bool ExpectAndConsumeSemi(unsigned DiagID);
521   
522   //===--------------------------------------------------------------------===//
523   // Scope manipulation
524
525   /// ParseScope - Introduces a new scope for parsing. The kind of
526   /// scope is determined by ScopeFlags. Objects of this type should
527   /// be created on the stack to coincide with the position where the
528   /// parser enters the new scope, and this object's constructor will
529   /// create that new scope. Similarly, once the object is destroyed
530   /// the parser will exit the scope.
531   class ParseScope {
532     Parser *Self;
533     ParseScope(const ParseScope&); // do not implement
534     ParseScope& operator=(const ParseScope&); // do not implement
535
536   public:
537     // ParseScope - Construct a new object to manage a scope in the
538     // parser Self where the new Scope is created with the flags
539     // ScopeFlags, but only when ManageScope is true (the default). If
540     // ManageScope is false, this object does nothing.
541     ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
542       : Self(Self) {
543       if (ManageScope)
544         Self->EnterScope(ScopeFlags);
545       else
546         this->Self = 0;
547     }
548
549     // Exit - Exit the scope associated with this object now, rather
550     // than waiting until the object is destroyed.
551     void Exit() {
552       if (Self) {
553         Self->ExitScope();
554         Self = 0;
555       }
556     }
557
558     ~ParseScope() {
559       Exit();
560     }
561   };
562
563   /// EnterScope - Start a new scope.
564   void EnterScope(unsigned ScopeFlags);
565
566   /// ExitScope - Pop a scope off the scope stack.
567   void ExitScope();
568
569   /// \brief RAII object used to modify the scope flags for the current scope.
570   class ParseScopeFlags {
571     Scope *CurScope;
572     unsigned OldFlags;
573     ParseScopeFlags(const ParseScopeFlags &); // do not implement
574     void operator=(const ParseScopeFlags &); // do not implement
575
576   public:
577     ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
578     ~ParseScopeFlags();
579   };
580
581   //===--------------------------------------------------------------------===//
582   // Diagnostic Emission and Error recovery.
583
584 public:
585   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
586   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
587
588 private:
589   void SuggestParentheses(SourceLocation Loc, unsigned DK,
590                           SourceRange ParenRange);
591
592   /// SkipUntil - Read tokens until we get to the specified token, then consume
593   /// it (unless DontConsume is true).  Because we cannot guarantee that the
594   /// token will ever occur, this skips to the next token, or to some likely
595   /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
596   /// character.
597   ///
598   /// If SkipUntil finds the specified token, it returns true, otherwise it
599   /// returns false.
600   bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
601                  bool DontConsume = false, bool StopAtCodeCompletion = false) {
602     return SkipUntil(&T, 1, StopAtSemi, DontConsume, StopAtCodeCompletion);
603   }
604   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
605                  bool DontConsume = false, bool StopAtCodeCompletion = false) {
606     tok::TokenKind TokArray[] = {T1, T2};
607     return SkipUntil(TokArray, 2, StopAtSemi, DontConsume,StopAtCodeCompletion);
608   }
609   bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
610                  bool StopAtSemi = true, bool DontConsume = false,
611                  bool StopAtCodeCompletion = false);
612
613   //===--------------------------------------------------------------------===//
614   // Lexing and parsing of C++ inline methods.
615
616   struct ParsingClass;
617
618   /// [class.mem]p1: "... the class is regarded as complete within
619   /// - function bodies
620   /// - default arguments
621   /// - exception-specifications (TODO: C++0x)
622   /// - and brace-or-equal-initializers for non-static data members
623   /// (including such things in nested classes)."
624   /// LateParsedDeclarations build the tree of those elements so they can
625   /// be parsed after parsing the top-level class.
626   class LateParsedDeclaration {
627   public:
628     virtual ~LateParsedDeclaration();
629
630     virtual void ParseLexedMethodDeclarations();
631     virtual void ParseLexedMemberInitializers();
632     virtual void ParseLexedMethodDefs();
633   };
634
635   /// Inner node of the LateParsedDeclaration tree that parses
636   /// all its members recursively.
637   class LateParsedClass : public LateParsedDeclaration {
638   public:
639     LateParsedClass(Parser *P, ParsingClass *C);
640     virtual ~LateParsedClass();
641
642     virtual void ParseLexedMethodDeclarations();
643     virtual void ParseLexedMemberInitializers();
644     virtual void ParseLexedMethodDefs();
645
646   private:
647     Parser *Self;
648     ParsingClass *Class;
649   };
650
651   /// Contains the lexed tokens of a member function definition
652   /// which needs to be parsed at the end of the class declaration
653   /// after parsing all other member declarations.
654   struct LexedMethod : public LateParsedDeclaration {
655     Parser *Self;
656     Decl *D;
657     CachedTokens Toks;
658
659     /// \brief Whether this member function had an associated template
660     /// scope. When true, D is a template declaration.
661     /// othewise, it is a member function declaration.
662     bool TemplateScope;
663
664     explicit LexedMethod(Parser* P, Decl *MD)
665       : Self(P), D(MD), TemplateScope(false) {}
666
667     virtual void ParseLexedMethodDefs();
668   };
669
670   /// LateParsedDefaultArgument - Keeps track of a parameter that may
671   /// have a default argument that cannot be parsed yet because it
672   /// occurs within a member function declaration inside the class
673   /// (C++ [class.mem]p2).
674   struct LateParsedDefaultArgument {
675     explicit LateParsedDefaultArgument(Decl *P,
676                                        CachedTokens *Toks = 0)
677       : Param(P), Toks(Toks) { }
678
679     /// Param - The parameter declaration for this parameter.
680     Decl *Param;
681
682     /// Toks - The sequence of tokens that comprises the default
683     /// argument expression, not including the '=' or the terminating
684     /// ')' or ','. This will be NULL for parameters that have no
685     /// default argument.
686     CachedTokens *Toks;
687   };
688
689   /// LateParsedMethodDeclaration - A method declaration inside a class that
690   /// contains at least one entity whose parsing needs to be delayed
691   /// until the class itself is completely-defined, such as a default
692   /// argument (C++ [class.mem]p2).
693   struct LateParsedMethodDeclaration : public LateParsedDeclaration {
694     explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
695       : Self(P), Method(M), TemplateScope(false) { }
696
697     virtual void ParseLexedMethodDeclarations();
698
699     Parser* Self;
700
701     /// Method - The method declaration.
702     Decl *Method;
703
704     /// \brief Whether this member function had an associated template
705     /// scope. When true, D is a template declaration.
706     /// othewise, it is a member function declaration.
707     bool TemplateScope;
708
709     /// DefaultArgs - Contains the parameters of the function and
710     /// their default arguments. At least one of the parameters will
711     /// have a default argument, but all of the parameters of the
712     /// method will be stored so that they can be reintroduced into
713     /// scope at the appropriate times.
714     llvm::SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
715   };
716
717   /// LateParsedMemberInitializer - An initializer for a non-static class data
718   /// member whose parsing must to be delayed until the class is completely
719   /// defined (C++11 [class.mem]p2).
720   struct LateParsedMemberInitializer : public LateParsedDeclaration {
721     LateParsedMemberInitializer(Parser *P, Decl *FD)
722       : Self(P), Field(FD) { }
723
724     virtual void ParseLexedMemberInitializers();
725
726     Parser *Self;
727
728     /// Field - The field declaration.
729     Decl *Field;
730
731     /// CachedTokens - The sequence of tokens that comprises the initializer,
732     /// including any leading '='.
733     CachedTokens Toks;
734   };
735
736   /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
737   /// C++ class, its method declarations that contain parts that won't be
738   /// parsed until after the definition is completed (C++ [class.mem]p2),
739   /// the method declarations and possibly attached inline definitions
740   /// will be stored here with the tokens that will be parsed to create those entities.
741   typedef llvm::SmallVector<LateParsedDeclaration*, 2> LateParsedDeclarationsContainer;
742
743   /// \brief Representation of a class that has been parsed, including
744   /// any member function declarations or definitions that need to be
745   /// parsed after the corresponding top-level class is complete.
746   struct ParsingClass {
747     ParsingClass(Decl *TagOrTemplate, bool TopLevelClass)
748       : TopLevelClass(TopLevelClass), TemplateScope(false),
749         TagOrTemplate(TagOrTemplate) { }
750
751     /// \brief Whether this is a "top-level" class, meaning that it is
752     /// not nested within another class.
753     bool TopLevelClass : 1;
754
755     /// \brief Whether this class had an associated template
756     /// scope. When true, TagOrTemplate is a template declaration;
757     /// othewise, it is a tag declaration.
758     bool TemplateScope : 1;
759
760     /// \brief The class or class template whose definition we are parsing.
761     Decl *TagOrTemplate;
762
763     /// LateParsedDeclarations - Method declarations, inline definitions and
764     /// nested classes that contain pieces whose parsing will be delayed until
765     /// the top-level class is fully defined.
766     LateParsedDeclarationsContainer LateParsedDeclarations;
767   };
768
769   /// \brief The stack of classes that is currently being
770   /// parsed. Nested and local classes will be pushed onto this stack
771   /// when they are parsed, and removed afterward.
772   std::stack<ParsingClass *> ClassStack;
773
774   ParsingClass &getCurrentClass() {
775     assert(!ClassStack.empty() && "No lexed method stacks!");
776     return *ClassStack.top();
777   }
778
779   /// \brief RAII object used to inform the actions that we're
780   /// currently parsing a declaration.  This is active when parsing a
781   /// variable's initializer, but not when parsing the body of a
782   /// class or function definition.
783   class ParsingDeclRAIIObject {
784     Sema &Actions;
785     Sema::ParsingDeclState State;
786     bool Popped;
787
788   public:
789     ParsingDeclRAIIObject(Parser &P) : Actions(P.Actions) {
790       push();
791     }
792
793     ParsingDeclRAIIObject(Parser &P, ParsingDeclRAIIObject *Other)
794         : Actions(P.Actions) {
795       if (Other) steal(*Other);
796       else push();
797     }
798
799     /// Creates a RAII object which steals the state from a different
800     /// object instead of pushing.
801     ParsingDeclRAIIObject(ParsingDeclRAIIObject &Other)
802         : Actions(Other.Actions) {
803       steal(Other);
804     }
805
806     ~ParsingDeclRAIIObject() {
807       abort();
808     }
809
810     /// Resets the RAII object for a new declaration.
811     void reset() {
812       abort();
813       push();
814     }
815
816     /// Signals that the context was completed without an appropriate
817     /// declaration being parsed.
818     void abort() {
819       pop(0);
820     }
821
822     void complete(Decl *D) {
823       assert(!Popped && "ParsingDeclaration has already been popped!");
824       pop(D);
825     }
826
827   private:
828     void steal(ParsingDeclRAIIObject &Other) {
829       State = Other.State;
830       Popped = Other.Popped;
831       Other.Popped = true;
832     }
833     
834     void push() {
835       State = Actions.PushParsingDeclaration();
836       Popped = false;
837     }
838
839     void pop(Decl *D) {
840       if (!Popped) {
841         Actions.PopParsingDeclaration(State, D);
842         Popped = true;
843       }
844     }
845   };
846
847   /// A class for parsing a DeclSpec.
848   class ParsingDeclSpec : public DeclSpec {
849     ParsingDeclRAIIObject ParsingRAII;
850
851   public:
852     ParsingDeclSpec(Parser &P) : DeclSpec(P.AttrFactory), ParsingRAII(P) {}
853     ParsingDeclSpec(Parser &P, ParsingDeclRAIIObject *RAII)
854       : DeclSpec(P.AttrFactory), ParsingRAII(P, RAII) {}
855
856     void complete(Decl *D) {
857       ParsingRAII.complete(D);
858     }
859
860     void abort() {
861       ParsingRAII.abort();
862     }
863   };
864
865   /// A class for parsing a declarator.
866   class ParsingDeclarator : public Declarator {
867     ParsingDeclRAIIObject ParsingRAII;
868
869   public:
870     ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, TheContext C)
871       : Declarator(DS, C), ParsingRAII(P) {
872     }
873
874     const ParsingDeclSpec &getDeclSpec() const {
875       return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec());
876     }
877
878     ParsingDeclSpec &getMutableDeclSpec() const {
879       return const_cast<ParsingDeclSpec&>(getDeclSpec());
880     }
881
882     void clear() {
883       Declarator::clear();
884       ParsingRAII.reset();
885     }
886
887     void complete(Decl *D) {
888       ParsingRAII.complete(D);
889     }
890   };
891
892   /// \brief RAII object used to
893   class ParsingClassDefinition {
894     Parser &P;
895     bool Popped;
896     Sema::ParsingClassState State;
897
898   public:
899     ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass)
900       : P(P), Popped(false),
901         State(P.PushParsingClass(TagOrTemplate, TopLevelClass)) {
902     }
903
904     /// \brief Pop this class of the stack.
905     void Pop() {
906       assert(!Popped && "Nested class has already been popped");
907       Popped = true;
908       P.PopParsingClass(State);
909     }
910
911     ~ParsingClassDefinition() {
912       if (!Popped)
913         P.PopParsingClass(State);
914     }
915   };
916
917   /// \brief Contains information about any template-specific
918   /// information that has been parsed prior to parsing declaration
919   /// specifiers.
920   struct ParsedTemplateInfo {
921     ParsedTemplateInfo()
922       : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
923
924     ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
925                        bool isSpecialization,
926                        bool lastParameterListWasEmpty = false)
927       : Kind(isSpecialization? ExplicitSpecialization : Template),
928         TemplateParams(TemplateParams), 
929         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
930
931     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
932                                 SourceLocation TemplateLoc)
933       : Kind(ExplicitInstantiation), TemplateParams(0),
934         ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
935         LastParameterListWasEmpty(false){ }
936
937     /// \brief The kind of template we are parsing.
938     enum {
939       /// \brief We are not parsing a template at all.
940       NonTemplate = 0,
941       /// \brief We are parsing a template declaration.
942       Template,
943       /// \brief We are parsing an explicit specialization.
944       ExplicitSpecialization,
945       /// \brief We are parsing an explicit instantiation.
946       ExplicitInstantiation
947     } Kind;
948
949     /// \brief The template parameter lists, for template declarations
950     /// and explicit specializations.
951     TemplateParameterLists *TemplateParams;
952
953     /// \brief The location of the 'extern' keyword, if any, for an explicit
954     /// instantiation
955     SourceLocation ExternLoc;
956
957     /// \brief The location of the 'template' keyword, for an explicit
958     /// instantiation.
959     SourceLocation TemplateLoc;
960     
961     /// \brief Whether the last template parameter list was empty.
962     bool LastParameterListWasEmpty;
963
964     SourceRange getSourceRange() const;
965   };
966
967   /// \brief Contains a late templated function.
968   /// Will be parsed at the end of the translation unit.
969   struct LateParsedTemplatedFunction {
970     explicit LateParsedTemplatedFunction(Parser* P, Decl *MD)
971       : D(MD) {}
972
973     CachedTokens Toks;
974     
975     /// \brief The template function declaration to be late parsed.
976     Decl *D; 
977   };
978
979   void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
980   void ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT);
981   typedef llvm::DenseMap<const FunctionDecl*, LateParsedTemplatedFunction*>
982     LateParsedTemplateMapT;
983   LateParsedTemplateMapT LateParsedTemplateMap;
984
985   static void LateTemplateParserCallback(void *P, const FunctionDecl *FD);
986   void LateTemplateParser(const FunctionDecl *FD);
987
988   Sema::ParsingClassState
989   PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass);
990   void DeallocateParsedClasses(ParsingClass *Class);
991   void PopParsingClass(Sema::ParsingClassState);
992
993   Decl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsingDeclarator &D,
994                                 const ParsedTemplateInfo &TemplateInfo,
995                                 const VirtSpecifiers& VS, ExprResult& Init);
996   void ParseCXXNonStaticMemberInitializer(Decl *VarD);
997   void ParseLexedMethodDeclarations(ParsingClass &Class);
998   void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
999   void ParseLexedMethodDefs(ParsingClass &Class);
1000   void ParseLexedMethodDef(LexedMethod &LM);
1001   void ParseLexedMemberInitializers(ParsingClass &Class);
1002   void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
1003   bool ConsumeAndStoreUntil(tok::TokenKind T1,
1004                             CachedTokens &Toks,
1005                             bool StopAtSemi = true,
1006                             bool ConsumeFinalToken = true) {
1007     return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
1008   }
1009   bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
1010                             CachedTokens &Toks,
1011                             bool StopAtSemi = true,
1012                             bool ConsumeFinalToken = true);
1013
1014   //===--------------------------------------------------------------------===//
1015   // C99 6.9: External Definitions.
1016   struct ParsedAttributesWithRange : ParsedAttributes {
1017     ParsedAttributesWithRange(AttributeFactory &factory)
1018       : ParsedAttributes(factory) {}
1019
1020     SourceRange Range;
1021   };
1022
1023   DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
1024                                           ParsingDeclSpec *DS = 0);
1025   bool isDeclarationAfterDeclarator();
1026   bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
1027   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs,
1028                                                   AccessSpecifier AS = AS_none);
1029   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
1030                                                   AccessSpecifier AS = AS_none);
1031   
1032   Decl *ParseFunctionDefinition(ParsingDeclarator &D,
1033                  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1034   void ParseKNRParamDeclarations(Declarator &D);
1035   // EndLoc, if non-NULL, is filled with the location of the last token of
1036   // the simple-asm.
1037   ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
1038   ExprResult ParseAsmStringLiteral();
1039
1040   // Objective-C External Declarations
1041   Decl *ParseObjCAtDirectives();
1042   Decl *ParseObjCAtClassDeclaration(SourceLocation atLoc);
1043   Decl *ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
1044                                         ParsedAttributes &prefixAttrs);
1045   void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1046                                        tok::ObjCKeywordKind visibility,
1047                                        SourceLocation atLoc);
1048   bool ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &P,
1049                                    llvm::SmallVectorImpl<SourceLocation> &PLocs,
1050                                    bool WarnOnDeclarations,
1051                                    SourceLocation &LAngleLoc,
1052                                    SourceLocation &EndProtoLoc);
1053   bool ParseObjCProtocolQualifiers(DeclSpec &DS);
1054   void ParseObjCInterfaceDeclList(Decl *interfaceDecl,
1055                                   tok::ObjCKeywordKind contextKey);
1056   Decl *ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
1057                                        ParsedAttributes &prefixAttrs);
1058
1059   Decl *ObjCImpDecl;
1060   llvm::SmallVector<Decl *, 4> PendingObjCImpDecl;
1061
1062   Decl *ParseObjCAtImplementationDeclaration(SourceLocation atLoc);
1063   Decl *ParseObjCAtEndDeclaration(SourceRange atEnd);
1064   Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
1065   Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
1066   Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
1067
1068   IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
1069   // Definitions for Objective-c context sensitive keywords recognition.
1070   enum ObjCTypeQual {
1071     objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
1072     objc_NumQuals
1073   };
1074   IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
1075
1076   bool isTokIdentifier_in() const;
1077
1078   /// \brief The context in which we are parsing an Objective-C type name.
1079   enum ObjCTypeNameContext {
1080     OTN_ResultType,
1081     OTN_ParameterType
1082   };
1083   
1084   ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, ObjCTypeNameContext Context);
1085   void ParseObjCMethodRequirement();
1086   Decl *ParseObjCMethodPrototype(Decl *classOrCat,
1087             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1088             bool MethodDefinition = true);
1089   Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
1090                                 Decl *classDecl,
1091             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
1092             bool MethodDefinition=true);
1093   void ParseObjCPropertyAttribute(ObjCDeclSpec &DS, Decl *ClassDecl);
1094
1095   Decl *ParseObjCMethodDefinition();
1096
1097   //===--------------------------------------------------------------------===//
1098   // C99 6.5: Expressions.
1099   
1100   ExprResult ParseExpression();
1101   ExprResult ParseConstantExpression();
1102   // Expr that doesn't include commas.
1103   ExprResult ParseAssignmentExpression();
1104
1105   ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
1106
1107   ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
1108
1109   ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
1110                                         prec::Level MinPrec);
1111   ExprResult ParseCastExpression(bool isUnaryExpression,
1112                                  bool isAddressOfOperand,
1113                                  bool &NotCastExpr,
1114                                  bool isTypeCast);
1115   ExprResult ParseCastExpression(bool isUnaryExpression,
1116                                  bool isAddressOfOperand = false,
1117                                  bool isTypeCast = false);
1118
1119   /// Returns true if the next token would start a postfix-expression
1120   /// suffix.
1121   bool isPostfixExpressionSuffixStart() {
1122     tok::TokenKind K = Tok.getKind();
1123     return (K == tok::l_square || K == tok::l_paren ||
1124             K == tok::period || K == tok::arrow ||
1125             K == tok::plusplus || K == tok::minusminus);
1126   }
1127
1128   ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
1129   ExprResult ParseUnaryExprOrTypeTraitExpression();
1130   ExprResult ParseBuiltinPrimaryExpression();
1131
1132   ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1133                                                      bool &isCastExpr,
1134                                                      ParsedType &CastTy,
1135                                                      SourceRange &CastRange);
1136
1137   typedef llvm::SmallVector<Expr*, 20> ExprListTy;
1138   typedef llvm::SmallVector<SourceLocation, 20> CommaLocsTy;
1139
1140   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1141   bool ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs,
1142                            llvm::SmallVectorImpl<SourceLocation> &CommaLocs,
1143                            void (Sema::*Completer)(Scope *S,
1144                                                    Expr *Data,
1145                                                    Expr **Args,
1146                                                    unsigned NumArgs) = 0,
1147                            Expr *Data = 0);
1148
1149   /// ParenParseOption - Control what ParseParenExpression will parse.
1150   enum ParenParseOption {
1151     SimpleExpr,      // Only parse '(' expression ')'
1152     CompoundStmt,    // Also allow '(' compound-statement ')'
1153     CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
1154     CastExpr         // Also allow '(' type-name ')' <anything>
1155   };
1156   ExprResult ParseParenExpression(ParenParseOption &ExprType,
1157                                         bool stopIfCastExpr,
1158                                         bool isTypeCast,
1159                                         ParsedType &CastTy,
1160                                         SourceLocation &RParenLoc);
1161
1162   ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1163                                                     ParsedType &CastTy,
1164                                                     SourceLocation LParenLoc,
1165                                                     SourceLocation &RParenLoc);
1166
1167   ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
1168                                                   SourceLocation LParenLoc,
1169                                                   SourceLocation RParenLoc);
1170
1171   ExprResult ParseStringLiteralExpression();
1172
1173   ExprResult ParseGenericSelectionExpression();
1174
1175   //===--------------------------------------------------------------------===//
1176   // C++ Expressions
1177   ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
1178
1179   bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
1180                                       ParsedType ObjectType,
1181                                       bool EnteringContext,
1182                                       bool *MayBePseudoDestructor = 0,
1183                                       bool IsTypename = false);
1184
1185   //===--------------------------------------------------------------------===//
1186   // C++ 5.2p1: C++ Casts
1187   ExprResult ParseCXXCasts();
1188
1189   //===--------------------------------------------------------------------===//
1190   // C++ 5.2p1: C++ Type Identification
1191   ExprResult ParseCXXTypeid();
1192
1193   //===--------------------------------------------------------------------===//
1194   //  C++ : Microsoft __uuidof Expression
1195   ExprResult ParseCXXUuidof();
1196
1197   //===--------------------------------------------------------------------===//
1198   // C++ 5.2.4: C++ Pseudo-Destructor Expressions
1199   ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1200                                             tok::TokenKind OpKind,
1201                                             CXXScopeSpec &SS,
1202                                             ParsedType ObjectType);
1203
1204   //===--------------------------------------------------------------------===//
1205   // C++ 9.3.2: C++ 'this' pointer
1206   ExprResult ParseCXXThis();
1207
1208   //===--------------------------------------------------------------------===//
1209   // C++ 15: C++ Throw Expression
1210   ExprResult ParseThrowExpression();
1211
1212   ExceptionSpecificationType MaybeParseExceptionSpecification(
1213                     SourceRange &SpecificationRange,
1214                     llvm::SmallVectorImpl<ParsedType> &DynamicExceptions,
1215                     llvm::SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
1216                     ExprResult &NoexceptExpr);
1217
1218   // EndLoc is filled with the location of the last token of the specification.
1219   ExceptionSpecificationType ParseDynamicExceptionSpecification(
1220                                   SourceRange &SpecificationRange,
1221                                   llvm::SmallVectorImpl<ParsedType> &Exceptions,
1222                                   llvm::SmallVectorImpl<SourceRange> &Ranges);
1223
1224   //===--------------------------------------------------------------------===//
1225   // C++0x 8: Function declaration trailing-return-type
1226   TypeResult ParseTrailingReturnType();
1227
1228   //===--------------------------------------------------------------------===//
1229   // C++ 2.13.5: C++ Boolean Literals
1230   ExprResult ParseCXXBoolLiteral();
1231
1232   //===--------------------------------------------------------------------===//
1233   // C++ 5.2.3: Explicit type conversion (functional notation)
1234   ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
1235
1236   bool isCXXSimpleTypeSpecifier() const;
1237
1238   /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1239   /// This should only be called when the current token is known to be part of
1240   /// simple-type-specifier.
1241   void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
1242
1243   bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
1244
1245   //===--------------------------------------------------------------------===//
1246   // C++ 5.3.4 and 5.3.5: C++ new and delete
1247   bool ParseExpressionListOrTypeId(llvm::SmallVectorImpl<Expr*> &Exprs,
1248                                    Declarator &D);
1249   void ParseDirectNewDeclarator(Declarator &D);
1250   ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
1251   ExprResult ParseCXXDeleteExpression(bool UseGlobal,
1252                                             SourceLocation Start);
1253
1254   //===--------------------------------------------------------------------===//
1255   // C++ if/switch/while condition expression.
1256   bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
1257                          SourceLocation Loc, bool ConvertToBoolean);
1258
1259   //===--------------------------------------------------------------------===//
1260   // C++ types
1261
1262   //===--------------------------------------------------------------------===//
1263   // C99 6.7.8: Initialization.
1264
1265   /// ParseInitializer
1266   ///       initializer: [C99 6.7.8]
1267   ///         assignment-expression
1268   ///         '{' ...
1269   ExprResult ParseInitializer() {
1270     if (Tok.isNot(tok::l_brace))
1271       return ParseAssignmentExpression();
1272     return ParseBraceInitializer();
1273   }
1274   ExprResult ParseBraceInitializer();
1275   ExprResult ParseInitializerWithPotentialDesignator();
1276
1277   //===--------------------------------------------------------------------===//
1278   // clang Expressions
1279
1280   ExprResult ParseBlockLiteralExpression();  // ^{...}
1281
1282   //===--------------------------------------------------------------------===//
1283   // Objective-C Expressions
1284   ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
1285   ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
1286   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
1287   ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
1288   ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
1289   bool isSimpleObjCMessageExpression();
1290   ExprResult ParseObjCMessageExpression();
1291   ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
1292                                                   SourceLocation SuperLoc,
1293                                                   ParsedType ReceiverType,
1294                                                   ExprArg ReceiverExpr);
1295   ExprResult ParseAssignmentExprWithObjCMessageExprStart(
1296       SourceLocation LBracloc, SourceLocation SuperLoc,
1297       ParsedType ReceiverType, ExprArg ReceiverExpr);
1298   bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
1299
1300   //===--------------------------------------------------------------------===//
1301   // C99 6.8: Statements and Blocks.
1302
1303   StmtResult ParseStatement() {
1304     StmtVector Stmts(Actions);
1305     return ParseStatementOrDeclaration(Stmts, true);
1306   }
1307   StmtResult ParseStatementOrDeclaration(StmtVector& Stmts,
1308                                          bool OnlyStatement = false);
1309   StmtResult ParseExprStatement(ParsedAttributes &Attrs);
1310   StmtResult ParseLabeledStatement(ParsedAttributes &Attr);
1311   StmtResult ParseCaseStatement(ParsedAttributes &Attr,
1312                                 bool MissingCase = false,
1313                                 ExprResult Expr = ExprResult());
1314   StmtResult ParseDefaultStatement(ParsedAttributes &Attr);
1315   StmtResult ParseCompoundStatement(ParsedAttributes &Attr,
1316                                     bool isStmtExpr = false);
1317   StmtResult ParseCompoundStatement(ParsedAttributes &Attr,
1318                                     bool isStmtExpr,
1319                                     unsigned ScopeFlags);
1320   StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
1321   bool ParseParenExprOrCondition(ExprResult &ExprResult,
1322                                  Decl *&DeclResult,
1323                                  SourceLocation Loc,
1324                                  bool ConvertToBoolean);
1325   StmtResult ParseIfStatement(ParsedAttributes &Attr);
1326   StmtResult ParseSwitchStatement(ParsedAttributes &Attr);
1327   StmtResult ParseWhileStatement(ParsedAttributes &Attr);
1328   StmtResult ParseDoStatement(ParsedAttributes &Attr);
1329   StmtResult ParseForStatement(ParsedAttributes &Attr);
1330   StmtResult ParseGotoStatement(ParsedAttributes &Attr);
1331   StmtResult ParseContinueStatement(ParsedAttributes &Attr);
1332   StmtResult ParseBreakStatement(ParsedAttributes &Attr);
1333   StmtResult ParseReturnStatement(ParsedAttributes &Attr);
1334   StmtResult ParseAsmStatement(bool &msAsm);
1335   StmtResult FuzzyParseMicrosoftAsmStatement(SourceLocation AsmLoc);
1336   bool ParseMicrosoftIfExistsCondition(bool& Result);
1337   void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
1338   void ParseMicrosoftIfExistsExternalDeclaration();
1339   void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
1340                                               AccessSpecifier& CurAS);
1341 bool ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
1342                            llvm::SmallVectorImpl<ExprTy *> &Constraints,
1343                            llvm::SmallVectorImpl<ExprTy *> &Exprs);
1344
1345   //===--------------------------------------------------------------------===//
1346   // C++ 6: Statements and Blocks
1347
1348   StmtResult ParseCXXTryBlock(ParsedAttributes &Attr);
1349   StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc);
1350   StmtResult ParseCXXCatchBlock();
1351
1352   //===--------------------------------------------------------------------===//
1353   // MS: SEH Statements and Blocks
1354
1355   StmtResult ParseSEHTryBlock(ParsedAttributes &Attr);
1356   StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
1357   StmtResult ParseSEHExceptBlock(SourceLocation Loc);
1358   StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
1359
1360   //===--------------------------------------------------------------------===//
1361   // Objective-C Statements
1362
1363   StmtResult ParseObjCAtStatement(SourceLocation atLoc);
1364   StmtResult ParseObjCTryStmt(SourceLocation atLoc);
1365   StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
1366   StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
1367   StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
1368
1369
1370   //===--------------------------------------------------------------------===//
1371   // C99 6.7: Declarations.
1372
1373   /// A context for parsing declaration specifiers.  TODO: flesh this
1374   /// out, there are other significant restrictions on specifiers than
1375   /// would be best implemented in the parser.
1376   enum DeclSpecContext {
1377     DSC_normal, // normal context
1378     DSC_class,  // class context, enables 'friend'
1379     DSC_top_level // top-level/namespace declaration context
1380   };
1381
1382   /// Information on a C++0x for-range-initializer found while parsing a
1383   /// declaration which turns out to be a for-range-declaration.
1384   struct ForRangeInit {
1385     SourceLocation ColonLoc;
1386     ExprResult RangeExpr;
1387
1388     bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
1389   };
1390
1391   DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
1392                                   unsigned Context, SourceLocation &DeclEnd,
1393                                   ParsedAttributesWithRange &attrs);
1394   DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
1395                                         unsigned Context,
1396                                         SourceLocation &DeclEnd,
1397                                         ParsedAttributes &attrs,
1398                                         bool RequireSemi,
1399                                         ForRangeInit *FRI = 0);
1400   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
1401                                 bool AllowFunctionDefinitions,
1402                                 SourceLocation *DeclEnd = 0,
1403                                 ForRangeInit *FRI = 0);
1404   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
1405                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1406   bool ParseAttributesAfterDeclarator(Declarator &D);
1407   Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1408                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
1409   Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
1410   Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
1411
1412   /// \brief When in code-completion, skip parsing of the function/method body
1413   /// unless the body contains the code-completion point.
1414   ///
1415   /// \returns true if the function body was skipped.
1416   bool trySkippingFunctionBodyForCodeCompletion();
1417
1418   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1419                         const ParsedTemplateInfo &TemplateInfo,
1420                         AccessSpecifier AS);
1421   DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
1422   void ParseDeclarationSpecifiers(DeclSpec &DS,
1423                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1424                                   AccessSpecifier AS = AS_none,
1425                                   DeclSpecContext DSC = DSC_normal);
1426   bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid,
1427                                   const char *&PrevSpec,
1428                                   unsigned &DiagID,
1429                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1430                                   bool SuppressDeclarations = false);
1431
1432   void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none);
1433
1434   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 
1435                                   ObjCTypeNameContext Context);
1436
1437   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
1438                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1439                 AccessSpecifier AS = AS_none);
1440   void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
1441   void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
1442                             Decl *TagDecl);
1443
1444   struct FieldCallback {
1445     virtual Decl *invoke(FieldDeclarator &Field) = 0;
1446     virtual ~FieldCallback() {}
1447
1448   private:
1449     virtual void _anchor();
1450   };
1451   struct ObjCPropertyCallback;
1452
1453   void ParseStructDeclaration(DeclSpec &DS, FieldCallback &Callback);
1454
1455   bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
1456   bool isTypeSpecifierQualifier();
1457   bool isTypeQualifier() const;
1458   
1459   /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
1460   /// is definitely a type-specifier.  Return false if it isn't part of a type
1461   /// specifier or if we're not sure.
1462   bool isKnownToBeTypeSpecifier(const Token &Tok) const;
1463
1464   /// isDeclarationStatement - Disambiguates between a declaration or an
1465   /// expression statement, when parsing function bodies.
1466   /// Returns true for declaration, false for expression.
1467   bool isDeclarationStatement() {
1468     if (getLang().CPlusPlus)
1469       return isCXXDeclarationStatement();
1470     return isDeclarationSpecifier(true);
1471   }
1472
1473   /// isSimpleDeclaration - Disambiguates between a declaration or an
1474   /// expression, mainly used for the C 'clause-1' or the C++
1475   // 'for-init-statement' part of a 'for' statement.
1476   /// Returns true for declaration, false for expression.
1477   bool isSimpleDeclaration() {
1478     if (getLang().CPlusPlus)
1479       return isCXXSimpleDeclaration();
1480     return isDeclarationSpecifier(true);
1481   }
1482
1483   /// \brief Determine whether we are currently at the start of an Objective-C
1484   /// class message that appears to be missing the open bracket '['.
1485   bool isStartOfObjCClassMessageMissingOpenBracket();
1486   
1487   /// \brief Starting with a scope specifier, identifier, or
1488   /// template-id that refers to the current class, determine whether
1489   /// this is a constructor declarator.
1490   bool isConstructorDeclarator();
1491
1492   /// \brief Specifies the context in which type-id/expression
1493   /// disambiguation will occur.
1494   enum TentativeCXXTypeIdContext {
1495     TypeIdInParens,
1496     TypeIdAsTemplateArgument
1497   };
1498
1499
1500   /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
1501   /// whether the parens contain an expression or a type-id.
1502   /// Returns true for a type-id and false for an expression.
1503   bool isTypeIdInParens(bool &isAmbiguous) {
1504     if (getLang().CPlusPlus)
1505       return isCXXTypeId(TypeIdInParens, isAmbiguous);
1506     isAmbiguous = false;
1507     return isTypeSpecifierQualifier();
1508   }
1509   bool isTypeIdInParens() {
1510     bool isAmbiguous;
1511     return isTypeIdInParens(isAmbiguous);
1512   }
1513
1514   /// isCXXDeclarationStatement - C++-specialized function that disambiguates
1515   /// between a declaration or an expression statement, when parsing function
1516   /// bodies. Returns true for declaration, false for expression.
1517   bool isCXXDeclarationStatement();
1518
1519   /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
1520   /// between a simple-declaration or an expression-statement.
1521   /// If during the disambiguation process a parsing error is encountered,
1522   /// the function returns true to let the declaration parsing code handle it.
1523   /// Returns false if the statement is disambiguated as expression.
1524   bool isCXXSimpleDeclaration();
1525
1526   /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1527   /// a constructor-style initializer, when parsing declaration statements.
1528   /// Returns true for function declarator and false for constructor-style
1529   /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to
1530   /// indicate that the parens were disambiguated as function declarator.
1531   /// If during the disambiguation process a parsing error is encountered,
1532   /// the function returns true to let the declaration parsing code handle it.
1533   bool isCXXFunctionDeclarator(bool warnIfAmbiguous);
1534
1535   /// isCXXConditionDeclaration - Disambiguates between a declaration or an
1536   /// expression for a condition of a if/switch/while/for statement.
1537   /// If during the disambiguation process a parsing error is encountered,
1538   /// the function returns true to let the declaration parsing code handle it.
1539   bool isCXXConditionDeclaration();
1540
1541   bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
1542   bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
1543     bool isAmbiguous;
1544     return isCXXTypeId(Context, isAmbiguous);
1545   }
1546
1547   /// TPResult - Used as the result value for functions whose purpose is to
1548   /// disambiguate C++ constructs by "tentatively parsing" them.
1549   /// This is a class instead of a simple enum because the implicit enum-to-bool
1550   /// conversions may cause subtle bugs.
1551   class TPResult {
1552     enum Result {
1553       TPR_true,
1554       TPR_false,
1555       TPR_ambiguous,
1556       TPR_error
1557     };
1558     Result Res;
1559     TPResult(Result result) : Res(result) {}
1560   public:
1561     static TPResult True() { return TPR_true; }
1562     static TPResult False() { return TPR_false; }
1563     static TPResult Ambiguous() { return TPR_ambiguous; }
1564     static TPResult Error() { return TPR_error; }
1565
1566     bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
1567     bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
1568   };
1569
1570   /// \brief Based only on the given token kind, determine whether we know that
1571   /// we're at the start of an expression or a type-specifier-seq (which may
1572   /// be an expression, in C++).
1573   ///
1574   /// This routine does not attempt to resolve any of the trick cases, e.g.,
1575   /// those involving lookup of identifiers.
1576   ///
1577   /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
1578   /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
1579   /// tell.
1580   TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
1581
1582   /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
1583   /// declaration specifier, TPResult::False() if it is not,
1584   /// TPResult::Ambiguous() if it could be either a decl-specifier or a
1585   /// function-style cast, and TPResult::Error() if a parsing error was
1586   /// encountered.
1587   /// Doesn't consume tokens.
1588   TPResult isCXXDeclarationSpecifier();
1589   
1590   // "Tentative parsing" functions, used for disambiguation. If a parsing error
1591   // is encountered they will return TPResult::Error().
1592   // Returning TPResult::True()/False() indicates that the ambiguity was
1593   // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
1594   // that more tentative parsing is necessary for disambiguation.
1595   // They all consume tokens, so backtracking should be used after calling them.
1596
1597   TPResult TryParseDeclarationSpecifier();
1598   TPResult TryParseSimpleDeclaration();
1599   TPResult TryParseTypeofSpecifier();
1600   TPResult TryParseProtocolQualifiers();
1601   TPResult TryParseInitDeclaratorList();
1602   TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
1603   TPResult TryParseParameterDeclarationClause();
1604   TPResult TryParseFunctionDeclarator();
1605   TPResult TryParseBracketDeclarator();
1606
1607   TypeResult ParseTypeName(SourceRange *Range = 0,
1608                            Declarator::TheContext Context
1609                              = Declarator::TypeNameContext,
1610                            ObjCDeclSpec *objcQuals = 0,
1611                            AccessSpecifier AS = AS_none,
1612                            Decl **OwnedType = 0);
1613   void ParseBlockId();
1614
1615   void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
1616     if (!attrs.Range.isValid()) return;
1617     DiagnoseProhibitedAttributes(attrs);
1618   }
1619   void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
1620
1621   void MaybeParseGNUAttributes(Declarator &D) {
1622     if (Tok.is(tok::kw___attribute)) {
1623       ParsedAttributes attrs(AttrFactory);
1624       SourceLocation endLoc;
1625       ParseGNUAttributes(attrs, &endLoc);
1626       D.takeAttributes(attrs, endLoc);
1627     }
1628   }
1629   void MaybeParseGNUAttributes(ParsedAttributes &attrs,
1630                                SourceLocation *endLoc = 0) {
1631     if (Tok.is(tok::kw___attribute))
1632       ParseGNUAttributes(attrs, endLoc);
1633   }
1634   void ParseGNUAttributes(ParsedAttributes &attrs,
1635                           SourceLocation *endLoc = 0);
1636
1637   void MaybeParseCXX0XAttributes(Declarator &D) {
1638     if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1639       ParsedAttributesWithRange attrs(AttrFactory);
1640       SourceLocation endLoc;
1641       ParseCXX0XAttributes(attrs, &endLoc);
1642       D.takeAttributes(attrs, endLoc);
1643     }
1644   }
1645   void MaybeParseCXX0XAttributes(ParsedAttributes &attrs,
1646                                  SourceLocation *endLoc = 0) {
1647     if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1648       ParsedAttributesWithRange attrsWithRange(AttrFactory);
1649       ParseCXX0XAttributes(attrsWithRange, endLoc);
1650       attrs.takeAllFrom(attrsWithRange);
1651     }
1652   }
1653   void MaybeParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
1654                                  SourceLocation *endLoc = 0) {
1655     if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1656       ParseCXX0XAttributes(attrs, endLoc);
1657   }
1658   void ParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
1659                             SourceLocation *EndLoc = 0);
1660
1661   void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
1662                                      SourceLocation *endLoc = 0) {
1663     if (getLang().Microsoft && Tok.is(tok::l_square))
1664       ParseMicrosoftAttributes(attrs, endLoc);
1665   }
1666   void ParseMicrosoftAttributes(ParsedAttributes &attrs,
1667                                 SourceLocation *endLoc = 0);
1668   void ParseMicrosoftDeclSpec(ParsedAttributes &attrs);
1669   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
1670   void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
1671   void ParseOpenCLAttributes(ParsedAttributes &attrs);
1672   void ParseOpenCLQualifiers(DeclSpec &DS);
1673
1674   VersionTuple ParseVersionTuple(SourceRange &Range);
1675   void ParseAvailabilityAttribute(IdentifierInfo &Availability,
1676                                   SourceLocation AvailabilityLoc,
1677                                   ParsedAttributes &attrs,
1678                                   SourceLocation *endLoc);
1679
1680   void ParseTypeofSpecifier(DeclSpec &DS);
1681   void ParseDecltypeSpecifier(DeclSpec &DS);
1682   void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
1683   
1684   ExprResult ParseCXX0XAlignArgument(SourceLocation Start);
1685
1686   VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const;
1687   void ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS);
1688
1689   bool isCXX0XFinalKeyword() const;
1690
1691   /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
1692   /// enter a new C++ declarator scope and exit it when the function is
1693   /// finished.
1694   class DeclaratorScopeObj {
1695     Parser &P;
1696     CXXScopeSpec &SS;
1697     bool EnteredScope;
1698     bool CreatedScope;
1699   public:
1700     DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
1701       : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
1702
1703     void EnterDeclaratorScope() {
1704       assert(!EnteredScope && "Already entered the scope!");
1705       assert(SS.isSet() && "C++ scope was not set!");
1706
1707       CreatedScope = true;
1708       P.EnterScope(0); // Not a decl scope.
1709
1710       if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
1711         EnteredScope = true;
1712     }
1713
1714     ~DeclaratorScopeObj() {
1715       if (EnteredScope) {
1716         assert(SS.isSet() && "C++ scope was cleared ?");
1717         P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
1718       }
1719       if (CreatedScope)
1720         P.ExitScope();
1721     }
1722   };
1723
1724   /// ParseDeclarator - Parse and verify a newly-initialized declarator.
1725   void ParseDeclarator(Declarator &D);
1726   /// A function that parses a variant of direct-declarator.
1727   typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
1728   void ParseDeclaratorInternal(Declarator &D,
1729                                DirectDeclParseFunction DirectDeclParser);
1730
1731   void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
1732                                  bool CXX0XAttributesAllowed = true);
1733   void ParseDirectDeclarator(Declarator &D);
1734   void ParseParenDeclarator(Declarator &D);
1735   void ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
1736                                ParsedAttributes &attrs,
1737                                bool RequiresArg = false);
1738   bool isFunctionDeclaratorIdentifierList();
1739   void ParseFunctionDeclaratorIdentifierList(
1740          Declarator &D,
1741          llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo);
1742   void ParseParameterDeclarationClause(
1743          Declarator &D,
1744          ParsedAttributes &attrs,
1745          llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
1746          SourceLocation &EllipsisLoc);
1747   void ParseBracketDeclarator(Declarator &D);
1748
1749   //===--------------------------------------------------------------------===//
1750   // C++ 7: Declarations [dcl.dcl]
1751
1752   bool isCXX0XAttributeSpecifier(bool FullLookahead = false, 
1753                                  tok::TokenKind *After = 0);
1754   
1755   Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
1756                        SourceLocation InlineLoc = SourceLocation());
1757   void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
1758                            std::vector<IdentifierInfo*>& Ident,
1759                            std::vector<SourceLocation>& NamespaceLoc,
1760                            unsigned int index, SourceLocation& InlineLoc,
1761                            SourceLocation& LBrace, ParsedAttributes& attrs,
1762                            SourceLocation& RBraceLoc);
1763   Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
1764   Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
1765                                          const ParsedTemplateInfo &TemplateInfo,
1766                                          SourceLocation &DeclEnd,
1767                                          ParsedAttributesWithRange &attrs,
1768                                          Decl **OwnedType = 0);
1769   Decl *ParseUsingDirective(unsigned Context,
1770                             SourceLocation UsingLoc,
1771                             SourceLocation &DeclEnd,
1772                             ParsedAttributes &attrs);
1773   Decl *ParseUsingDeclaration(unsigned Context,
1774                               const ParsedTemplateInfo &TemplateInfo,
1775                               SourceLocation UsingLoc,
1776                               SourceLocation &DeclEnd,
1777                               AccessSpecifier AS = AS_none,
1778                               Decl **OwnedType = 0);
1779   Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
1780   Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
1781                             SourceLocation AliasLoc, IdentifierInfo *Alias,
1782                             SourceLocation &DeclEnd);
1783
1784   //===--------------------------------------------------------------------===//
1785   // C++ 9: classes [class] and C structs/unions.
1786   TypeResult ParseClassName(SourceLocation &EndLocation, CXXScopeSpec &SS);
1787   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
1788                            DeclSpec &DS,
1789                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1790                            AccessSpecifier AS = AS_none,
1791                            bool SuppressDeclarations = false);
1792   void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType,
1793                                    Decl *TagDecl);
1794   ExprResult ParseCXXMemberInitializer(bool IsFunction,
1795                                        SourceLocation &EqualLoc);
1796   void ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1797                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
1798                                  ParsingDeclRAIIObject *DiagsFromTParams = 0);
1799   void ParseConstructorInitializer(Decl *ConstructorDecl);
1800   MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
1801   void HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
1802                                        Decl *ThisDecl);
1803
1804   //===--------------------------------------------------------------------===//
1805   // C++ 10: Derived classes [class.derived]
1806   void ParseBaseClause(Decl *ClassDecl);
1807   BaseResult ParseBaseSpecifier(Decl *ClassDecl);
1808   AccessSpecifier getAccessSpecifierIfPresent() const;
1809
1810   bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 
1811                                     IdentifierInfo *Name,
1812                                     SourceLocation NameLoc,
1813                                     bool EnteringContext,
1814                                     ParsedType ObjectType,
1815                                     UnqualifiedId &Id,
1816                                     bool AssumeTemplateId,
1817                                     SourceLocation TemplateKWLoc);
1818   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
1819                                   ParsedType ObjectType,
1820                                   UnqualifiedId &Result);
1821   bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1822                           bool AllowDestructorName,
1823                           bool AllowConstructorName,
1824                           ParsedType ObjectType,
1825                           UnqualifiedId &Result);
1826     
1827   //===--------------------------------------------------------------------===//
1828   // C++ 14: Templates [temp]
1829
1830   // C++ 14.1: Template Parameters [temp.param]
1831   Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
1832                                                  SourceLocation &DeclEnd,
1833                                                  AccessSpecifier AS = AS_none);
1834   Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
1835                                                      SourceLocation &DeclEnd,
1836                                                      AccessSpecifier AS);
1837   Decl *ParseSingleDeclarationAfterTemplate(
1838                                        unsigned Context,
1839                                        const ParsedTemplateInfo &TemplateInfo,
1840                                        ParsingDeclRAIIObject &DiagsFromParams,
1841                                        SourceLocation &DeclEnd,
1842                                        AccessSpecifier AS=AS_none);
1843   bool ParseTemplateParameters(unsigned Depth,
1844                                llvm::SmallVectorImpl<Decl*> &TemplateParams,
1845                                SourceLocation &LAngleLoc,
1846                                SourceLocation &RAngleLoc);
1847   bool ParseTemplateParameterList(unsigned Depth,
1848                                   llvm::SmallVectorImpl<Decl*> &TemplateParams);
1849   bool isStartOfTemplateTypeParameter();
1850   Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
1851   Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
1852   Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
1853   Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
1854   // C++ 14.3: Template arguments [temp.arg]
1855   typedef llvm::SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
1856
1857   bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
1858                                         SourceLocation TemplateNameLoc,
1859                                         const CXXScopeSpec &SS,
1860                                         bool ConsumeLastToken,
1861                                         SourceLocation &LAngleLoc,
1862                                         TemplateArgList &TemplateArgs,
1863                                         SourceLocation &RAngleLoc);
1864
1865   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1866                                CXXScopeSpec &SS,
1867                                UnqualifiedId &TemplateName,
1868                                SourceLocation TemplateKWLoc = SourceLocation(),
1869                                bool AllowTypeAnnotation = true);
1870   void AnnotateTemplateIdTokenAsType();
1871   bool IsTemplateArgumentList(unsigned Skip = 0);
1872   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
1873   ParsedTemplateArgument ParseTemplateTemplateArgument();
1874   ParsedTemplateArgument ParseTemplateArgument();
1875   Decl *ParseExplicitInstantiation(SourceLocation ExternLoc,
1876                                         SourceLocation TemplateLoc,
1877                                         SourceLocation &DeclEnd);
1878
1879   //===--------------------------------------------------------------------===//
1880   // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
1881   ExprResult ParseUnaryTypeTrait();
1882   ExprResult ParseBinaryTypeTrait();
1883
1884   //===--------------------------------------------------------------------===//
1885   // Embarcadero: Arary and Expression Traits
1886   ExprResult ParseArrayTypeTrait();
1887   ExprResult ParseExpressionTrait();
1888
1889   //===--------------------------------------------------------------------===//
1890   // Preprocessor code-completion pass-through
1891   virtual void CodeCompleteDirective(bool InConditional);
1892   virtual void CodeCompleteInConditionalExclusion();
1893   virtual void CodeCompleteMacroName(bool IsDefinition);
1894   virtual void CodeCompletePreprocessorExpression();
1895   virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
1896                                          MacroInfo *MacroInfo,
1897                                          unsigned ArgumentIndex);
1898   virtual void CodeCompleteNaturalLanguage();
1899 };
1900
1901 }  // end namespace clang
1902
1903 #endif