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