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