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