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