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