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