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