Parser.h revision a7bc7c880f86bc180684ef032d06df51bcae7a23
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/Lex/Preprocessor.h"
18#include "clang/Parse/Action.h"
19#include "clang/Parse/DeclSpec.h"
20#include <stack>
21
22namespace clang {
23  class AttributeList;
24  class DeclSpec;
25  class Declarator;
26  class FieldDeclarator;
27  class ObjCDeclSpec;
28  class PragmaHandler;
29  class Scope;
30  class DiagnosticBuilder;
31
32/// Parser - This implements a parser for the C family of languages.  After
33/// parsing units of the grammar, productions are invoked to handle whatever has
34/// been read.
35///
36class Parser {
37  Preprocessor &PP;
38
39  /// Tok - The current token we are peeking ahead.  All parsing methods assume
40  /// that this is valid.
41  Token Tok;
42
43  unsigned short ParenCount, BracketCount, BraceCount;
44
45  /// Actions - These are the callbacks we invoke as we parse various constructs
46  /// in the file.  This refers to the common base class between MinimalActions
47  /// and SemaActions for those uses that don't matter.
48  Action &Actions;
49
50  Scope *CurScope;
51  Diagnostic &Diags;
52
53  /// ScopeCache - Cache scopes to reduce malloc traffic.
54  enum { ScopeCacheSize = 16 };
55  unsigned NumCachedScopes;
56  Scope *ScopeCache[ScopeCacheSize];
57
58  /// Ident_super - IdentifierInfo for "super", to support fast
59  /// comparison.
60  IdentifierInfo *Ident_super;
61
62  PragmaHandler *PackHandler;
63
64public:
65  Parser(Preprocessor &PP, Action &Actions);
66  ~Parser();
67
68  const LangOptions &getLang() const { return PP.getLangOptions(); }
69  TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
70  Action &getActions() const { return Actions; }
71
72  // Type forwarding.  All of these are statically 'void*', but they may all be
73  // different actual classes based on the actions in place.
74  typedef Action::ExprTy ExprTy;
75  typedef Action::StmtTy StmtTy;
76  typedef Action::DeclTy DeclTy;
77  typedef Action::TypeTy TypeTy;
78  typedef Action::BaseTy BaseTy;
79  typedef Action::MemInitTy MemInitTy;
80  typedef Action::CXXScopeTy CXXScopeTy;
81  typedef Action::TemplateParamsTy TemplateParamsTy;
82  typedef Action::TemplateArgTy TemplateArgTy;
83
84  typedef llvm::SmallVector<TemplateParamsTy *, 4> TemplateParameterLists;
85
86  typedef Action::ExprResult        ExprResult;
87  typedef Action::StmtResult        StmtResult;
88  typedef Action::BaseResult        BaseResult;
89  typedef Action::MemInitResult     MemInitResult;
90
91  typedef Action::OwningExprResult OwningExprResult;
92  typedef Action::OwningStmtResult OwningStmtResult;
93  typedef Action::OwningTemplateArgResult OwningTemplateArgResult;
94
95  typedef Action::ExprArg ExprArg;
96  typedef Action::MultiStmtArg MultiStmtArg;
97
98  /// Adorns a ExprResult with Actions to make it an OwningExprResult
99  OwningExprResult Owned(ExprResult res) {
100    return OwningExprResult(Actions, res);
101  }
102  /// Adorns a StmtResult with Actions to make it an OwningStmtResult
103  OwningStmtResult Owned(StmtResult res) {
104    return OwningStmtResult(Actions, res);
105  }
106
107  OwningExprResult ExprError() { return OwningExprResult(Actions, true); }
108  OwningStmtResult StmtError() { return OwningStmtResult(Actions, true); }
109  OwningTemplateArgResult TemplateArgError() {
110    return OwningTemplateArgResult(Actions, true);
111  }
112
113  OwningExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
114  OwningStmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
115  OwningTemplateArgResult TemplateArgError(const DiagnosticBuilder &) {
116    return TemplateArgError();
117  }
118
119  // Parsing methods.
120
121  /// ParseTranslationUnit - All in one method that initializes parses, and
122  /// shuts down the parser.
123  void ParseTranslationUnit();
124
125  /// Initialize - Warm up the parser.
126  ///
127  void Initialize();
128
129  /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
130  /// the EOF was encountered.
131  bool ParseTopLevelDecl(DeclTy*& Result);
132
133private:
134  //===--------------------------------------------------------------------===//
135  // Low-Level token peeking and consumption methods.
136  //
137
138  /// isTokenParen - Return true if the cur token is '(' or ')'.
139  bool isTokenParen() const {
140    return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
141  }
142  /// isTokenBracket - Return true if the cur token is '[' or ']'.
143  bool isTokenBracket() const {
144    return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
145  }
146  /// isTokenBrace - Return true if the cur token is '{' or '}'.
147  bool isTokenBrace() const {
148    return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
149  }
150
151  /// isTokenStringLiteral - True if this token is a string-literal.
152  ///
153  bool isTokenStringLiteral() const {
154    return Tok.getKind() == tok::string_literal ||
155           Tok.getKind() == tok::wide_string_literal;
156  }
157
158  /// ConsumeToken - Consume the current 'peek token' and lex the next one.
159  /// This does not work with all kinds of tokens: strings and specific other
160  /// tokens must be consumed with custom methods below.  This returns the
161  /// location of the consumed token.
162  SourceLocation ConsumeToken() {
163    assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
164           !isTokenBrace() &&
165           "Should consume special tokens with Consume*Token");
166    SourceLocation L = Tok.getLocation();
167    PP.Lex(Tok);
168    return L;
169  }
170
171  /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
172  /// current token type.  This should only be used in cases where the type of
173  /// the token really isn't known, e.g. in error recovery.
174  SourceLocation ConsumeAnyToken() {
175    if (isTokenParen())
176      return ConsumeParen();
177    else if (isTokenBracket())
178      return ConsumeBracket();
179    else if (isTokenBrace())
180      return ConsumeBrace();
181    else if (isTokenStringLiteral())
182      return ConsumeStringToken();
183    else
184      return ConsumeToken();
185  }
186
187  /// ConsumeParen - This consume method keeps the paren count up-to-date.
188  ///
189  SourceLocation ConsumeParen() {
190    assert(isTokenParen() && "wrong consume method");
191    if (Tok.getKind() == tok::l_paren)
192      ++ParenCount;
193    else if (ParenCount)
194      --ParenCount;       // Don't let unbalanced )'s drive the count negative.
195    SourceLocation L = Tok.getLocation();
196    PP.Lex(Tok);
197    return L;
198  }
199
200  /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
201  ///
202  SourceLocation ConsumeBracket() {
203    assert(isTokenBracket() && "wrong consume method");
204    if (Tok.getKind() == tok::l_square)
205      ++BracketCount;
206    else if (BracketCount)
207      --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
208
209    SourceLocation L = Tok.getLocation();
210    PP.Lex(Tok);
211    return L;
212  }
213
214  /// ConsumeBrace - This consume method keeps the brace count up-to-date.
215  ///
216  SourceLocation ConsumeBrace() {
217    assert(isTokenBrace() && "wrong consume method");
218    if (Tok.getKind() == tok::l_brace)
219      ++BraceCount;
220    else if (BraceCount)
221      --BraceCount;     // Don't let unbalanced }'s drive the count negative.
222
223    SourceLocation L = Tok.getLocation();
224    PP.Lex(Tok);
225    return L;
226  }
227
228  /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
229  /// and returning the token kind.  This method is specific to strings, as it
230  /// handles string literal concatenation, as per C99 5.1.1.2, translation
231  /// phase #6.
232  SourceLocation ConsumeStringToken() {
233    assert(isTokenStringLiteral() &&
234           "Should only consume string literals with this method");
235    SourceLocation L = Tok.getLocation();
236    PP.Lex(Tok);
237    return L;
238  }
239
240  /// GetLookAheadToken - This peeks ahead N tokens and returns that token
241  /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
242  /// returns the token after Tok, etc.
243  ///
244  /// Note that this differs from the Preprocessor's LookAhead method, because
245  /// the Parser always has one token lexed that the preprocessor doesn't.
246  ///
247  const Token &GetLookAheadToken(unsigned N) {
248    if (N == 0 || Tok.is(tok::eof)) return Tok;
249    return PP.LookAhead(N-1);
250  }
251
252  /// NextToken - This peeks ahead one token and returns it without
253  /// consuming it.
254  const Token &NextToken() {
255    return PP.LookAhead(0);
256  }
257
258  /// TryAnnotateTypeOrScopeToken - If the current token position is on a
259  /// typename (possibly qualified in C++) or a C++ scope specifier not followed
260  /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
261  /// with a single annotation token representing the typename or C++ scope
262  /// respectively.
263  /// This simplifies handling of C++ scope specifiers and allows efficient
264  /// backtracking without the need to re-parse and resolve nested-names and
265  /// typenames.
266  /// It will mainly be called when we expect to treat identifiers as typenames
267  /// (if they are typenames). For example, in C we do not expect identifiers
268  /// inside expressions to be treated as typenames so it will not be called
269  /// for expressions in C.
270  ///
271  /// This returns true if the token was annotated.
272  bool TryAnnotateTypeOrScopeToken(const Token *GlobalQualifier = 0);
273
274  /// TryAnnotateCXXScopeToken - Like TryAnnotateTypeOrScopeToken but only
275  /// annotates C++ scope specifiers.
276  void TryAnnotateCXXScopeToken();
277
278  /// TentativeParsingAction - An object that is used as a kind of "tentative
279  /// parsing transaction". It gets instantiated to mark the token position and
280  /// after the token consumption is done, Commit() or Revert() is called to
281  /// either "commit the consumed tokens" or revert to the previously marked
282  /// token position. Example:
283  ///
284  ///   TentativeParsingAction TPA;
285  ///   ConsumeToken();
286  ///   ....
287  ///   TPA.Revert();
288  ///
289  class TentativeParsingAction {
290    Parser &P;
291    Token PrevTok;
292    bool isActive;
293
294  public:
295    explicit TentativeParsingAction(Parser& p) : P(p) {
296      PrevTok = P.Tok;
297      P.PP.EnableBacktrackAtThisPos();
298      isActive = true;
299    }
300    void Commit() {
301      assert(isActive && "Parsing action was finished!");
302      P.PP.CommitBacktrackedTokens();
303      isActive = false;
304    }
305    void Revert() {
306      assert(isActive && "Parsing action was finished!");
307      P.PP.Backtrack();
308      P.Tok = PrevTok;
309      isActive = false;
310    }
311    ~TentativeParsingAction() {
312      assert(!isActive && "Forgot to call Commit or Revert!");
313    }
314  };
315
316
317  /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
318  /// this helper function matches and consumes the specified RHS token if
319  /// present.  If not present, it emits the specified diagnostic indicating
320  /// that the parser failed to match the RHS of the token at LHSLoc.  LHSName
321  /// should be the name of the unmatched LHS token.  This returns the location
322  /// of the consumed token.
323  SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok,
324                                     SourceLocation LHSLoc);
325
326  /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
327  /// input.  If so, it is consumed and false is returned.
328  ///
329  /// If the input is malformed, this emits the specified diagnostic.  Next, if
330  /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
331  /// returned.
332  bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
333                        const char *DiagMsg = "",
334                        tok::TokenKind SkipToTok = tok::unknown);
335
336  //===--------------------------------------------------------------------===//
337  // Scope manipulation
338
339  /// ParseScope - Introduces a new scope for parsing. The kind of
340  /// scope is determined by ScopeFlags. Objects of this type should
341  /// be created on the stack to coincide with the position where the
342  /// parser enters the new scope, and this object's constructor will
343  /// create that new scope. Similarly, once the object is destroyed
344  /// the parser will exit the scope.
345  class ParseScope {
346    Parser *Self;
347    ParseScope(const ParseScope&); // do not implement
348    ParseScope& operator=(const ParseScope&); // do not implement
349
350  public:
351    // ParseScope - Construct a new object to manage a scope in the
352    // parser Self where the new Scope is created with the flags
353    // ScopeFlags, but only when ManageScope is true (the default). If
354    // ManageScope is false, this object does nothing.
355    ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
356      : Self(Self) {
357      if (ManageScope)
358        Self->EnterScope(ScopeFlags);
359      else
360        this->Self = 0;
361    }
362
363    // Exit - Exit the scope associated with this object now, rather
364    // than waiting until the object is destroyed.
365    void Exit() {
366      if (Self) {
367        Self->ExitScope();
368        Self = 0;
369      }
370    }
371
372    ~ParseScope() {
373      Exit();
374    }
375  };
376
377  /// EnterScope - Start a new scope.
378  void EnterScope(unsigned ScopeFlags);
379
380  /// ExitScope - Pop a scope off the scope stack.
381  void ExitScope();
382
383  //===--------------------------------------------------------------------===//
384  // Diagnostic Emission and Error recovery.
385
386  DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
387  DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
388
389  /// SkipUntil - Read tokens until we get to the specified token, then consume
390  /// it (unless DontConsume is true).  Because we cannot guarantee that the
391  /// token will ever occur, this skips to the next token, or to some likely
392  /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
393  /// character.
394  ///
395  /// If SkipUntil finds the specified token, it returns true, otherwise it
396  /// returns false.
397  bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
398                 bool DontConsume = false) {
399    return SkipUntil(&T, 1, StopAtSemi, DontConsume);
400  }
401  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
402                 bool DontConsume = false) {
403    tok::TokenKind TokArray[] = {T1, T2};
404    return SkipUntil(TokArray, 2, StopAtSemi, DontConsume);
405  }
406  bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
407                 bool StopAtSemi = true, bool DontConsume = false);
408
409  //===--------------------------------------------------------------------===//
410  // Lexing and parsing of C++ inline methods.
411
412  struct LexedMethod {
413    Action::DeclTy *D;
414    CachedTokens Toks;
415    explicit LexedMethod(Action::DeclTy *MD) : D(MD) {}
416  };
417
418  /// LateParsedDefaultArgument - Keeps track of a parameter that may
419  /// have a default argument that cannot be parsed yet because it
420  /// occurs within a member function declaration inside the class
421  /// (C++ [class.mem]p2).
422  struct LateParsedDefaultArgument {
423    explicit LateParsedDefaultArgument(Action::DeclTy *P,
424                                       CachedTokens *Toks = 0)
425      : Param(P), Toks(Toks) { }
426
427    /// Param - The parameter declaration for this parameter.
428    Action::DeclTy *Param;
429
430    /// Toks - The sequence of tokens that comprises the default
431    /// argument expression, not including the '=' or the terminating
432    /// ')' or ','. This will be NULL for parameters that have no
433    /// default argument.
434    CachedTokens *Toks;
435  };
436
437  /// LateParsedMethodDeclaration - A method declaration inside a class that
438  /// contains at least one entity whose parsing needs to be delayed
439  /// until the class itself is completely-defined, such as a default
440  /// argument (C++ [class.mem]p2).
441  struct LateParsedMethodDeclaration {
442    explicit LateParsedMethodDeclaration(Action::DeclTy *M) : Method(M) { }
443
444    /// Method - The method declaration.
445    Action::DeclTy *Method;
446
447    /// DefaultArgs - Contains the parameters of the function and
448    /// their default arguments. At least one of the parameters will
449    /// have a default argument, but all of the parameters of the
450    /// method will be stored so that they can be reintroduced into
451    /// scope at the appropriate times.
452    llvm::SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
453  };
454
455  /// LateParsedMethodDecls - During parsing of a top (non-nested) C++
456  /// class, its method declarations that contain parts that won't be
457  /// parsed until after the definiton is completed (C++ [class.mem]p2),
458  /// the method declarations will be stored here with the tokens that
459  /// will be parsed to create those entities.
460  typedef std::list<LateParsedMethodDeclaration> LateParsedMethodDecls;
461
462  /// LexedMethodsForTopClass - During parsing of a top (non-nested) C++ class,
463  /// its inline method definitions and the inline method definitions of its
464  /// nested classes are lexed and stored here.
465  typedef std::list<LexedMethod> LexedMethodsForTopClass;
466
467
468  /// TopClass - Contains information about parts of the top
469  /// (non-nested) C++ class that will need to be parsed after the
470  /// class is fully defined.
471  struct TopClass {
472    /// MethodDecls - Method declarations that contain pieces whose
473    /// parsing will be delayed until the class is fully defined.
474    LateParsedMethodDecls MethodDecls;
475
476    /// MethodDefs - Methods whose definitions will be parsed once the
477    /// class has been fully defined.
478    LexedMethodsForTopClass MethodDefs;
479  };
480
481  /// TopClassStacks - This is initialized with one TopClass used
482  /// for lexing all top classes, until a local class in an inline method is
483  /// encountered, at which point a new TopClass is pushed here
484  /// and used until the parsing of that local class is finished.
485  std::stack<TopClass> TopClassStacks;
486
487  TopClass &getCurTopClassStack() {
488    assert(!TopClassStacks.empty() && "No lexed method stacks!");
489    return TopClassStacks.top();
490  }
491
492  void PushTopClassStack() {
493    TopClassStacks.push(TopClass());
494  }
495  void PopTopClassStack() { TopClassStacks.pop(); }
496
497  DeclTy *ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D);
498  void ParseLexedMethodDeclarations();
499  void ParseLexedMethodDefs();
500  bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
501                            CachedTokens &Toks,
502                            tok::TokenKind EarlyAbortIf = tok::unknown,
503                            bool ConsumeFinalToken = true);
504
505  //===--------------------------------------------------------------------===//
506  // C99 6.9: External Definitions.
507  DeclTy *ParseExternalDeclaration();
508  DeclTy *ParseDeclarationOrFunctionDefinition(
509            TemplateParameterLists *TemplateParams = 0);
510  DeclTy *ParseFunctionDefinition(Declarator &D);
511  void ParseKNRParamDeclarations(Declarator &D);
512  OwningExprResult ParseSimpleAsm();
513  OwningExprResult ParseAsmStringLiteral();
514
515  // Objective-C External Declarations
516  DeclTy *ParseObjCAtDirectives();
517  DeclTy *ParseObjCAtClassDeclaration(SourceLocation atLoc);
518  DeclTy *ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
519                                          AttributeList *prefixAttrs = 0);
520  void ParseObjCClassInstanceVariables(DeclTy *interfaceDecl,
521                                       SourceLocation atLoc);
522  bool ParseObjCProtocolReferences(llvm::SmallVectorImpl<Action::DeclTy*> &P,
523                                   bool WarnOnDeclarations,
524                                   SourceLocation &EndProtoLoc);
525  void ParseObjCInterfaceDeclList(DeclTy *interfaceDecl,
526                                  tok::ObjCKeywordKind contextKey);
527  DeclTy *ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
528                                         AttributeList *prefixAttrs = 0);
529
530  DeclTy *ObjCImpDecl;
531
532  DeclTy *ParseObjCAtImplementationDeclaration(SourceLocation atLoc);
533  DeclTy *ParseObjCAtEndDeclaration(SourceLocation atLoc);
534  DeclTy *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
535  DeclTy *ParseObjCPropertySynthesize(SourceLocation atLoc);
536  DeclTy *ParseObjCPropertyDynamic(SourceLocation atLoc);
537
538  IdentifierInfo *ParseObjCSelector(SourceLocation &MethodLocation);
539  // Definitions for Objective-c context sensitive keywords recognition.
540  enum ObjCTypeQual {
541    objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
542    objc_NumQuals
543  };
544  IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
545
546  bool isTokIdentifier_in() const;
547
548  TypeTy *ParseObjCTypeName(ObjCDeclSpec &DS);
549  void ParseObjCMethodRequirement();
550  DeclTy *ParseObjCMethodPrototype(DeclTy *classOrCat,
551            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword);
552  DeclTy *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
553                              DeclTy *classDecl,
554            tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword);
555  void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
556
557  DeclTy *ParseObjCMethodDefinition();
558
559  //===--------------------------------------------------------------------===//
560  // C99 6.5: Expressions.
561
562  OwningExprResult ParseExpression();
563  OwningExprResult ParseConstantExpression();
564  // Expr that doesn't include commas.
565  OwningExprResult ParseAssignmentExpression();
566
567  OwningExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
568
569  OwningExprResult ParseRHSOfBinaryExpression(OwningExprResult LHS,
570                                              unsigned MinPrec);
571  OwningExprResult ParseCastExpression(bool isUnaryExpression);
572  OwningExprResult ParsePostfixExpressionSuffix(OwningExprResult LHS);
573  OwningExprResult ParseSizeofAlignofExpression();
574  OwningExprResult ParseBuiltinPrimaryExpression();
575
576  static const unsigned ExprListSize = 12;
577  typedef llvm::SmallVector<ExprTy*, ExprListSize> ExprListTy;
578  typedef llvm::SmallVector<SourceLocation, ExprListSize> CommaLocsTy;
579
580  /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
581  bool ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs);
582
583  /// ParenParseOption - Control what ParseParenExpression will parse.
584  enum ParenParseOption {
585    SimpleExpr,      // Only parse '(' expression ')'
586    CompoundStmt,    // Also allow '(' compound-statement ')'
587    CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
588    CastExpr         // Also allow '(' type-name ')' <anything>
589  };
590  OwningExprResult ParseParenExpression(ParenParseOption &ExprType,
591                                        TypeTy *&CastTy,
592                                        SourceLocation &RParenLoc);
593
594  OwningExprResult ParseSimpleParenExpression() {  // Parse SimpleExpr only.
595    SourceLocation RParenLoc;
596    return ParseSimpleParenExpression(RParenLoc);
597  }
598  OwningExprResult ParseSimpleParenExpression(SourceLocation &RParenLoc) {
599    ParenParseOption Op = SimpleExpr;
600    TypeTy *CastTy;
601    return ParseParenExpression(Op, CastTy, RParenLoc);
602  }
603
604  OwningExprResult ParseStringLiteralExpression();
605
606  //===--------------------------------------------------------------------===//
607  // C++ Expressions
608  OwningExprResult ParseCXXIdExpression();
609
610  /// MaybeParseCXXScopeSpecifier - Parse global scope or nested-name-specifier.
611  /// Returns true if a nested-name-specifier was parsed from the token stream.
612  ///
613  /// If GlobalQualifier is non-null, then it is a :: token we should use as the
614  /// global qualifier.
615  bool MaybeParseCXXScopeSpecifier(CXXScopeSpec &SS,
616                                   const Token *GlobalQualifier = 0);
617
618  //===--------------------------------------------------------------------===//
619  // C++ 5.2p1: C++ Casts
620  OwningExprResult ParseCXXCasts();
621
622  //===--------------------------------------------------------------------===//
623  // C++ 5.2p1: C++ Type Identification
624  OwningExprResult ParseCXXTypeid();
625
626  //===--------------------------------------------------------------------===//
627  // C++ 9.3.2: C++ 'this' pointer
628  OwningExprResult ParseCXXThis();
629
630  //===--------------------------------------------------------------------===//
631  // C++ 15: C++ Throw Expression
632  OwningExprResult ParseThrowExpression();
633  bool ParseExceptionSpecification();
634
635  //===--------------------------------------------------------------------===//
636  // C++ 2.13.5: C++ Boolean Literals
637  OwningExprResult ParseCXXBoolLiteral();
638
639  //===--------------------------------------------------------------------===//
640  // C++ 5.2.3: Explicit type conversion (functional notation)
641  OwningExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
642
643  /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
644  /// This should only be called when the current token is known to be part of
645  /// simple-type-specifier.
646  void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
647
648  bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
649
650  //===--------------------------------------------------------------------===//
651  // C++ 5.3.4 and 5.3.5: C++ new and delete
652  bool ParseExpressionListOrTypeId(ExprListTy &Exprs, Declarator &D);
653  void ParseDirectNewDeclarator(Declarator &D);
654  OwningExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
655  OwningExprResult ParseCXXDeleteExpression(bool UseGlobal,
656                                            SourceLocation Start);
657
658  //===--------------------------------------------------------------------===//
659  // C++ if/switch/while/for condition expression.
660  OwningExprResult ParseCXXCondition();
661
662  //===--------------------------------------------------------------------===//
663  // C++ types
664
665  //===--------------------------------------------------------------------===//
666  // C99 6.7.8: Initialization.
667
668  /// ParseInitializer
669  ///       initializer: [C99 6.7.8]
670  ///         assignment-expression
671  ///         '{' ...
672  OwningExprResult ParseInitializer() {
673    if (Tok.isNot(tok::l_brace))
674      return ParseAssignmentExpression();
675    return ParseBraceInitializer();
676  }
677  OwningExprResult ParseBraceInitializer();
678  OwningExprResult ParseInitializerWithPotentialDesignator(
679                       InitListDesignations &D, unsigned InitNum);
680
681  //===--------------------------------------------------------------------===//
682  // clang Expressions
683
684  OwningExprResult ParseBlockLiteralExpression();  // ^{...}
685
686  //===--------------------------------------------------------------------===//
687  // Objective-C Expressions
688
689  bool isTokObjCMessageIdentifierReceiver() const {
690    if (!Tok.is(tok::identifier))
691      return false;
692
693    if (Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope))
694      return true;
695
696    return Tok.getIdentifierInfo() == Ident_super;
697  }
698
699  OwningExprResult ParseObjCAtExpression(SourceLocation AtLocation);
700  OwningExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
701  OwningExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
702  OwningExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
703  OwningExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
704  OwningExprResult ParseObjCMessageExpression();
705  OwningExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
706                                                  SourceLocation NameLoc,
707                                                  IdentifierInfo *ReceiverName,
708                                                  ExprArg ReceiverExpr);
709  OwningExprResult ParseAssignmentExprWithObjCMessageExprStart(
710      SourceLocation LBracloc, SourceLocation NameLoc,
711      IdentifierInfo *ReceiverName, ExprArg ReceiverExpr);
712
713  //===--------------------------------------------------------------------===//
714  // C99 6.8: Statements and Blocks.
715
716  OwningStmtResult ParseStatement() {
717    return ParseStatementOrDeclaration(true);
718  }
719  OwningStmtResult ParseStatementOrDeclaration(bool OnlyStatement = false);
720  OwningStmtResult ParseLabeledStatement();
721  OwningStmtResult ParseCaseStatement();
722  OwningStmtResult ParseDefaultStatement();
723  OwningStmtResult ParseCompoundStatement(bool isStmtExpr = false);
724  OwningStmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
725  bool ParseParenExprOrCondition(OwningExprResult &CondExp,
726                                 bool OnlyAllowCondition = false);
727  OwningStmtResult ParseIfStatement();
728  OwningStmtResult ParseSwitchStatement();
729  OwningStmtResult ParseWhileStatement();
730  OwningStmtResult ParseDoStatement();
731  OwningStmtResult ParseForStatement();
732  OwningStmtResult ParseGotoStatement();
733  OwningStmtResult ParseContinueStatement();
734  OwningStmtResult ParseBreakStatement();
735  OwningStmtResult ParseReturnStatement();
736  OwningStmtResult ParseAsmStatement(bool &msAsm);
737  OwningStmtResult FuzzyParseMicrosoftAsmStatement();
738  bool ParseAsmOperandsOpt(llvm::SmallVectorImpl<std::string> &Names,
739                           llvm::SmallVectorImpl<ExprTy*> &Constraints,
740                           llvm::SmallVectorImpl<ExprTy*> &Exprs);
741
742  //===--------------------------------------------------------------------===//
743  // C++ 6: Statements and Blocks
744
745  OwningStmtResult ParseCXXTryBlock();
746  OwningStmtResult ParseCXXCatchBlock();
747
748  //===--------------------------------------------------------------------===//
749  // Objective-C Statements
750
751  OwningStmtResult ParseObjCAtStatement(SourceLocation atLoc);
752  OwningStmtResult ParseObjCTryStmt(SourceLocation atLoc);
753  OwningStmtResult ParseObjCThrowStmt(SourceLocation atLoc);
754  OwningStmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
755
756
757  //===--------------------------------------------------------------------===//
758  // C99 6.7: Declarations.
759
760  DeclTy *ParseDeclaration(unsigned Context);
761  DeclTy *ParseSimpleDeclaration(unsigned Context);
762  DeclTy *ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D);
763  DeclTy *ParseFunctionStatementBody(DeclTy *Decl,
764                                     SourceLocation L, SourceLocation R);
765  void ParseDeclarationSpecifiers(DeclSpec &DS,
766                                  TemplateParameterLists *TemplateParams = 0);
767  bool MaybeParseTypeSpecifier(DeclSpec &DS, int &isInvalid,
768                               const char *&PrevSpec,
769                               TemplateParameterLists *TemplateParams = 0);
770  void ParseSpecifierQualifierList(DeclSpec &DS);
771
772  void ParseObjCTypeQualifierList(ObjCDeclSpec &DS);
773
774  void ParseEnumSpecifier(DeclSpec &DS);
775  void ParseEnumBody(SourceLocation StartLoc, DeclTy *TagDecl);
776  void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
777                            DeclTy *TagDecl);
778  void ParseStructDeclaration(DeclSpec &DS,
779                              llvm::SmallVectorImpl<FieldDeclarator> &Fields);
780
781  bool isDeclarationSpecifier();
782  bool isTypeSpecifierQualifier();
783  bool isTypeQualifier() const;
784
785  /// isDeclarationStatement - Disambiguates between a declaration or an
786  /// expression statement, when parsing function bodies.
787  /// Returns true for declaration, false for expression.
788  bool isDeclarationStatement() {
789    if (getLang().CPlusPlus)
790      return isCXXDeclarationStatement();
791    return isDeclarationSpecifier();
792  }
793
794  /// isSimpleDeclaration - Disambiguates between a declaration or an
795  /// expression, mainly used for the C 'clause-1' or the C++
796  // 'for-init-statement' part of a 'for' statement.
797  /// Returns true for declaration, false for expression.
798  bool isSimpleDeclaration() {
799    if (getLang().CPlusPlus)
800      return isCXXSimpleDeclaration();
801    return isDeclarationSpecifier();
802  }
803
804  /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
805  /// whether the parens contain an expression or a type-id.
806  /// Returns true for a type-id and false for an expression.
807  bool isTypeIdInParens() {
808    if (getLang().CPlusPlus)
809      return isCXXTypeIdInParens();
810    return isTypeSpecifierQualifier();
811  }
812
813  /// isCXXDeclarationStatement - C++-specialized function that disambiguates
814  /// between a declaration or an expression statement, when parsing function
815  /// bodies. Returns true for declaration, false for expression.
816  bool isCXXDeclarationStatement();
817
818  /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
819  /// between a simple-declaration or an expression-statement.
820  /// If during the disambiguation process a parsing error is encountered,
821  /// the function returns true to let the declaration parsing code handle it.
822  /// Returns false if the statement is disambiguated as expression.
823  bool isCXXSimpleDeclaration();
824
825  /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
826  /// a constructor-style initializer, when parsing declaration statements.
827  /// Returns true for function declarator and false for constructor-style
828  /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to
829  /// indicate that the parens were disambiguated as function declarator.
830  /// If during the disambiguation process a parsing error is encountered,
831  /// the function returns true to let the declaration parsing code handle it.
832  bool isCXXFunctionDeclarator(bool warnIfAmbiguous);
833
834  /// isCXXConditionDeclaration - Disambiguates between a declaration or an
835  /// expression for a condition of a if/switch/while/for statement.
836  /// If during the disambiguation process a parsing error is encountered,
837  /// the function returns true to let the declaration parsing code handle it.
838  bool isCXXConditionDeclaration();
839
840  /// isCXXTypeIdInParens - Assumes that a '(' was parsed and now we want to
841  /// know whether the parens contain an expression or a type-id.
842  /// Returns true for a type-id and false for an expression.
843  /// If during the disambiguation process a parsing error is encountered,
844  /// the function returns true to let the declaration parsing code handle it.
845  bool isCXXTypeIdInParens();
846
847  /// TPResult - Used as the result value for functions whose purpose is to
848  /// disambiguate C++ constructs by "tentatively parsing" them.
849  /// This is a class instead of a simple enum because the implicit enum-to-bool
850  /// conversions may cause subtle bugs.
851  class TPResult {
852    enum Result {
853      TPR_true,
854      TPR_false,
855      TPR_ambiguous,
856      TPR_error
857    };
858    Result Res;
859    TPResult(Result result) : Res(result) {}
860  public:
861    static TPResult True() { return TPR_true; }
862    static TPResult False() { return TPR_false; }
863    static TPResult Ambiguous() { return TPR_ambiguous; }
864    static TPResult Error() { return TPR_error; }
865
866    bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
867    bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
868  };
869
870  /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
871  /// declaration specifier, TPResult::False() if it is not,
872  /// TPResult::Ambiguous() if it could be either a decl-specifier or a
873  /// function-style cast, and TPResult::Error() if a parsing error was
874  /// encountered.
875  /// Doesn't consume tokens.
876  TPResult isCXXDeclarationSpecifier();
877
878  // "Tentative parsing" functions, used for disambiguation. If a parsing error
879  // is encountered they will return TPResult::Error().
880  // Returning TPResult::True()/False() indicates that the ambiguity was
881  // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
882  // that more tentative parsing is necessary for disambiguation.
883  // They all consume tokens, so backtracking should be used after calling them.
884
885  TPResult TryParseDeclarationSpecifier();
886  TPResult TryParseSimpleDeclaration();
887  TPResult TryParseTypeofSpecifier();
888  TPResult TryParseInitDeclaratorList();
889  TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
890  TPResult TryParseParameterDeclarationClause();
891  TPResult TryParseFunctionDeclarator();
892  TPResult TryParseBracketDeclarator();
893
894
895  TypeTy *ParseTypeName();
896  AttributeList *ParseAttributes();
897  void FuzzyParseMicrosoftDeclSpec();
898  void ParseTypeofSpecifier(DeclSpec &DS);
899
900  /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
901  /// enter a new C++ declarator scope and exit it when the function is
902  /// finished.
903  class DeclaratorScopeObj {
904    Parser &P;
905    CXXScopeSpec &SS;
906  public:
907    DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss) {}
908
909    void EnterDeclaratorScope() {
910      if (SS.isSet())
911        P.Actions.ActOnCXXEnterDeclaratorScope(P.CurScope, SS);
912    }
913
914    ~DeclaratorScopeObj() {
915      if (SS.isSet())
916        P.Actions.ActOnCXXExitDeclaratorScope(P.CurScope, SS);
917    }
918  };
919
920  /// ParseDeclarator - Parse and verify a newly-initialized declarator.
921  void ParseDeclarator(Declarator &D);
922  /// A function that parses a variant of direct-declarator.
923  typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
924  void ParseDeclaratorInternal(Declarator &D,
925                               DirectDeclParseFunction DirectDeclParser);
926  void ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed = true);
927  void ParseDirectDeclarator(Declarator &D);
928  void ParseParenDeclarator(Declarator &D);
929  void ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
930                               AttributeList *AttrList = 0,
931                               bool RequiresArg = false);
932  void ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
933                                             Declarator &D);
934  void ParseBracketDeclarator(Declarator &D);
935
936  //===--------------------------------------------------------------------===//
937  // C++ 7: Declarations [dcl.dcl]
938
939  DeclTy *ParseNamespace(unsigned Context);
940  DeclTy *ParseLinkage(unsigned Context);
941  DeclTy *ParseUsingDirectiveOrDeclaration(unsigned Context);
942  DeclTy *ParseUsingDirective(unsigned Context, SourceLocation UsingLoc);
943  DeclTy *ParseUsingDeclaration(unsigned Context, SourceLocation UsingLoc);
944
945  //===--------------------------------------------------------------------===//
946  // C++ 9: classes [class] and C structs/unions.
947  TypeTy *ParseClassName(const CXXScopeSpec *SS = 0);
948  void ParseClassSpecifier(DeclSpec &DS,
949                           TemplateParameterLists *TemplateParams = 0);
950  void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType,
951                                   DeclTy *TagDecl);
952  DeclTy *ParseCXXClassMemberDeclaration(AccessSpecifier AS);
953  void ParseConstructorInitializer(DeclTy *ConstructorDecl);
954  MemInitResult ParseMemInitializer(DeclTy *ConstructorDecl);
955
956  //===--------------------------------------------------------------------===//
957  // C++ 10: Derived classes [class.derived]
958  void ParseBaseClause(DeclTy *ClassDecl);
959  BaseResult ParseBaseSpecifier(DeclTy *ClassDecl);
960  AccessSpecifier getAccessSpecifierIfPresent() const;
961
962  //===--------------------------------------------------------------------===//
963  // C++ 13.5: Overloaded operators [over.oper]
964  OverloadedOperatorKind TryParseOperatorFunctionId();
965  TypeTy *ParseConversionFunctionId();
966
967  //===--------------------------------------------------------------------===//
968  // C++ 14: Templates [temp]
969  typedef llvm::SmallVector<DeclTy *, 4> TemplateParameterList;
970
971  // C++ 14.1: Template Parameters [temp.param]
972  DeclTy *ParseTemplateDeclaration(unsigned Context);
973  bool ParseTemplateParameters(unsigned Depth,
974                               TemplateParameterList &TemplateParams,
975                               SourceLocation &LAngleLoc,
976                               SourceLocation &RAngleLoc);
977  bool ParseTemplateParameterList(unsigned Depth,
978                                  TemplateParameterList &TemplateParams);
979  DeclTy *ParseTemplateParameter(unsigned Depth, unsigned Position);
980  DeclTy *ParseTypeParameter(unsigned Depth, unsigned Position);
981  DeclTy *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
982  DeclTy *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
983  // C++ 14.3: Template arguments [temp.arg]
984  typedef llvm::SmallVector<TemplateArgTy*, 8> TemplateArgList;
985  void AnnotateTemplateIdToken(DeclTy *Template, const CXXScopeSpec *SS = 0);
986  bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
987  OwningTemplateArgResult ParseTemplateArgument();
988
989};
990
991}  // end namespace clang
992
993#endif
994