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