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