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