xref: /aosp_15_r20/external/clang/lib/Parse/Parser.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- Parser.cpp - C Language Family Parser ----------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements the Parser interfaces.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Parse/Parser.h"
15*67e74705SXin Li #include "RAIIObjectsForParser.h"
16*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
17*67e74705SXin Li #include "clang/AST/ASTContext.h"
18*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
19*67e74705SXin Li #include "clang/Parse/ParseDiagnostic.h"
20*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
21*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
22*67e74705SXin Li #include "clang/Sema/Scope.h"
23*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
24*67e74705SXin Li using namespace clang;
25*67e74705SXin Li 
26*67e74705SXin Li 
27*67e74705SXin Li namespace {
28*67e74705SXin Li /// \brief A comment handler that passes comments found by the preprocessor
29*67e74705SXin Li /// to the parser action.
30*67e74705SXin Li class ActionCommentHandler : public CommentHandler {
31*67e74705SXin Li   Sema &S;
32*67e74705SXin Li 
33*67e74705SXin Li public:
ActionCommentHandler(Sema & S)34*67e74705SXin Li   explicit ActionCommentHandler(Sema &S) : S(S) { }
35*67e74705SXin Li 
HandleComment(Preprocessor & PP,SourceRange Comment)36*67e74705SXin Li   bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
37*67e74705SXin Li     S.ActOnComment(Comment);
38*67e74705SXin Li     return false;
39*67e74705SXin Li   }
40*67e74705SXin Li };
41*67e74705SXin Li 
42*67e74705SXin Li /// \brief RAIIObject to destroy the contents of a SmallVector of
43*67e74705SXin Li /// TemplateIdAnnotation pointers and clear the vector.
44*67e74705SXin Li class DestroyTemplateIdAnnotationsRAIIObj {
45*67e74705SXin Li   SmallVectorImpl<TemplateIdAnnotation *> &Container;
46*67e74705SXin Li 
47*67e74705SXin Li public:
DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation * > & Container)48*67e74705SXin Li   DestroyTemplateIdAnnotationsRAIIObj(
49*67e74705SXin Li       SmallVectorImpl<TemplateIdAnnotation *> &Container)
50*67e74705SXin Li       : Container(Container) {}
51*67e74705SXin Li 
~DestroyTemplateIdAnnotationsRAIIObj()52*67e74705SXin Li   ~DestroyTemplateIdAnnotationsRAIIObj() {
53*67e74705SXin Li     for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
54*67e74705SXin Li              Container.begin(),
55*67e74705SXin Li                                                            E = Container.end();
56*67e74705SXin Li          I != E; ++I)
57*67e74705SXin Li       (*I)->Destroy();
58*67e74705SXin Li     Container.clear();
59*67e74705SXin Li   }
60*67e74705SXin Li };
61*67e74705SXin Li } // end anonymous namespace
62*67e74705SXin Li 
getSEHExceptKeyword()63*67e74705SXin Li IdentifierInfo *Parser::getSEHExceptKeyword() {
64*67e74705SXin Li   // __except is accepted as a (contextual) keyword
65*67e74705SXin Li   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
66*67e74705SXin Li     Ident__except = PP.getIdentifierInfo("__except");
67*67e74705SXin Li 
68*67e74705SXin Li   return Ident__except;
69*67e74705SXin Li }
70*67e74705SXin Li 
Parser(Preprocessor & pp,Sema & actions,bool skipFunctionBodies)71*67e74705SXin Li Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
72*67e74705SXin Li   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
73*67e74705SXin Li     GreaterThanIsOperator(true), ColonIsSacred(false),
74*67e74705SXin Li     InMessageExpression(false), TemplateParameterDepth(0),
75*67e74705SXin Li     ParsingInObjCContainer(false) {
76*67e74705SXin Li   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
77*67e74705SXin Li   Tok.startToken();
78*67e74705SXin Li   Tok.setKind(tok::eof);
79*67e74705SXin Li   Actions.CurScope = nullptr;
80*67e74705SXin Li   NumCachedScopes = 0;
81*67e74705SXin Li   ParenCount = BracketCount = BraceCount = 0;
82*67e74705SXin Li   CurParsedObjCImpl = nullptr;
83*67e74705SXin Li 
84*67e74705SXin Li   // Add #pragma handlers. These are removed and destroyed in the
85*67e74705SXin Li   // destructor.
86*67e74705SXin Li   initializePragmaHandlers();
87*67e74705SXin Li 
88*67e74705SXin Li   CommentSemaHandler.reset(new ActionCommentHandler(actions));
89*67e74705SXin Li   PP.addCommentHandler(CommentSemaHandler.get());
90*67e74705SXin Li 
91*67e74705SXin Li   PP.setCodeCompletionHandler(*this);
92*67e74705SXin Li }
93*67e74705SXin Li 
Diag(SourceLocation Loc,unsigned DiagID)94*67e74705SXin Li DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
95*67e74705SXin Li   return Diags.Report(Loc, DiagID);
96*67e74705SXin Li }
97*67e74705SXin Li 
Diag(const Token & Tok,unsigned DiagID)98*67e74705SXin Li DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
99*67e74705SXin Li   return Diag(Tok.getLocation(), DiagID);
100*67e74705SXin Li }
101*67e74705SXin Li 
102*67e74705SXin Li /// \brief Emits a diagnostic suggesting parentheses surrounding a
103*67e74705SXin Li /// given range.
104*67e74705SXin Li ///
105*67e74705SXin Li /// \param Loc The location where we'll emit the diagnostic.
106*67e74705SXin Li /// \param DK The kind of diagnostic to emit.
107*67e74705SXin Li /// \param ParenRange Source range enclosing code that should be parenthesized.
SuggestParentheses(SourceLocation Loc,unsigned DK,SourceRange ParenRange)108*67e74705SXin Li void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
109*67e74705SXin Li                                 SourceRange ParenRange) {
110*67e74705SXin Li   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
111*67e74705SXin Li   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
112*67e74705SXin Li     // We can't display the parentheses, so just dig the
113*67e74705SXin Li     // warning/error and return.
114*67e74705SXin Li     Diag(Loc, DK);
115*67e74705SXin Li     return;
116*67e74705SXin Li   }
117*67e74705SXin Li 
118*67e74705SXin Li   Diag(Loc, DK)
119*67e74705SXin Li     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
120*67e74705SXin Li     << FixItHint::CreateInsertion(EndLoc, ")");
121*67e74705SXin Li }
122*67e74705SXin Li 
IsCommonTypo(tok::TokenKind ExpectedTok,const Token & Tok)123*67e74705SXin Li static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
124*67e74705SXin Li   switch (ExpectedTok) {
125*67e74705SXin Li   case tok::semi:
126*67e74705SXin Li     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
127*67e74705SXin Li   default: return false;
128*67e74705SXin Li   }
129*67e74705SXin Li }
130*67e74705SXin Li 
ExpectAndConsume(tok::TokenKind ExpectedTok,unsigned DiagID,StringRef Msg)131*67e74705SXin Li bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
132*67e74705SXin Li                               StringRef Msg) {
133*67e74705SXin Li   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
134*67e74705SXin Li     ConsumeAnyToken();
135*67e74705SXin Li     return false;
136*67e74705SXin Li   }
137*67e74705SXin Li 
138*67e74705SXin Li   // Detect common single-character typos and resume.
139*67e74705SXin Li   if (IsCommonTypo(ExpectedTok, Tok)) {
140*67e74705SXin Li     SourceLocation Loc = Tok.getLocation();
141*67e74705SXin Li     {
142*67e74705SXin Li       DiagnosticBuilder DB = Diag(Loc, DiagID);
143*67e74705SXin Li       DB << FixItHint::CreateReplacement(
144*67e74705SXin Li                 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
145*67e74705SXin Li       if (DiagID == diag::err_expected)
146*67e74705SXin Li         DB << ExpectedTok;
147*67e74705SXin Li       else if (DiagID == diag::err_expected_after)
148*67e74705SXin Li         DB << Msg << ExpectedTok;
149*67e74705SXin Li       else
150*67e74705SXin Li         DB << Msg;
151*67e74705SXin Li     }
152*67e74705SXin Li 
153*67e74705SXin Li     // Pretend there wasn't a problem.
154*67e74705SXin Li     ConsumeAnyToken();
155*67e74705SXin Li     return false;
156*67e74705SXin Li   }
157*67e74705SXin Li 
158*67e74705SXin Li   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
159*67e74705SXin Li   const char *Spelling = nullptr;
160*67e74705SXin Li   if (EndLoc.isValid())
161*67e74705SXin Li     Spelling = tok::getPunctuatorSpelling(ExpectedTok);
162*67e74705SXin Li 
163*67e74705SXin Li   DiagnosticBuilder DB =
164*67e74705SXin Li       Spelling
165*67e74705SXin Li           ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
166*67e74705SXin Li           : Diag(Tok, DiagID);
167*67e74705SXin Li   if (DiagID == diag::err_expected)
168*67e74705SXin Li     DB << ExpectedTok;
169*67e74705SXin Li   else if (DiagID == diag::err_expected_after)
170*67e74705SXin Li     DB << Msg << ExpectedTok;
171*67e74705SXin Li   else
172*67e74705SXin Li     DB << Msg;
173*67e74705SXin Li 
174*67e74705SXin Li   return true;
175*67e74705SXin Li }
176*67e74705SXin Li 
ExpectAndConsumeSemi(unsigned DiagID)177*67e74705SXin Li bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
178*67e74705SXin Li   if (TryConsumeToken(tok::semi))
179*67e74705SXin Li     return false;
180*67e74705SXin Li 
181*67e74705SXin Li   if (Tok.is(tok::code_completion)) {
182*67e74705SXin Li     handleUnexpectedCodeCompletionToken();
183*67e74705SXin Li     return false;
184*67e74705SXin Li   }
185*67e74705SXin Li 
186*67e74705SXin Li   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
187*67e74705SXin Li       NextToken().is(tok::semi)) {
188*67e74705SXin Li     Diag(Tok, diag::err_extraneous_token_before_semi)
189*67e74705SXin Li       << PP.getSpelling(Tok)
190*67e74705SXin Li       << FixItHint::CreateRemoval(Tok.getLocation());
191*67e74705SXin Li     ConsumeAnyToken(); // The ')' or ']'.
192*67e74705SXin Li     ConsumeToken(); // The ';'.
193*67e74705SXin Li     return false;
194*67e74705SXin Li   }
195*67e74705SXin Li 
196*67e74705SXin Li   return ExpectAndConsume(tok::semi, DiagID);
197*67e74705SXin Li }
198*67e74705SXin Li 
ConsumeExtraSemi(ExtraSemiKind Kind,unsigned TST)199*67e74705SXin Li void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
200*67e74705SXin Li   if (!Tok.is(tok::semi)) return;
201*67e74705SXin Li 
202*67e74705SXin Li   bool HadMultipleSemis = false;
203*67e74705SXin Li   SourceLocation StartLoc = Tok.getLocation();
204*67e74705SXin Li   SourceLocation EndLoc = Tok.getLocation();
205*67e74705SXin Li   ConsumeToken();
206*67e74705SXin Li 
207*67e74705SXin Li   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
208*67e74705SXin Li     HadMultipleSemis = true;
209*67e74705SXin Li     EndLoc = Tok.getLocation();
210*67e74705SXin Li     ConsumeToken();
211*67e74705SXin Li   }
212*67e74705SXin Li 
213*67e74705SXin Li   // C++11 allows extra semicolons at namespace scope, but not in any of the
214*67e74705SXin Li   // other contexts.
215*67e74705SXin Li   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
216*67e74705SXin Li     if (getLangOpts().CPlusPlus11)
217*67e74705SXin Li       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
218*67e74705SXin Li           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
219*67e74705SXin Li     else
220*67e74705SXin Li       Diag(StartLoc, diag::ext_extra_semi_cxx11)
221*67e74705SXin Li           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
222*67e74705SXin Li     return;
223*67e74705SXin Li   }
224*67e74705SXin Li 
225*67e74705SXin Li   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
226*67e74705SXin Li     Diag(StartLoc, diag::ext_extra_semi)
227*67e74705SXin Li         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
228*67e74705SXin Li                                     Actions.getASTContext().getPrintingPolicy())
229*67e74705SXin Li         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
230*67e74705SXin Li   else
231*67e74705SXin Li     // A single semicolon is valid after a member function definition.
232*67e74705SXin Li     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
233*67e74705SXin Li       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
234*67e74705SXin Li }
235*67e74705SXin Li 
236*67e74705SXin Li //===----------------------------------------------------------------------===//
237*67e74705SXin Li // Error recovery.
238*67e74705SXin Li //===----------------------------------------------------------------------===//
239*67e74705SXin Li 
HasFlagsSet(Parser::SkipUntilFlags L,Parser::SkipUntilFlags R)240*67e74705SXin Li static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
241*67e74705SXin Li   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
242*67e74705SXin Li }
243*67e74705SXin Li 
244*67e74705SXin Li /// SkipUntil - Read tokens until we get to the specified token, then consume
245*67e74705SXin Li /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
246*67e74705SXin Li /// token will ever occur, this skips to the next token, or to some likely
247*67e74705SXin Li /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
248*67e74705SXin Li /// character.
249*67e74705SXin Li ///
250*67e74705SXin Li /// If SkipUntil finds the specified token, it returns true, otherwise it
251*67e74705SXin Li /// returns false.
SkipUntil(ArrayRef<tok::TokenKind> Toks,SkipUntilFlags Flags)252*67e74705SXin Li bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
253*67e74705SXin Li   // We always want this function to skip at least one token if the first token
254*67e74705SXin Li   // isn't T and if not at EOF.
255*67e74705SXin Li   bool isFirstTokenSkipped = true;
256*67e74705SXin Li   while (1) {
257*67e74705SXin Li     // If we found one of the tokens, stop and return true.
258*67e74705SXin Li     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
259*67e74705SXin Li       if (Tok.is(Toks[i])) {
260*67e74705SXin Li         if (HasFlagsSet(Flags, StopBeforeMatch)) {
261*67e74705SXin Li           // Noop, don't consume the token.
262*67e74705SXin Li         } else {
263*67e74705SXin Li           ConsumeAnyToken();
264*67e74705SXin Li         }
265*67e74705SXin Li         return true;
266*67e74705SXin Li       }
267*67e74705SXin Li     }
268*67e74705SXin Li 
269*67e74705SXin Li     // Important special case: The caller has given up and just wants us to
270*67e74705SXin Li     // skip the rest of the file. Do this without recursing, since we can
271*67e74705SXin Li     // get here precisely because the caller detected too much recursion.
272*67e74705SXin Li     if (Toks.size() == 1 && Toks[0] == tok::eof &&
273*67e74705SXin Li         !HasFlagsSet(Flags, StopAtSemi) &&
274*67e74705SXin Li         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
275*67e74705SXin Li       while (Tok.isNot(tok::eof))
276*67e74705SXin Li         ConsumeAnyToken();
277*67e74705SXin Li       return true;
278*67e74705SXin Li     }
279*67e74705SXin Li 
280*67e74705SXin Li     switch (Tok.getKind()) {
281*67e74705SXin Li     case tok::eof:
282*67e74705SXin Li       // Ran out of tokens.
283*67e74705SXin Li       return false;
284*67e74705SXin Li 
285*67e74705SXin Li     case tok::annot_pragma_openmp:
286*67e74705SXin Li     case tok::annot_pragma_openmp_end:
287*67e74705SXin Li       // Stop before an OpenMP pragma boundary.
288*67e74705SXin Li     case tok::annot_module_begin:
289*67e74705SXin Li     case tok::annot_module_end:
290*67e74705SXin Li     case tok::annot_module_include:
291*67e74705SXin Li       // Stop before we change submodules. They generally indicate a "good"
292*67e74705SXin Li       // place to pick up parsing again (except in the special case where
293*67e74705SXin Li       // we're trying to skip to EOF).
294*67e74705SXin Li       return false;
295*67e74705SXin Li 
296*67e74705SXin Li     case tok::code_completion:
297*67e74705SXin Li       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
298*67e74705SXin Li         handleUnexpectedCodeCompletionToken();
299*67e74705SXin Li       return false;
300*67e74705SXin Li 
301*67e74705SXin Li     case tok::l_paren:
302*67e74705SXin Li       // Recursively skip properly-nested parens.
303*67e74705SXin Li       ConsumeParen();
304*67e74705SXin Li       if (HasFlagsSet(Flags, StopAtCodeCompletion))
305*67e74705SXin Li         SkipUntil(tok::r_paren, StopAtCodeCompletion);
306*67e74705SXin Li       else
307*67e74705SXin Li         SkipUntil(tok::r_paren);
308*67e74705SXin Li       break;
309*67e74705SXin Li     case tok::l_square:
310*67e74705SXin Li       // Recursively skip properly-nested square brackets.
311*67e74705SXin Li       ConsumeBracket();
312*67e74705SXin Li       if (HasFlagsSet(Flags, StopAtCodeCompletion))
313*67e74705SXin Li         SkipUntil(tok::r_square, StopAtCodeCompletion);
314*67e74705SXin Li       else
315*67e74705SXin Li         SkipUntil(tok::r_square);
316*67e74705SXin Li       break;
317*67e74705SXin Li     case tok::l_brace:
318*67e74705SXin Li       // Recursively skip properly-nested braces.
319*67e74705SXin Li       ConsumeBrace();
320*67e74705SXin Li       if (HasFlagsSet(Flags, StopAtCodeCompletion))
321*67e74705SXin Li         SkipUntil(tok::r_brace, StopAtCodeCompletion);
322*67e74705SXin Li       else
323*67e74705SXin Li         SkipUntil(tok::r_brace);
324*67e74705SXin Li       break;
325*67e74705SXin Li 
326*67e74705SXin Li     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
327*67e74705SXin Li     // Since the user wasn't looking for this token (if they were, it would
328*67e74705SXin Li     // already be handled), this isn't balanced.  If there is a LHS token at a
329*67e74705SXin Li     // higher level, we will assume that this matches the unbalanced token
330*67e74705SXin Li     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
331*67e74705SXin Li     case tok::r_paren:
332*67e74705SXin Li       if (ParenCount && !isFirstTokenSkipped)
333*67e74705SXin Li         return false;  // Matches something.
334*67e74705SXin Li       ConsumeParen();
335*67e74705SXin Li       break;
336*67e74705SXin Li     case tok::r_square:
337*67e74705SXin Li       if (BracketCount && !isFirstTokenSkipped)
338*67e74705SXin Li         return false;  // Matches something.
339*67e74705SXin Li       ConsumeBracket();
340*67e74705SXin Li       break;
341*67e74705SXin Li     case tok::r_brace:
342*67e74705SXin Li       if (BraceCount && !isFirstTokenSkipped)
343*67e74705SXin Li         return false;  // Matches something.
344*67e74705SXin Li       ConsumeBrace();
345*67e74705SXin Li       break;
346*67e74705SXin Li 
347*67e74705SXin Li     case tok::string_literal:
348*67e74705SXin Li     case tok::wide_string_literal:
349*67e74705SXin Li     case tok::utf8_string_literal:
350*67e74705SXin Li     case tok::utf16_string_literal:
351*67e74705SXin Li     case tok::utf32_string_literal:
352*67e74705SXin Li       ConsumeStringToken();
353*67e74705SXin Li       break;
354*67e74705SXin Li 
355*67e74705SXin Li     case tok::semi:
356*67e74705SXin Li       if (HasFlagsSet(Flags, StopAtSemi))
357*67e74705SXin Li         return false;
358*67e74705SXin Li       // FALL THROUGH.
359*67e74705SXin Li     default:
360*67e74705SXin Li       // Skip this token.
361*67e74705SXin Li       ConsumeToken();
362*67e74705SXin Li       break;
363*67e74705SXin Li     }
364*67e74705SXin Li     isFirstTokenSkipped = false;
365*67e74705SXin Li   }
366*67e74705SXin Li }
367*67e74705SXin Li 
368*67e74705SXin Li //===----------------------------------------------------------------------===//
369*67e74705SXin Li // Scope manipulation
370*67e74705SXin Li //===----------------------------------------------------------------------===//
371*67e74705SXin Li 
372*67e74705SXin Li /// EnterScope - Start a new scope.
EnterScope(unsigned ScopeFlags)373*67e74705SXin Li void Parser::EnterScope(unsigned ScopeFlags) {
374*67e74705SXin Li   if (NumCachedScopes) {
375*67e74705SXin Li     Scope *N = ScopeCache[--NumCachedScopes];
376*67e74705SXin Li     N->Init(getCurScope(), ScopeFlags);
377*67e74705SXin Li     Actions.CurScope = N;
378*67e74705SXin Li   } else {
379*67e74705SXin Li     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
380*67e74705SXin Li   }
381*67e74705SXin Li }
382*67e74705SXin Li 
383*67e74705SXin Li /// ExitScope - Pop a scope off the scope stack.
ExitScope()384*67e74705SXin Li void Parser::ExitScope() {
385*67e74705SXin Li   assert(getCurScope() && "Scope imbalance!");
386*67e74705SXin Li 
387*67e74705SXin Li   // Inform the actions module that this scope is going away if there are any
388*67e74705SXin Li   // decls in it.
389*67e74705SXin Li   Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
390*67e74705SXin Li 
391*67e74705SXin Li   Scope *OldScope = getCurScope();
392*67e74705SXin Li   Actions.CurScope = OldScope->getParent();
393*67e74705SXin Li 
394*67e74705SXin Li   if (NumCachedScopes == ScopeCacheSize)
395*67e74705SXin Li     delete OldScope;
396*67e74705SXin Li   else
397*67e74705SXin Li     ScopeCache[NumCachedScopes++] = OldScope;
398*67e74705SXin Li }
399*67e74705SXin Li 
400*67e74705SXin Li /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
401*67e74705SXin Li /// this object does nothing.
ParseScopeFlags(Parser * Self,unsigned ScopeFlags,bool ManageFlags)402*67e74705SXin Li Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
403*67e74705SXin Li                                  bool ManageFlags)
404*67e74705SXin Li   : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
405*67e74705SXin Li   if (CurScope) {
406*67e74705SXin Li     OldFlags = CurScope->getFlags();
407*67e74705SXin Li     CurScope->setFlags(ScopeFlags);
408*67e74705SXin Li   }
409*67e74705SXin Li }
410*67e74705SXin Li 
411*67e74705SXin Li /// Restore the flags for the current scope to what they were before this
412*67e74705SXin Li /// object overrode them.
~ParseScopeFlags()413*67e74705SXin Li Parser::ParseScopeFlags::~ParseScopeFlags() {
414*67e74705SXin Li   if (CurScope)
415*67e74705SXin Li     CurScope->setFlags(OldFlags);
416*67e74705SXin Li }
417*67e74705SXin Li 
418*67e74705SXin Li 
419*67e74705SXin Li //===----------------------------------------------------------------------===//
420*67e74705SXin Li // C99 6.9: External Definitions.
421*67e74705SXin Li //===----------------------------------------------------------------------===//
422*67e74705SXin Li 
~Parser()423*67e74705SXin Li Parser::~Parser() {
424*67e74705SXin Li   // If we still have scopes active, delete the scope tree.
425*67e74705SXin Li   delete getCurScope();
426*67e74705SXin Li   Actions.CurScope = nullptr;
427*67e74705SXin Li 
428*67e74705SXin Li   // Free the scope cache.
429*67e74705SXin Li   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
430*67e74705SXin Li     delete ScopeCache[i];
431*67e74705SXin Li 
432*67e74705SXin Li   resetPragmaHandlers();
433*67e74705SXin Li 
434*67e74705SXin Li   PP.removeCommentHandler(CommentSemaHandler.get());
435*67e74705SXin Li 
436*67e74705SXin Li   PP.clearCodeCompletionHandler();
437*67e74705SXin Li 
438*67e74705SXin Li   if (getLangOpts().DelayedTemplateParsing &&
439*67e74705SXin Li       !PP.isIncrementalProcessingEnabled() && !TemplateIds.empty()) {
440*67e74705SXin Li     // If an ASTConsumer parsed delay-parsed templates in their
441*67e74705SXin Li     // HandleTranslationUnit() method, TemplateIds created there were not
442*67e74705SXin Li     // guarded by a DestroyTemplateIdAnnotationsRAIIObj object in
443*67e74705SXin Li     // ParseTopLevelDecl(). Destroy them here.
444*67e74705SXin Li     DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
445*67e74705SXin Li   }
446*67e74705SXin Li 
447*67e74705SXin Li   assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
448*67e74705SXin Li }
449*67e74705SXin Li 
450*67e74705SXin Li /// Initialize - Warm up the parser.
451*67e74705SXin Li ///
Initialize()452*67e74705SXin Li void Parser::Initialize() {
453*67e74705SXin Li   // Create the translation unit scope.  Install it as the current scope.
454*67e74705SXin Li   assert(getCurScope() == nullptr && "A scope is already active?");
455*67e74705SXin Li   EnterScope(Scope::DeclScope);
456*67e74705SXin Li   Actions.ActOnTranslationUnitScope(getCurScope());
457*67e74705SXin Li 
458*67e74705SXin Li   // Initialization for Objective-C context sensitive keywords recognition.
459*67e74705SXin Li   // Referenced in Parser::ParseObjCTypeQualifierList.
460*67e74705SXin Li   if (getLangOpts().ObjC1) {
461*67e74705SXin Li     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
462*67e74705SXin Li     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
463*67e74705SXin Li     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
464*67e74705SXin Li     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
465*67e74705SXin Li     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
466*67e74705SXin Li     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
467*67e74705SXin Li     ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
468*67e74705SXin Li     ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
469*67e74705SXin Li     ObjCTypeQuals[objc_null_unspecified]
470*67e74705SXin Li       = &PP.getIdentifierTable().get("null_unspecified");
471*67e74705SXin Li   }
472*67e74705SXin Li 
473*67e74705SXin Li   Ident_instancetype = nullptr;
474*67e74705SXin Li   Ident_final = nullptr;
475*67e74705SXin Li   Ident_sealed = nullptr;
476*67e74705SXin Li   Ident_override = nullptr;
477*67e74705SXin Li 
478*67e74705SXin Li   Ident_super = &PP.getIdentifierTable().get("super");
479*67e74705SXin Li 
480*67e74705SXin Li   Ident_vector = nullptr;
481*67e74705SXin Li   Ident_bool = nullptr;
482*67e74705SXin Li   Ident_pixel = nullptr;
483*67e74705SXin Li   if (getLangOpts().AltiVec || getLangOpts().ZVector) {
484*67e74705SXin Li     Ident_vector = &PP.getIdentifierTable().get("vector");
485*67e74705SXin Li     Ident_bool = &PP.getIdentifierTable().get("bool");
486*67e74705SXin Li   }
487*67e74705SXin Li   if (getLangOpts().AltiVec)
488*67e74705SXin Li     Ident_pixel = &PP.getIdentifierTable().get("pixel");
489*67e74705SXin Li 
490*67e74705SXin Li   Ident_introduced = nullptr;
491*67e74705SXin Li   Ident_deprecated = nullptr;
492*67e74705SXin Li   Ident_obsoleted = nullptr;
493*67e74705SXin Li   Ident_unavailable = nullptr;
494*67e74705SXin Li   Ident_strict = nullptr;
495*67e74705SXin Li   Ident_replacement = nullptr;
496*67e74705SXin Li 
497*67e74705SXin Li   Ident__except = nullptr;
498*67e74705SXin Li 
499*67e74705SXin Li   Ident__exception_code = Ident__exception_info = nullptr;
500*67e74705SXin Li   Ident__abnormal_termination = Ident___exception_code = nullptr;
501*67e74705SXin Li   Ident___exception_info = Ident___abnormal_termination = nullptr;
502*67e74705SXin Li   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
503*67e74705SXin Li   Ident_AbnormalTermination = nullptr;
504*67e74705SXin Li 
505*67e74705SXin Li   if(getLangOpts().Borland) {
506*67e74705SXin Li     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
507*67e74705SXin Li     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
508*67e74705SXin Li     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
509*67e74705SXin Li     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
510*67e74705SXin Li     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
511*67e74705SXin Li     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
512*67e74705SXin Li     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
513*67e74705SXin Li     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
514*67e74705SXin Li     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
515*67e74705SXin Li 
516*67e74705SXin Li     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
517*67e74705SXin Li     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
518*67e74705SXin Li     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
519*67e74705SXin Li     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
520*67e74705SXin Li     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
521*67e74705SXin Li     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
522*67e74705SXin Li     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
523*67e74705SXin Li     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
524*67e74705SXin Li     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
525*67e74705SXin Li   }
526*67e74705SXin Li 
527*67e74705SXin Li   Actions.Initialize();
528*67e74705SXin Li 
529*67e74705SXin Li   // Prime the lexer look-ahead.
530*67e74705SXin Li   ConsumeToken();
531*67e74705SXin Li }
532*67e74705SXin Li 
LateTemplateParserCleanupCallback(void * P)533*67e74705SXin Li void Parser::LateTemplateParserCleanupCallback(void *P) {
534*67e74705SXin Li   // While this RAII helper doesn't bracket any actual work, the destructor will
535*67e74705SXin Li   // clean up annotations that were created during ActOnEndOfTranslationUnit
536*67e74705SXin Li   // when incremental processing is enabled.
537*67e74705SXin Li   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
538*67e74705SXin Li }
539*67e74705SXin Li 
540*67e74705SXin Li /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
541*67e74705SXin Li /// action tells us to.  This returns true if the EOF was encountered.
ParseTopLevelDecl(DeclGroupPtrTy & Result)542*67e74705SXin Li bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
543*67e74705SXin Li   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
544*67e74705SXin Li 
545*67e74705SXin Li   // Skip over the EOF token, flagging end of previous input for incremental
546*67e74705SXin Li   // processing
547*67e74705SXin Li   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
548*67e74705SXin Li     ConsumeToken();
549*67e74705SXin Li 
550*67e74705SXin Li   Result = nullptr;
551*67e74705SXin Li   switch (Tok.getKind()) {
552*67e74705SXin Li   case tok::annot_pragma_unused:
553*67e74705SXin Li     HandlePragmaUnused();
554*67e74705SXin Li     return false;
555*67e74705SXin Li 
556*67e74705SXin Li   case tok::annot_module_include:
557*67e74705SXin Li     Actions.ActOnModuleInclude(Tok.getLocation(),
558*67e74705SXin Li                                reinterpret_cast<Module *>(
559*67e74705SXin Li                                    Tok.getAnnotationValue()));
560*67e74705SXin Li     ConsumeToken();
561*67e74705SXin Li     return false;
562*67e74705SXin Li 
563*67e74705SXin Li   case tok::annot_module_begin:
564*67e74705SXin Li     Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
565*67e74705SXin Li                                                     Tok.getAnnotationValue()));
566*67e74705SXin Li     ConsumeToken();
567*67e74705SXin Li     return false;
568*67e74705SXin Li 
569*67e74705SXin Li   case tok::annot_module_end:
570*67e74705SXin Li     Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
571*67e74705SXin Li                                                   Tok.getAnnotationValue()));
572*67e74705SXin Li     ConsumeToken();
573*67e74705SXin Li     return false;
574*67e74705SXin Li 
575*67e74705SXin Li   case tok::eof:
576*67e74705SXin Li     // Late template parsing can begin.
577*67e74705SXin Li     if (getLangOpts().DelayedTemplateParsing)
578*67e74705SXin Li       Actions.SetLateTemplateParser(LateTemplateParserCallback,
579*67e74705SXin Li                                     PP.isIncrementalProcessingEnabled() ?
580*67e74705SXin Li                                     LateTemplateParserCleanupCallback : nullptr,
581*67e74705SXin Li                                     this);
582*67e74705SXin Li     if (!PP.isIncrementalProcessingEnabled())
583*67e74705SXin Li       Actions.ActOnEndOfTranslationUnit();
584*67e74705SXin Li     //else don't tell Sema that we ended parsing: more input might come.
585*67e74705SXin Li     return true;
586*67e74705SXin Li 
587*67e74705SXin Li   default:
588*67e74705SXin Li     break;
589*67e74705SXin Li   }
590*67e74705SXin Li 
591*67e74705SXin Li   ParsedAttributesWithRange attrs(AttrFactory);
592*67e74705SXin Li   MaybeParseCXX11Attributes(attrs);
593*67e74705SXin Li   MaybeParseMicrosoftAttributes(attrs);
594*67e74705SXin Li 
595*67e74705SXin Li   Result = ParseExternalDeclaration(attrs);
596*67e74705SXin Li   return false;
597*67e74705SXin Li }
598*67e74705SXin Li 
599*67e74705SXin Li /// ParseExternalDeclaration:
600*67e74705SXin Li ///
601*67e74705SXin Li ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
602*67e74705SXin Li ///         function-definition
603*67e74705SXin Li ///         declaration
604*67e74705SXin Li /// [GNU]   asm-definition
605*67e74705SXin Li /// [GNU]   __extension__ external-declaration
606*67e74705SXin Li /// [OBJC]  objc-class-definition
607*67e74705SXin Li /// [OBJC]  objc-class-declaration
608*67e74705SXin Li /// [OBJC]  objc-alias-declaration
609*67e74705SXin Li /// [OBJC]  objc-protocol-definition
610*67e74705SXin Li /// [OBJC]  objc-method-definition
611*67e74705SXin Li /// [OBJC]  @end
612*67e74705SXin Li /// [C++]   linkage-specification
613*67e74705SXin Li /// [GNU] asm-definition:
614*67e74705SXin Li ///         simple-asm-expr ';'
615*67e74705SXin Li /// [C++11] empty-declaration
616*67e74705SXin Li /// [C++11] attribute-declaration
617*67e74705SXin Li ///
618*67e74705SXin Li /// [C++11] empty-declaration:
619*67e74705SXin Li ///           ';'
620*67e74705SXin Li ///
621*67e74705SXin Li /// [C++0x/GNU] 'extern' 'template' declaration
622*67e74705SXin Li Parser::DeclGroupPtrTy
ParseExternalDeclaration(ParsedAttributesWithRange & attrs,ParsingDeclSpec * DS)623*67e74705SXin Li Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
624*67e74705SXin Li                                  ParsingDeclSpec *DS) {
625*67e74705SXin Li   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
626*67e74705SXin Li   ParenBraceBracketBalancer BalancerRAIIObj(*this);
627*67e74705SXin Li 
628*67e74705SXin Li   if (PP.isCodeCompletionReached()) {
629*67e74705SXin Li     cutOffParsing();
630*67e74705SXin Li     return nullptr;
631*67e74705SXin Li   }
632*67e74705SXin Li 
633*67e74705SXin Li   Decl *SingleDecl = nullptr;
634*67e74705SXin Li   switch (Tok.getKind()) {
635*67e74705SXin Li   case tok::annot_pragma_vis:
636*67e74705SXin Li     HandlePragmaVisibility();
637*67e74705SXin Li     return nullptr;
638*67e74705SXin Li   case tok::annot_pragma_pack:
639*67e74705SXin Li     HandlePragmaPack();
640*67e74705SXin Li     return nullptr;
641*67e74705SXin Li   case tok::annot_pragma_msstruct:
642*67e74705SXin Li     HandlePragmaMSStruct();
643*67e74705SXin Li     return nullptr;
644*67e74705SXin Li   case tok::annot_pragma_align:
645*67e74705SXin Li     HandlePragmaAlign();
646*67e74705SXin Li     return nullptr;
647*67e74705SXin Li   case tok::annot_pragma_weak:
648*67e74705SXin Li     HandlePragmaWeak();
649*67e74705SXin Li     return nullptr;
650*67e74705SXin Li   case tok::annot_pragma_weakalias:
651*67e74705SXin Li     HandlePragmaWeakAlias();
652*67e74705SXin Li     return nullptr;
653*67e74705SXin Li   case tok::annot_pragma_redefine_extname:
654*67e74705SXin Li     HandlePragmaRedefineExtname();
655*67e74705SXin Li     return nullptr;
656*67e74705SXin Li   case tok::annot_pragma_fp_contract:
657*67e74705SXin Li     HandlePragmaFPContract();
658*67e74705SXin Li     return nullptr;
659*67e74705SXin Li   case tok::annot_pragma_opencl_extension:
660*67e74705SXin Li     HandlePragmaOpenCLExtension();
661*67e74705SXin Li     return nullptr;
662*67e74705SXin Li   case tok::annot_pragma_openmp: {
663*67e74705SXin Li     AccessSpecifier AS = AS_none;
664*67e74705SXin Li     return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
665*67e74705SXin Li   }
666*67e74705SXin Li   case tok::annot_pragma_ms_pointers_to_members:
667*67e74705SXin Li     HandlePragmaMSPointersToMembers();
668*67e74705SXin Li     return nullptr;
669*67e74705SXin Li   case tok::annot_pragma_ms_vtordisp:
670*67e74705SXin Li     HandlePragmaMSVtorDisp();
671*67e74705SXin Li     return nullptr;
672*67e74705SXin Li   case tok::annot_pragma_ms_pragma:
673*67e74705SXin Li     HandlePragmaMSPragma();
674*67e74705SXin Li     return nullptr;
675*67e74705SXin Li   case tok::annot_pragma_dump:
676*67e74705SXin Li     HandlePragmaDump();
677*67e74705SXin Li     return nullptr;
678*67e74705SXin Li   case tok::semi:
679*67e74705SXin Li     // Either a C++11 empty-declaration or attribute-declaration.
680*67e74705SXin Li     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
681*67e74705SXin Li                                                attrs.getList(),
682*67e74705SXin Li                                                Tok.getLocation());
683*67e74705SXin Li     ConsumeExtraSemi(OutsideFunction);
684*67e74705SXin Li     break;
685*67e74705SXin Li   case tok::r_brace:
686*67e74705SXin Li     Diag(Tok, diag::err_extraneous_closing_brace);
687*67e74705SXin Li     ConsumeBrace();
688*67e74705SXin Li     return nullptr;
689*67e74705SXin Li   case tok::eof:
690*67e74705SXin Li     Diag(Tok, diag::err_expected_external_declaration);
691*67e74705SXin Li     return nullptr;
692*67e74705SXin Li   case tok::kw___extension__: {
693*67e74705SXin Li     // __extension__ silences extension warnings in the subexpression.
694*67e74705SXin Li     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
695*67e74705SXin Li     ConsumeToken();
696*67e74705SXin Li     return ParseExternalDeclaration(attrs);
697*67e74705SXin Li   }
698*67e74705SXin Li   case tok::kw_asm: {
699*67e74705SXin Li     ProhibitAttributes(attrs);
700*67e74705SXin Li 
701*67e74705SXin Li     SourceLocation StartLoc = Tok.getLocation();
702*67e74705SXin Li     SourceLocation EndLoc;
703*67e74705SXin Li 
704*67e74705SXin Li     ExprResult Result(ParseSimpleAsm(&EndLoc));
705*67e74705SXin Li 
706*67e74705SXin Li     // Check if GNU-style InlineAsm is disabled.
707*67e74705SXin Li     // Empty asm string is allowed because it will not introduce
708*67e74705SXin Li     // any assembly code.
709*67e74705SXin Li     if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
710*67e74705SXin Li       const auto *SL = cast<StringLiteral>(Result.get());
711*67e74705SXin Li       if (!SL->getString().trim().empty())
712*67e74705SXin Li         Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
713*67e74705SXin Li     }
714*67e74705SXin Li 
715*67e74705SXin Li     ExpectAndConsume(tok::semi, diag::err_expected_after,
716*67e74705SXin Li                      "top-level asm block");
717*67e74705SXin Li 
718*67e74705SXin Li     if (Result.isInvalid())
719*67e74705SXin Li       return nullptr;
720*67e74705SXin Li     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
721*67e74705SXin Li     break;
722*67e74705SXin Li   }
723*67e74705SXin Li   case tok::at:
724*67e74705SXin Li     return ParseObjCAtDirectives();
725*67e74705SXin Li   case tok::minus:
726*67e74705SXin Li   case tok::plus:
727*67e74705SXin Li     if (!getLangOpts().ObjC1) {
728*67e74705SXin Li       Diag(Tok, diag::err_expected_external_declaration);
729*67e74705SXin Li       ConsumeToken();
730*67e74705SXin Li       return nullptr;
731*67e74705SXin Li     }
732*67e74705SXin Li     SingleDecl = ParseObjCMethodDefinition();
733*67e74705SXin Li     break;
734*67e74705SXin Li   case tok::code_completion:
735*67e74705SXin Li       Actions.CodeCompleteOrdinaryName(getCurScope(),
736*67e74705SXin Li                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
737*67e74705SXin Li                                               : Sema::PCC_Namespace);
738*67e74705SXin Li     cutOffParsing();
739*67e74705SXin Li     return nullptr;
740*67e74705SXin Li   case tok::kw_using:
741*67e74705SXin Li   case tok::kw_namespace:
742*67e74705SXin Li   case tok::kw_typedef:
743*67e74705SXin Li   case tok::kw_template:
744*67e74705SXin Li   case tok::kw_export:    // As in 'export template'
745*67e74705SXin Li   case tok::kw_static_assert:
746*67e74705SXin Li   case tok::kw__Static_assert:
747*67e74705SXin Li     // A function definition cannot start with any of these keywords.
748*67e74705SXin Li     {
749*67e74705SXin Li       SourceLocation DeclEnd;
750*67e74705SXin Li       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
751*67e74705SXin Li     }
752*67e74705SXin Li 
753*67e74705SXin Li   case tok::kw_static:
754*67e74705SXin Li     // Parse (then ignore) 'static' prior to a template instantiation. This is
755*67e74705SXin Li     // a GCC extension that we intentionally do not support.
756*67e74705SXin Li     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
757*67e74705SXin Li       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
758*67e74705SXin Li         << 0;
759*67e74705SXin Li       SourceLocation DeclEnd;
760*67e74705SXin Li       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
761*67e74705SXin Li     }
762*67e74705SXin Li     goto dont_know;
763*67e74705SXin Li 
764*67e74705SXin Li   case tok::kw_inline:
765*67e74705SXin Li     if (getLangOpts().CPlusPlus) {
766*67e74705SXin Li       tok::TokenKind NextKind = NextToken().getKind();
767*67e74705SXin Li 
768*67e74705SXin Li       // Inline namespaces. Allowed as an extension even in C++03.
769*67e74705SXin Li       if (NextKind == tok::kw_namespace) {
770*67e74705SXin Li         SourceLocation DeclEnd;
771*67e74705SXin Li         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
772*67e74705SXin Li       }
773*67e74705SXin Li 
774*67e74705SXin Li       // Parse (then ignore) 'inline' prior to a template instantiation. This is
775*67e74705SXin Li       // a GCC extension that we intentionally do not support.
776*67e74705SXin Li       if (NextKind == tok::kw_template) {
777*67e74705SXin Li         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
778*67e74705SXin Li           << 1;
779*67e74705SXin Li         SourceLocation DeclEnd;
780*67e74705SXin Li         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
781*67e74705SXin Li       }
782*67e74705SXin Li     }
783*67e74705SXin Li     goto dont_know;
784*67e74705SXin Li 
785*67e74705SXin Li   case tok::kw_extern:
786*67e74705SXin Li     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
787*67e74705SXin Li       // Extern templates
788*67e74705SXin Li       SourceLocation ExternLoc = ConsumeToken();
789*67e74705SXin Li       SourceLocation TemplateLoc = ConsumeToken();
790*67e74705SXin Li       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
791*67e74705SXin Li              diag::warn_cxx98_compat_extern_template :
792*67e74705SXin Li              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
793*67e74705SXin Li       SourceLocation DeclEnd;
794*67e74705SXin Li       return Actions.ConvertDeclToDeclGroup(
795*67e74705SXin Li                   ParseExplicitInstantiation(Declarator::FileContext,
796*67e74705SXin Li                                              ExternLoc, TemplateLoc, DeclEnd));
797*67e74705SXin Li     }
798*67e74705SXin Li     goto dont_know;
799*67e74705SXin Li 
800*67e74705SXin Li   case tok::kw___if_exists:
801*67e74705SXin Li   case tok::kw___if_not_exists:
802*67e74705SXin Li     ParseMicrosoftIfExistsExternalDeclaration();
803*67e74705SXin Li     return nullptr;
804*67e74705SXin Li 
805*67e74705SXin Li   default:
806*67e74705SXin Li   dont_know:
807*67e74705SXin Li     // We can't tell whether this is a function-definition or declaration yet.
808*67e74705SXin Li     return ParseDeclarationOrFunctionDefinition(attrs, DS);
809*67e74705SXin Li   }
810*67e74705SXin Li 
811*67e74705SXin Li   // This routine returns a DeclGroup, if the thing we parsed only contains a
812*67e74705SXin Li   // single decl, convert it now.
813*67e74705SXin Li   return Actions.ConvertDeclToDeclGroup(SingleDecl);
814*67e74705SXin Li }
815*67e74705SXin Li 
816*67e74705SXin Li /// \brief Determine whether the current token, if it occurs after a
817*67e74705SXin Li /// declarator, continues a declaration or declaration list.
isDeclarationAfterDeclarator()818*67e74705SXin Li bool Parser::isDeclarationAfterDeclarator() {
819*67e74705SXin Li   // Check for '= delete' or '= default'
820*67e74705SXin Li   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
821*67e74705SXin Li     const Token &KW = NextToken();
822*67e74705SXin Li     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
823*67e74705SXin Li       return false;
824*67e74705SXin Li   }
825*67e74705SXin Li 
826*67e74705SXin Li   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
827*67e74705SXin Li     Tok.is(tok::comma) ||           // int X(),  -> not a function def
828*67e74705SXin Li     Tok.is(tok::semi)  ||           // int X();  -> not a function def
829*67e74705SXin Li     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
830*67e74705SXin Li     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
831*67e74705SXin Li     (getLangOpts().CPlusPlus &&
832*67e74705SXin Li      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
833*67e74705SXin Li }
834*67e74705SXin Li 
835*67e74705SXin Li /// \brief Determine whether the current token, if it occurs after a
836*67e74705SXin Li /// declarator, indicates the start of a function definition.
isStartOfFunctionDefinition(const ParsingDeclarator & Declarator)837*67e74705SXin Li bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
838*67e74705SXin Li   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
839*67e74705SXin Li   if (Tok.is(tok::l_brace))   // int X() {}
840*67e74705SXin Li     return true;
841*67e74705SXin Li 
842*67e74705SXin Li   // Handle K&R C argument lists: int X(f) int f; {}
843*67e74705SXin Li   if (!getLangOpts().CPlusPlus &&
844*67e74705SXin Li       Declarator.getFunctionTypeInfo().isKNRPrototype())
845*67e74705SXin Li     return isDeclarationSpecifier();
846*67e74705SXin Li 
847*67e74705SXin Li   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
848*67e74705SXin Li     const Token &KW = NextToken();
849*67e74705SXin Li     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
850*67e74705SXin Li   }
851*67e74705SXin Li 
852*67e74705SXin Li   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
853*67e74705SXin Li          Tok.is(tok::kw_try);          // X() try { ... }
854*67e74705SXin Li }
855*67e74705SXin Li 
856*67e74705SXin Li /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
857*67e74705SXin Li /// a declaration.  We can't tell which we have until we read up to the
858*67e74705SXin Li /// compound-statement in function-definition. TemplateParams, if
859*67e74705SXin Li /// non-NULL, provides the template parameters when we're parsing a
860*67e74705SXin Li /// C++ template-declaration.
861*67e74705SXin Li ///
862*67e74705SXin Li ///       function-definition: [C99 6.9.1]
863*67e74705SXin Li ///         decl-specs      declarator declaration-list[opt] compound-statement
864*67e74705SXin Li /// [C90] function-definition: [C99 6.7.1] - implicit int result
865*67e74705SXin Li /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
866*67e74705SXin Li ///
867*67e74705SXin Li ///       declaration: [C99 6.7]
868*67e74705SXin Li ///         declaration-specifiers init-declarator-list[opt] ';'
869*67e74705SXin Li /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
870*67e74705SXin Li /// [OMP]   threadprivate-directive                              [TODO]
871*67e74705SXin Li ///
872*67e74705SXin Li Parser::DeclGroupPtrTy
ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange & attrs,ParsingDeclSpec & DS,AccessSpecifier AS)873*67e74705SXin Li Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
874*67e74705SXin Li                                        ParsingDeclSpec &DS,
875*67e74705SXin Li                                        AccessSpecifier AS) {
876*67e74705SXin Li   // Parse the common declaration-specifiers piece.
877*67e74705SXin Li   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
878*67e74705SXin Li 
879*67e74705SXin Li   // If we had a free-standing type definition with a missing semicolon, we
880*67e74705SXin Li   // may get this far before the problem becomes obvious.
881*67e74705SXin Li   if (DS.hasTagDefinition() &&
882*67e74705SXin Li       DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
883*67e74705SXin Li     return nullptr;
884*67e74705SXin Li 
885*67e74705SXin Li   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
886*67e74705SXin Li   // declaration-specifiers init-declarator-list[opt] ';'
887*67e74705SXin Li   if (Tok.is(tok::semi)) {
888*67e74705SXin Li     ProhibitAttributes(attrs);
889*67e74705SXin Li     ConsumeToken();
890*67e74705SXin Li     RecordDecl *AnonRecord = nullptr;
891*67e74705SXin Li     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
892*67e74705SXin Li                                                        DS, AnonRecord);
893*67e74705SXin Li     DS.complete(TheDecl);
894*67e74705SXin Li     if (AnonRecord) {
895*67e74705SXin Li       Decl* decls[] = {AnonRecord, TheDecl};
896*67e74705SXin Li       return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
897*67e74705SXin Li     }
898*67e74705SXin Li     return Actions.ConvertDeclToDeclGroup(TheDecl);
899*67e74705SXin Li   }
900*67e74705SXin Li 
901*67e74705SXin Li   DS.takeAttributesFrom(attrs);
902*67e74705SXin Li 
903*67e74705SXin Li   // ObjC2 allows prefix attributes on class interfaces and protocols.
904*67e74705SXin Li   // FIXME: This still needs better diagnostics. We should only accept
905*67e74705SXin Li   // attributes here, no types, etc.
906*67e74705SXin Li   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
907*67e74705SXin Li     SourceLocation AtLoc = ConsumeToken(); // the "@"
908*67e74705SXin Li     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
909*67e74705SXin Li         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
910*67e74705SXin Li       Diag(Tok, diag::err_objc_unexpected_attr);
911*67e74705SXin Li       SkipUntil(tok::semi); // FIXME: better skip?
912*67e74705SXin Li       return nullptr;
913*67e74705SXin Li     }
914*67e74705SXin Li 
915*67e74705SXin Li     DS.abort();
916*67e74705SXin Li 
917*67e74705SXin Li     const char *PrevSpec = nullptr;
918*67e74705SXin Li     unsigned DiagID;
919*67e74705SXin Li     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
920*67e74705SXin Li                            Actions.getASTContext().getPrintingPolicy()))
921*67e74705SXin Li       Diag(AtLoc, DiagID) << PrevSpec;
922*67e74705SXin Li 
923*67e74705SXin Li     if (Tok.isObjCAtKeyword(tok::objc_protocol))
924*67e74705SXin Li       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
925*67e74705SXin Li 
926*67e74705SXin Li     return Actions.ConvertDeclToDeclGroup(
927*67e74705SXin Li             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
928*67e74705SXin Li   }
929*67e74705SXin Li 
930*67e74705SXin Li   // If the declspec consisted only of 'extern' and we have a string
931*67e74705SXin Li   // literal following it, this must be a C++ linkage specifier like
932*67e74705SXin Li   // 'extern "C"'.
933*67e74705SXin Li   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
934*67e74705SXin Li       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
935*67e74705SXin Li       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
936*67e74705SXin Li     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
937*67e74705SXin Li     return Actions.ConvertDeclToDeclGroup(TheDecl);
938*67e74705SXin Li   }
939*67e74705SXin Li 
940*67e74705SXin Li   return ParseDeclGroup(DS, Declarator::FileContext);
941*67e74705SXin Li }
942*67e74705SXin Li 
943*67e74705SXin Li Parser::DeclGroupPtrTy
ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange & attrs,ParsingDeclSpec * DS,AccessSpecifier AS)944*67e74705SXin Li Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
945*67e74705SXin Li                                              ParsingDeclSpec *DS,
946*67e74705SXin Li                                              AccessSpecifier AS) {
947*67e74705SXin Li   if (DS) {
948*67e74705SXin Li     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
949*67e74705SXin Li   } else {
950*67e74705SXin Li     ParsingDeclSpec PDS(*this);
951*67e74705SXin Li     // Must temporarily exit the objective-c container scope for
952*67e74705SXin Li     // parsing c constructs and re-enter objc container scope
953*67e74705SXin Li     // afterwards.
954*67e74705SXin Li     ObjCDeclContextSwitch ObjCDC(*this);
955*67e74705SXin Li 
956*67e74705SXin Li     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
957*67e74705SXin Li   }
958*67e74705SXin Li }
959*67e74705SXin Li 
960*67e74705SXin Li /// ParseFunctionDefinition - We parsed and verified that the specified
961*67e74705SXin Li /// Declarator is well formed.  If this is a K&R-style function, read the
962*67e74705SXin Li /// parameters declaration-list, then start the compound-statement.
963*67e74705SXin Li ///
964*67e74705SXin Li ///       function-definition: [C99 6.9.1]
965*67e74705SXin Li ///         decl-specs      declarator declaration-list[opt] compound-statement
966*67e74705SXin Li /// [C90] function-definition: [C99 6.7.1] - implicit int result
967*67e74705SXin Li /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
968*67e74705SXin Li /// [C++] function-definition: [C++ 8.4]
969*67e74705SXin Li ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
970*67e74705SXin Li ///         function-body
971*67e74705SXin Li /// [C++] function-definition: [C++ 8.4]
972*67e74705SXin Li ///         decl-specifier-seq[opt] declarator function-try-block
973*67e74705SXin Li ///
ParseFunctionDefinition(ParsingDeclarator & D,const ParsedTemplateInfo & TemplateInfo,LateParsedAttrList * LateParsedAttrs)974*67e74705SXin Li Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
975*67e74705SXin Li                                       const ParsedTemplateInfo &TemplateInfo,
976*67e74705SXin Li                                       LateParsedAttrList *LateParsedAttrs) {
977*67e74705SXin Li   // Poison SEH identifiers so they are flagged as illegal in function bodies.
978*67e74705SXin Li   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
979*67e74705SXin Li   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
980*67e74705SXin Li 
981*67e74705SXin Li   // If this is C90 and the declspecs were completely missing, fudge in an
982*67e74705SXin Li   // implicit int.  We do this here because this is the only place where
983*67e74705SXin Li   // declaration-specifiers are completely optional in the grammar.
984*67e74705SXin Li   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
985*67e74705SXin Li     const char *PrevSpec;
986*67e74705SXin Li     unsigned DiagID;
987*67e74705SXin Li     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
988*67e74705SXin Li     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
989*67e74705SXin Li                                            D.getIdentifierLoc(),
990*67e74705SXin Li                                            PrevSpec, DiagID,
991*67e74705SXin Li                                            Policy);
992*67e74705SXin Li     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
993*67e74705SXin Li   }
994*67e74705SXin Li 
995*67e74705SXin Li   // If this declaration was formed with a K&R-style identifier list for the
996*67e74705SXin Li   // arguments, parse declarations for all of the args next.
997*67e74705SXin Li   // int foo(a,b) int a; float b; {}
998*67e74705SXin Li   if (FTI.isKNRPrototype())
999*67e74705SXin Li     ParseKNRParamDeclarations(D);
1000*67e74705SXin Li 
1001*67e74705SXin Li   // We should have either an opening brace or, in a C++ constructor,
1002*67e74705SXin Li   // we may have a colon.
1003*67e74705SXin Li   if (Tok.isNot(tok::l_brace) &&
1004*67e74705SXin Li       (!getLangOpts().CPlusPlus ||
1005*67e74705SXin Li        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1006*67e74705SXin Li         Tok.isNot(tok::equal)))) {
1007*67e74705SXin Li     Diag(Tok, diag::err_expected_fn_body);
1008*67e74705SXin Li 
1009*67e74705SXin Li     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1010*67e74705SXin Li     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1011*67e74705SXin Li 
1012*67e74705SXin Li     // If we didn't find the '{', bail out.
1013*67e74705SXin Li     if (Tok.isNot(tok::l_brace))
1014*67e74705SXin Li       return nullptr;
1015*67e74705SXin Li   }
1016*67e74705SXin Li 
1017*67e74705SXin Li   // Check to make sure that any normal attributes are allowed to be on
1018*67e74705SXin Li   // a definition.  Late parsed attributes are checked at the end.
1019*67e74705SXin Li   if (Tok.isNot(tok::equal)) {
1020*67e74705SXin Li     AttributeList *DtorAttrs = D.getAttributes();
1021*67e74705SXin Li     while (DtorAttrs) {
1022*67e74705SXin Li       if (DtorAttrs->isKnownToGCC() &&
1023*67e74705SXin Li           !DtorAttrs->isCXX11Attribute()) {
1024*67e74705SXin Li         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
1025*67e74705SXin Li           << DtorAttrs->getName();
1026*67e74705SXin Li       }
1027*67e74705SXin Li       DtorAttrs = DtorAttrs->getNext();
1028*67e74705SXin Li     }
1029*67e74705SXin Li   }
1030*67e74705SXin Li 
1031*67e74705SXin Li   // In delayed template parsing mode, for function template we consume the
1032*67e74705SXin Li   // tokens and store them for late parsing at the end of the translation unit.
1033*67e74705SXin Li   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1034*67e74705SXin Li       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1035*67e74705SXin Li       Actions.canDelayFunctionBody(D)) {
1036*67e74705SXin Li     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1037*67e74705SXin Li 
1038*67e74705SXin Li     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1039*67e74705SXin Li     Scope *ParentScope = getCurScope()->getParent();
1040*67e74705SXin Li 
1041*67e74705SXin Li     D.setFunctionDefinitionKind(FDK_Definition);
1042*67e74705SXin Li     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1043*67e74705SXin Li                                         TemplateParameterLists);
1044*67e74705SXin Li     D.complete(DP);
1045*67e74705SXin Li     D.getMutableDeclSpec().abort();
1046*67e74705SXin Li 
1047*67e74705SXin Li     if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1048*67e74705SXin Li         trySkippingFunctionBody()) {
1049*67e74705SXin Li       BodyScope.Exit();
1050*67e74705SXin Li       return Actions.ActOnSkippedFunctionBody(DP);
1051*67e74705SXin Li     }
1052*67e74705SXin Li 
1053*67e74705SXin Li     CachedTokens Toks;
1054*67e74705SXin Li     LexTemplateFunctionForLateParsing(Toks);
1055*67e74705SXin Li 
1056*67e74705SXin Li     if (DP) {
1057*67e74705SXin Li       FunctionDecl *FnD = DP->getAsFunction();
1058*67e74705SXin Li       Actions.CheckForFunctionRedefinition(FnD);
1059*67e74705SXin Li       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1060*67e74705SXin Li     }
1061*67e74705SXin Li     return DP;
1062*67e74705SXin Li   }
1063*67e74705SXin Li   else if (CurParsedObjCImpl &&
1064*67e74705SXin Li            !TemplateInfo.TemplateParams &&
1065*67e74705SXin Li            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1066*67e74705SXin Li             Tok.is(tok::colon)) &&
1067*67e74705SXin Li       Actions.CurContext->isTranslationUnit()) {
1068*67e74705SXin Li     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1069*67e74705SXin Li     Scope *ParentScope = getCurScope()->getParent();
1070*67e74705SXin Li 
1071*67e74705SXin Li     D.setFunctionDefinitionKind(FDK_Definition);
1072*67e74705SXin Li     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1073*67e74705SXin Li                                               MultiTemplateParamsArg());
1074*67e74705SXin Li     D.complete(FuncDecl);
1075*67e74705SXin Li     D.getMutableDeclSpec().abort();
1076*67e74705SXin Li     if (FuncDecl) {
1077*67e74705SXin Li       // Consume the tokens and store them for later parsing.
1078*67e74705SXin Li       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1079*67e74705SXin Li       CurParsedObjCImpl->HasCFunction = true;
1080*67e74705SXin Li       return FuncDecl;
1081*67e74705SXin Li     }
1082*67e74705SXin Li     // FIXME: Should we really fall through here?
1083*67e74705SXin Li   }
1084*67e74705SXin Li 
1085*67e74705SXin Li   // Enter a scope for the function body.
1086*67e74705SXin Li   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1087*67e74705SXin Li 
1088*67e74705SXin Li   // Tell the actions module that we have entered a function definition with the
1089*67e74705SXin Li   // specified Declarator for the function.
1090*67e74705SXin Li   Sema::SkipBodyInfo SkipBody;
1091*67e74705SXin Li   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1092*67e74705SXin Li                                               TemplateInfo.TemplateParams
1093*67e74705SXin Li                                                   ? *TemplateInfo.TemplateParams
1094*67e74705SXin Li                                                   : MultiTemplateParamsArg(),
1095*67e74705SXin Li                                               &SkipBody);
1096*67e74705SXin Li 
1097*67e74705SXin Li   if (SkipBody.ShouldSkip) {
1098*67e74705SXin Li     SkipFunctionBody();
1099*67e74705SXin Li     return Res;
1100*67e74705SXin Li   }
1101*67e74705SXin Li 
1102*67e74705SXin Li   // Break out of the ParsingDeclarator context before we parse the body.
1103*67e74705SXin Li   D.complete(Res);
1104*67e74705SXin Li 
1105*67e74705SXin Li   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1106*67e74705SXin Li   // safe because we're always the sole owner.
1107*67e74705SXin Li   D.getMutableDeclSpec().abort();
1108*67e74705SXin Li 
1109*67e74705SXin Li   if (TryConsumeToken(tok::equal)) {
1110*67e74705SXin Li     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1111*67e74705SXin Li 
1112*67e74705SXin Li     bool Delete = false;
1113*67e74705SXin Li     SourceLocation KWLoc;
1114*67e74705SXin Li     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1115*67e74705SXin Li       Diag(KWLoc, getLangOpts().CPlusPlus11
1116*67e74705SXin Li                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1117*67e74705SXin Li                       : diag::ext_defaulted_deleted_function)
1118*67e74705SXin Li         << 1 /* deleted */;
1119*67e74705SXin Li       Actions.SetDeclDeleted(Res, KWLoc);
1120*67e74705SXin Li       Delete = true;
1121*67e74705SXin Li     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1122*67e74705SXin Li       Diag(KWLoc, getLangOpts().CPlusPlus11
1123*67e74705SXin Li                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1124*67e74705SXin Li                       : diag::ext_defaulted_deleted_function)
1125*67e74705SXin Li         << 0 /* defaulted */;
1126*67e74705SXin Li       Actions.SetDeclDefaulted(Res, KWLoc);
1127*67e74705SXin Li     } else {
1128*67e74705SXin Li       llvm_unreachable("function definition after = not 'delete' or 'default'");
1129*67e74705SXin Li     }
1130*67e74705SXin Li 
1131*67e74705SXin Li     if (Tok.is(tok::comma)) {
1132*67e74705SXin Li       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1133*67e74705SXin Li         << Delete;
1134*67e74705SXin Li       SkipUntil(tok::semi);
1135*67e74705SXin Li     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1136*67e74705SXin Li                                 Delete ? "delete" : "default")) {
1137*67e74705SXin Li       SkipUntil(tok::semi);
1138*67e74705SXin Li     }
1139*67e74705SXin Li 
1140*67e74705SXin Li     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1141*67e74705SXin Li     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1142*67e74705SXin Li     return Res;
1143*67e74705SXin Li   }
1144*67e74705SXin Li 
1145*67e74705SXin Li   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1146*67e74705SXin Li       trySkippingFunctionBody()) {
1147*67e74705SXin Li     BodyScope.Exit();
1148*67e74705SXin Li     Actions.ActOnSkippedFunctionBody(Res);
1149*67e74705SXin Li     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1150*67e74705SXin Li   }
1151*67e74705SXin Li 
1152*67e74705SXin Li   if (Tok.is(tok::kw_try))
1153*67e74705SXin Li     return ParseFunctionTryBlock(Res, BodyScope);
1154*67e74705SXin Li 
1155*67e74705SXin Li   // If we have a colon, then we're probably parsing a C++
1156*67e74705SXin Li   // ctor-initializer.
1157*67e74705SXin Li   if (Tok.is(tok::colon)) {
1158*67e74705SXin Li     ParseConstructorInitializer(Res);
1159*67e74705SXin Li 
1160*67e74705SXin Li     // Recover from error.
1161*67e74705SXin Li     if (!Tok.is(tok::l_brace)) {
1162*67e74705SXin Li       BodyScope.Exit();
1163*67e74705SXin Li       Actions.ActOnFinishFunctionBody(Res, nullptr);
1164*67e74705SXin Li       return Res;
1165*67e74705SXin Li     }
1166*67e74705SXin Li   } else
1167*67e74705SXin Li     Actions.ActOnDefaultCtorInitializers(Res);
1168*67e74705SXin Li 
1169*67e74705SXin Li   // Late attributes are parsed in the same scope as the function body.
1170*67e74705SXin Li   if (LateParsedAttrs)
1171*67e74705SXin Li     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1172*67e74705SXin Li 
1173*67e74705SXin Li   return ParseFunctionStatementBody(Res, BodyScope);
1174*67e74705SXin Li }
1175*67e74705SXin Li 
SkipFunctionBody()1176*67e74705SXin Li void Parser::SkipFunctionBody() {
1177*67e74705SXin Li   if (Tok.is(tok::equal)) {
1178*67e74705SXin Li     SkipUntil(tok::semi);
1179*67e74705SXin Li     return;
1180*67e74705SXin Li   }
1181*67e74705SXin Li 
1182*67e74705SXin Li   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1183*67e74705SXin Li   if (IsFunctionTryBlock)
1184*67e74705SXin Li     ConsumeToken();
1185*67e74705SXin Li 
1186*67e74705SXin Li   CachedTokens Skipped;
1187*67e74705SXin Li   if (ConsumeAndStoreFunctionPrologue(Skipped))
1188*67e74705SXin Li     SkipMalformedDecl();
1189*67e74705SXin Li   else {
1190*67e74705SXin Li     SkipUntil(tok::r_brace);
1191*67e74705SXin Li     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1192*67e74705SXin Li       SkipUntil(tok::l_brace);
1193*67e74705SXin Li       SkipUntil(tok::r_brace);
1194*67e74705SXin Li     }
1195*67e74705SXin Li   }
1196*67e74705SXin Li }
1197*67e74705SXin Li 
1198*67e74705SXin Li /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1199*67e74705SXin Li /// types for a function with a K&R-style identifier list for arguments.
ParseKNRParamDeclarations(Declarator & D)1200*67e74705SXin Li void Parser::ParseKNRParamDeclarations(Declarator &D) {
1201*67e74705SXin Li   // We know that the top-level of this declarator is a function.
1202*67e74705SXin Li   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1203*67e74705SXin Li 
1204*67e74705SXin Li   // Enter function-declaration scope, limiting any declarators to the
1205*67e74705SXin Li   // function prototype scope, including parameter declarators.
1206*67e74705SXin Li   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1207*67e74705SXin Li                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1208*67e74705SXin Li 
1209*67e74705SXin Li   // Read all the argument declarations.
1210*67e74705SXin Li   while (isDeclarationSpecifier()) {
1211*67e74705SXin Li     SourceLocation DSStart = Tok.getLocation();
1212*67e74705SXin Li 
1213*67e74705SXin Li     // Parse the common declaration-specifiers piece.
1214*67e74705SXin Li     DeclSpec DS(AttrFactory);
1215*67e74705SXin Li     ParseDeclarationSpecifiers(DS);
1216*67e74705SXin Li 
1217*67e74705SXin Li     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1218*67e74705SXin Li     // least one declarator'.
1219*67e74705SXin Li     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1220*67e74705SXin Li     // the declarations though.  It's trivial to ignore them, really hard to do
1221*67e74705SXin Li     // anything else with them.
1222*67e74705SXin Li     if (TryConsumeToken(tok::semi)) {
1223*67e74705SXin Li       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1224*67e74705SXin Li       continue;
1225*67e74705SXin Li     }
1226*67e74705SXin Li 
1227*67e74705SXin Li     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1228*67e74705SXin Li     // than register.
1229*67e74705SXin Li     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1230*67e74705SXin Li         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1231*67e74705SXin Li       Diag(DS.getStorageClassSpecLoc(),
1232*67e74705SXin Li            diag::err_invalid_storage_class_in_func_decl);
1233*67e74705SXin Li       DS.ClearStorageClassSpecs();
1234*67e74705SXin Li     }
1235*67e74705SXin Li     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1236*67e74705SXin Li       Diag(DS.getThreadStorageClassSpecLoc(),
1237*67e74705SXin Li            diag::err_invalid_storage_class_in_func_decl);
1238*67e74705SXin Li       DS.ClearStorageClassSpecs();
1239*67e74705SXin Li     }
1240*67e74705SXin Li 
1241*67e74705SXin Li     // Parse the first declarator attached to this declspec.
1242*67e74705SXin Li     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1243*67e74705SXin Li     ParseDeclarator(ParmDeclarator);
1244*67e74705SXin Li 
1245*67e74705SXin Li     // Handle the full declarator list.
1246*67e74705SXin Li     while (1) {
1247*67e74705SXin Li       // If attributes are present, parse them.
1248*67e74705SXin Li       MaybeParseGNUAttributes(ParmDeclarator);
1249*67e74705SXin Li 
1250*67e74705SXin Li       // Ask the actions module to compute the type for this declarator.
1251*67e74705SXin Li       Decl *Param =
1252*67e74705SXin Li         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1253*67e74705SXin Li 
1254*67e74705SXin Li       if (Param &&
1255*67e74705SXin Li           // A missing identifier has already been diagnosed.
1256*67e74705SXin Li           ParmDeclarator.getIdentifier()) {
1257*67e74705SXin Li 
1258*67e74705SXin Li         // Scan the argument list looking for the correct param to apply this
1259*67e74705SXin Li         // type.
1260*67e74705SXin Li         for (unsigned i = 0; ; ++i) {
1261*67e74705SXin Li           // C99 6.9.1p6: those declarators shall declare only identifiers from
1262*67e74705SXin Li           // the identifier list.
1263*67e74705SXin Li           if (i == FTI.NumParams) {
1264*67e74705SXin Li             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1265*67e74705SXin Li               << ParmDeclarator.getIdentifier();
1266*67e74705SXin Li             break;
1267*67e74705SXin Li           }
1268*67e74705SXin Li 
1269*67e74705SXin Li           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1270*67e74705SXin Li             // Reject redefinitions of parameters.
1271*67e74705SXin Li             if (FTI.Params[i].Param) {
1272*67e74705SXin Li               Diag(ParmDeclarator.getIdentifierLoc(),
1273*67e74705SXin Li                    diag::err_param_redefinition)
1274*67e74705SXin Li                  << ParmDeclarator.getIdentifier();
1275*67e74705SXin Li             } else {
1276*67e74705SXin Li               FTI.Params[i].Param = Param;
1277*67e74705SXin Li             }
1278*67e74705SXin Li             break;
1279*67e74705SXin Li           }
1280*67e74705SXin Li         }
1281*67e74705SXin Li       }
1282*67e74705SXin Li 
1283*67e74705SXin Li       // If we don't have a comma, it is either the end of the list (a ';') or
1284*67e74705SXin Li       // an error, bail out.
1285*67e74705SXin Li       if (Tok.isNot(tok::comma))
1286*67e74705SXin Li         break;
1287*67e74705SXin Li 
1288*67e74705SXin Li       ParmDeclarator.clear();
1289*67e74705SXin Li 
1290*67e74705SXin Li       // Consume the comma.
1291*67e74705SXin Li       ParmDeclarator.setCommaLoc(ConsumeToken());
1292*67e74705SXin Li 
1293*67e74705SXin Li       // Parse the next declarator.
1294*67e74705SXin Li       ParseDeclarator(ParmDeclarator);
1295*67e74705SXin Li     }
1296*67e74705SXin Li 
1297*67e74705SXin Li     // Consume ';' and continue parsing.
1298*67e74705SXin Li     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1299*67e74705SXin Li       continue;
1300*67e74705SXin Li 
1301*67e74705SXin Li     // Otherwise recover by skipping to next semi or mandatory function body.
1302*67e74705SXin Li     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1303*67e74705SXin Li       break;
1304*67e74705SXin Li     TryConsumeToken(tok::semi);
1305*67e74705SXin Li   }
1306*67e74705SXin Li 
1307*67e74705SXin Li   // The actions module must verify that all arguments were declared.
1308*67e74705SXin Li   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1309*67e74705SXin Li }
1310*67e74705SXin Li 
1311*67e74705SXin Li 
1312*67e74705SXin Li /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1313*67e74705SXin Li /// allowed to be a wide string, and is not subject to character translation.
1314*67e74705SXin Li ///
1315*67e74705SXin Li /// [GNU] asm-string-literal:
1316*67e74705SXin Li ///         string-literal
1317*67e74705SXin Li ///
ParseAsmStringLiteral()1318*67e74705SXin Li ExprResult Parser::ParseAsmStringLiteral() {
1319*67e74705SXin Li   if (!isTokenStringLiteral()) {
1320*67e74705SXin Li     Diag(Tok, diag::err_expected_string_literal)
1321*67e74705SXin Li       << /*Source='in...'*/0 << "'asm'";
1322*67e74705SXin Li     return ExprError();
1323*67e74705SXin Li   }
1324*67e74705SXin Li 
1325*67e74705SXin Li   ExprResult AsmString(ParseStringLiteralExpression());
1326*67e74705SXin Li   if (!AsmString.isInvalid()) {
1327*67e74705SXin Li     const auto *SL = cast<StringLiteral>(AsmString.get());
1328*67e74705SXin Li     if (!SL->isAscii()) {
1329*67e74705SXin Li       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1330*67e74705SXin Li         << SL->isWide()
1331*67e74705SXin Li         << SL->getSourceRange();
1332*67e74705SXin Li       return ExprError();
1333*67e74705SXin Li     }
1334*67e74705SXin Li   }
1335*67e74705SXin Li   return AsmString;
1336*67e74705SXin Li }
1337*67e74705SXin Li 
1338*67e74705SXin Li /// ParseSimpleAsm
1339*67e74705SXin Li ///
1340*67e74705SXin Li /// [GNU] simple-asm-expr:
1341*67e74705SXin Li ///         'asm' '(' asm-string-literal ')'
1342*67e74705SXin Li ///
ParseSimpleAsm(SourceLocation * EndLoc)1343*67e74705SXin Li ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1344*67e74705SXin Li   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1345*67e74705SXin Li   SourceLocation Loc = ConsumeToken();
1346*67e74705SXin Li 
1347*67e74705SXin Li   if (Tok.is(tok::kw_volatile)) {
1348*67e74705SXin Li     // Remove from the end of 'asm' to the end of 'volatile'.
1349*67e74705SXin Li     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1350*67e74705SXin Li                              PP.getLocForEndOfToken(Tok.getLocation()));
1351*67e74705SXin Li 
1352*67e74705SXin Li     Diag(Tok, diag::warn_file_asm_volatile)
1353*67e74705SXin Li       << FixItHint::CreateRemoval(RemovalRange);
1354*67e74705SXin Li     ConsumeToken();
1355*67e74705SXin Li   }
1356*67e74705SXin Li 
1357*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
1358*67e74705SXin Li   if (T.consumeOpen()) {
1359*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1360*67e74705SXin Li     return ExprError();
1361*67e74705SXin Li   }
1362*67e74705SXin Li 
1363*67e74705SXin Li   ExprResult Result(ParseAsmStringLiteral());
1364*67e74705SXin Li 
1365*67e74705SXin Li   if (!Result.isInvalid()) {
1366*67e74705SXin Li     // Close the paren and get the location of the end bracket
1367*67e74705SXin Li     T.consumeClose();
1368*67e74705SXin Li     if (EndLoc)
1369*67e74705SXin Li       *EndLoc = T.getCloseLocation();
1370*67e74705SXin Li   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1371*67e74705SXin Li     if (EndLoc)
1372*67e74705SXin Li       *EndLoc = Tok.getLocation();
1373*67e74705SXin Li     ConsumeParen();
1374*67e74705SXin Li   }
1375*67e74705SXin Li 
1376*67e74705SXin Li   return Result;
1377*67e74705SXin Li }
1378*67e74705SXin Li 
1379*67e74705SXin Li /// \brief Get the TemplateIdAnnotation from the token and put it in the
1380*67e74705SXin Li /// cleanup pool so that it gets destroyed when parsing the current top level
1381*67e74705SXin Li /// declaration is finished.
takeTemplateIdAnnotation(const Token & tok)1382*67e74705SXin Li TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1383*67e74705SXin Li   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1384*67e74705SXin Li   TemplateIdAnnotation *
1385*67e74705SXin Li       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1386*67e74705SXin Li   return Id;
1387*67e74705SXin Li }
1388*67e74705SXin Li 
AnnotateScopeToken(CXXScopeSpec & SS,bool IsNewAnnotation)1389*67e74705SXin Li void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1390*67e74705SXin Li   // Push the current token back into the token stream (or revert it if it is
1391*67e74705SXin Li   // cached) and use an annotation scope token for current token.
1392*67e74705SXin Li   if (PP.isBacktrackEnabled())
1393*67e74705SXin Li     PP.RevertCachedTokens(1);
1394*67e74705SXin Li   else
1395*67e74705SXin Li     PP.EnterToken(Tok);
1396*67e74705SXin Li   Tok.setKind(tok::annot_cxxscope);
1397*67e74705SXin Li   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1398*67e74705SXin Li   Tok.setAnnotationRange(SS.getRange());
1399*67e74705SXin Li 
1400*67e74705SXin Li   // In case the tokens were cached, have Preprocessor replace them
1401*67e74705SXin Li   // with the annotation token.  We don't need to do this if we've
1402*67e74705SXin Li   // just reverted back to a prior state.
1403*67e74705SXin Li   if (IsNewAnnotation)
1404*67e74705SXin Li     PP.AnnotateCachedTokens(Tok);
1405*67e74705SXin Li }
1406*67e74705SXin Li 
1407*67e74705SXin Li /// \brief Attempt to classify the name at the current token position. This may
1408*67e74705SXin Li /// form a type, scope or primary expression annotation, or replace the token
1409*67e74705SXin Li /// with a typo-corrected keyword. This is only appropriate when the current
1410*67e74705SXin Li /// name must refer to an entity which has already been declared.
1411*67e74705SXin Li ///
1412*67e74705SXin Li /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1413*67e74705SXin Li ///        and might possibly have a dependent nested name specifier.
1414*67e74705SXin Li /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1415*67e74705SXin Li ///        no typo correction will be performed.
1416*67e74705SXin Li Parser::AnnotatedNameKind
TryAnnotateName(bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC)1417*67e74705SXin Li Parser::TryAnnotateName(bool IsAddressOfOperand,
1418*67e74705SXin Li                         std::unique_ptr<CorrectionCandidateCallback> CCC) {
1419*67e74705SXin Li   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1420*67e74705SXin Li 
1421*67e74705SXin Li   const bool EnteringContext = false;
1422*67e74705SXin Li   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1423*67e74705SXin Li 
1424*67e74705SXin Li   CXXScopeSpec SS;
1425*67e74705SXin Li   if (getLangOpts().CPlusPlus &&
1426*67e74705SXin Li       ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1427*67e74705SXin Li     return ANK_Error;
1428*67e74705SXin Li 
1429*67e74705SXin Li   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1430*67e74705SXin Li     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1431*67e74705SXin Li                                                   !WasScopeAnnotation))
1432*67e74705SXin Li       return ANK_Error;
1433*67e74705SXin Li     return ANK_Unresolved;
1434*67e74705SXin Li   }
1435*67e74705SXin Li 
1436*67e74705SXin Li   IdentifierInfo *Name = Tok.getIdentifierInfo();
1437*67e74705SXin Li   SourceLocation NameLoc = Tok.getLocation();
1438*67e74705SXin Li 
1439*67e74705SXin Li   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1440*67e74705SXin Li   // typo-correct to tentatively-declared identifiers.
1441*67e74705SXin Li   if (isTentativelyDeclared(Name)) {
1442*67e74705SXin Li     // Identifier has been tentatively declared, and thus cannot be resolved as
1443*67e74705SXin Li     // an expression. Fall back to annotating it as a type.
1444*67e74705SXin Li     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1445*67e74705SXin Li                                                   !WasScopeAnnotation))
1446*67e74705SXin Li       return ANK_Error;
1447*67e74705SXin Li     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1448*67e74705SXin Li   }
1449*67e74705SXin Li 
1450*67e74705SXin Li   Token Next = NextToken();
1451*67e74705SXin Li 
1452*67e74705SXin Li   // Look up and classify the identifier. We don't perform any typo-correction
1453*67e74705SXin Li   // after a scope specifier, because in general we can't recover from typos
1454*67e74705SXin Li   // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
1455*67e74705SXin Li   // jump back into scope specifier parsing).
1456*67e74705SXin Li   Sema::NameClassification Classification = Actions.ClassifyName(
1457*67e74705SXin Li       getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1458*67e74705SXin Li       SS.isEmpty() ? std::move(CCC) : nullptr);
1459*67e74705SXin Li 
1460*67e74705SXin Li   switch (Classification.getKind()) {
1461*67e74705SXin Li   case Sema::NC_Error:
1462*67e74705SXin Li     return ANK_Error;
1463*67e74705SXin Li 
1464*67e74705SXin Li   case Sema::NC_Keyword:
1465*67e74705SXin Li     // The identifier was typo-corrected to a keyword.
1466*67e74705SXin Li     Tok.setIdentifierInfo(Name);
1467*67e74705SXin Li     Tok.setKind(Name->getTokenID());
1468*67e74705SXin Li     PP.TypoCorrectToken(Tok);
1469*67e74705SXin Li     if (SS.isNotEmpty())
1470*67e74705SXin Li       AnnotateScopeToken(SS, !WasScopeAnnotation);
1471*67e74705SXin Li     // We've "annotated" this as a keyword.
1472*67e74705SXin Li     return ANK_Success;
1473*67e74705SXin Li 
1474*67e74705SXin Li   case Sema::NC_Unknown:
1475*67e74705SXin Li     // It's not something we know about. Leave it unannotated.
1476*67e74705SXin Li     break;
1477*67e74705SXin Li 
1478*67e74705SXin Li   case Sema::NC_Type: {
1479*67e74705SXin Li     SourceLocation BeginLoc = NameLoc;
1480*67e74705SXin Li     if (SS.isNotEmpty())
1481*67e74705SXin Li       BeginLoc = SS.getBeginLoc();
1482*67e74705SXin Li 
1483*67e74705SXin Li     /// An Objective-C object type followed by '<' is a specialization of
1484*67e74705SXin Li     /// a parameterized class type or a protocol-qualified type.
1485*67e74705SXin Li     ParsedType Ty = Classification.getType();
1486*67e74705SXin Li     if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1487*67e74705SXin Li         (Ty.get()->isObjCObjectType() ||
1488*67e74705SXin Li          Ty.get()->isObjCObjectPointerType())) {
1489*67e74705SXin Li       // Consume the name.
1490*67e74705SXin Li       SourceLocation IdentifierLoc = ConsumeToken();
1491*67e74705SXin Li       SourceLocation NewEndLoc;
1492*67e74705SXin Li       TypeResult NewType
1493*67e74705SXin Li           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1494*67e74705SXin Li                                                    /*consumeLastToken=*/false,
1495*67e74705SXin Li                                                    NewEndLoc);
1496*67e74705SXin Li       if (NewType.isUsable())
1497*67e74705SXin Li         Ty = NewType.get();
1498*67e74705SXin Li     }
1499*67e74705SXin Li 
1500*67e74705SXin Li     Tok.setKind(tok::annot_typename);
1501*67e74705SXin Li     setTypeAnnotation(Tok, Ty);
1502*67e74705SXin Li     Tok.setAnnotationEndLoc(Tok.getLocation());
1503*67e74705SXin Li     Tok.setLocation(BeginLoc);
1504*67e74705SXin Li     PP.AnnotateCachedTokens(Tok);
1505*67e74705SXin Li     return ANK_Success;
1506*67e74705SXin Li   }
1507*67e74705SXin Li 
1508*67e74705SXin Li   case Sema::NC_Expression:
1509*67e74705SXin Li     Tok.setKind(tok::annot_primary_expr);
1510*67e74705SXin Li     setExprAnnotation(Tok, Classification.getExpression());
1511*67e74705SXin Li     Tok.setAnnotationEndLoc(NameLoc);
1512*67e74705SXin Li     if (SS.isNotEmpty())
1513*67e74705SXin Li       Tok.setLocation(SS.getBeginLoc());
1514*67e74705SXin Li     PP.AnnotateCachedTokens(Tok);
1515*67e74705SXin Li     return ANK_Success;
1516*67e74705SXin Li 
1517*67e74705SXin Li   case Sema::NC_TypeTemplate:
1518*67e74705SXin Li     if (Next.isNot(tok::less)) {
1519*67e74705SXin Li       // This may be a type template being used as a template template argument.
1520*67e74705SXin Li       if (SS.isNotEmpty())
1521*67e74705SXin Li         AnnotateScopeToken(SS, !WasScopeAnnotation);
1522*67e74705SXin Li       return ANK_TemplateName;
1523*67e74705SXin Li     }
1524*67e74705SXin Li     // Fall through.
1525*67e74705SXin Li   case Sema::NC_VarTemplate:
1526*67e74705SXin Li   case Sema::NC_FunctionTemplate: {
1527*67e74705SXin Li     // We have a type, variable or function template followed by '<'.
1528*67e74705SXin Li     ConsumeToken();
1529*67e74705SXin Li     UnqualifiedId Id;
1530*67e74705SXin Li     Id.setIdentifier(Name, NameLoc);
1531*67e74705SXin Li     if (AnnotateTemplateIdToken(
1532*67e74705SXin Li             TemplateTy::make(Classification.getTemplateName()),
1533*67e74705SXin Li             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1534*67e74705SXin Li       return ANK_Error;
1535*67e74705SXin Li     return ANK_Success;
1536*67e74705SXin Li   }
1537*67e74705SXin Li 
1538*67e74705SXin Li   case Sema::NC_NestedNameSpecifier:
1539*67e74705SXin Li     llvm_unreachable("already parsed nested name specifier");
1540*67e74705SXin Li   }
1541*67e74705SXin Li 
1542*67e74705SXin Li   // Unable to classify the name, but maybe we can annotate a scope specifier.
1543*67e74705SXin Li   if (SS.isNotEmpty())
1544*67e74705SXin Li     AnnotateScopeToken(SS, !WasScopeAnnotation);
1545*67e74705SXin Li   return ANK_Unresolved;
1546*67e74705SXin Li }
1547*67e74705SXin Li 
TryKeywordIdentFallback(bool DisableKeyword)1548*67e74705SXin Li bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1549*67e74705SXin Li   assert(Tok.isNot(tok::identifier));
1550*67e74705SXin Li   Diag(Tok, diag::ext_keyword_as_ident)
1551*67e74705SXin Li     << PP.getSpelling(Tok)
1552*67e74705SXin Li     << DisableKeyword;
1553*67e74705SXin Li   if (DisableKeyword)
1554*67e74705SXin Li     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1555*67e74705SXin Li   Tok.setKind(tok::identifier);
1556*67e74705SXin Li   return true;
1557*67e74705SXin Li }
1558*67e74705SXin Li 
1559*67e74705SXin Li /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1560*67e74705SXin Li /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1561*67e74705SXin Li /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1562*67e74705SXin Li /// with a single annotation token representing the typename or C++ scope
1563*67e74705SXin Li /// respectively.
1564*67e74705SXin Li /// This simplifies handling of C++ scope specifiers and allows efficient
1565*67e74705SXin Li /// backtracking without the need to re-parse and resolve nested-names and
1566*67e74705SXin Li /// typenames.
1567*67e74705SXin Li /// It will mainly be called when we expect to treat identifiers as typenames
1568*67e74705SXin Li /// (if they are typenames). For example, in C we do not expect identifiers
1569*67e74705SXin Li /// inside expressions to be treated as typenames so it will not be called
1570*67e74705SXin Li /// for expressions in C.
1571*67e74705SXin Li /// The benefit for C/ObjC is that a typename will be annotated and
1572*67e74705SXin Li /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1573*67e74705SXin Li /// will not be called twice, once to check whether we have a declaration
1574*67e74705SXin Li /// specifier, and another one to get the actual type inside
1575*67e74705SXin Li /// ParseDeclarationSpecifiers).
1576*67e74705SXin Li ///
1577*67e74705SXin Li /// This returns true if an error occurred.
1578*67e74705SXin Li ///
1579*67e74705SXin Li /// Note that this routine emits an error if you call it with ::new or ::delete
1580*67e74705SXin Li /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateTypeOrScopeToken(bool EnteringContext,bool NeedType)1581*67e74705SXin Li bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1582*67e74705SXin Li   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1583*67e74705SXin Li           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1584*67e74705SXin Li           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1585*67e74705SXin Li           Tok.is(tok::kw___super)) &&
1586*67e74705SXin Li          "Cannot be a type or scope token!");
1587*67e74705SXin Li 
1588*67e74705SXin Li   if (Tok.is(tok::kw_typename)) {
1589*67e74705SXin Li     // MSVC lets you do stuff like:
1590*67e74705SXin Li     //   typename typedef T_::D D;
1591*67e74705SXin Li     //
1592*67e74705SXin Li     // We will consume the typedef token here and put it back after we have
1593*67e74705SXin Li     // parsed the first identifier, transforming it into something more like:
1594*67e74705SXin Li     //   typename T_::D typedef D;
1595*67e74705SXin Li     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1596*67e74705SXin Li       Token TypedefToken;
1597*67e74705SXin Li       PP.Lex(TypedefToken);
1598*67e74705SXin Li       bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
1599*67e74705SXin Li       PP.EnterToken(Tok);
1600*67e74705SXin Li       Tok = TypedefToken;
1601*67e74705SXin Li       if (!Result)
1602*67e74705SXin Li         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1603*67e74705SXin Li       return Result;
1604*67e74705SXin Li     }
1605*67e74705SXin Li 
1606*67e74705SXin Li     // Parse a C++ typename-specifier, e.g., "typename T::type".
1607*67e74705SXin Li     //
1608*67e74705SXin Li     //   typename-specifier:
1609*67e74705SXin Li     //     'typename' '::' [opt] nested-name-specifier identifier
1610*67e74705SXin Li     //     'typename' '::' [opt] nested-name-specifier template [opt]
1611*67e74705SXin Li     //            simple-template-id
1612*67e74705SXin Li     SourceLocation TypenameLoc = ConsumeToken();
1613*67e74705SXin Li     CXXScopeSpec SS;
1614*67e74705SXin Li     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1615*67e74705SXin Li                                        /*EnteringContext=*/false, nullptr,
1616*67e74705SXin Li                                        /*IsTypename*/ true))
1617*67e74705SXin Li       return true;
1618*67e74705SXin Li     if (!SS.isSet()) {
1619*67e74705SXin Li       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1620*67e74705SXin Li           Tok.is(tok::annot_decltype)) {
1621*67e74705SXin Li         // Attempt to recover by skipping the invalid 'typename'
1622*67e74705SXin Li         if (Tok.is(tok::annot_decltype) ||
1623*67e74705SXin Li             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1624*67e74705SXin Li              Tok.isAnnotation())) {
1625*67e74705SXin Li           unsigned DiagID = diag::err_expected_qualified_after_typename;
1626*67e74705SXin Li           // MS compatibility: MSVC permits using known types with typename.
1627*67e74705SXin Li           // e.g. "typedef typename T* pointer_type"
1628*67e74705SXin Li           if (getLangOpts().MicrosoftExt)
1629*67e74705SXin Li             DiagID = diag::warn_expected_qualified_after_typename;
1630*67e74705SXin Li           Diag(Tok.getLocation(), DiagID);
1631*67e74705SXin Li           return false;
1632*67e74705SXin Li         }
1633*67e74705SXin Li       }
1634*67e74705SXin Li 
1635*67e74705SXin Li       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1636*67e74705SXin Li       return true;
1637*67e74705SXin Li     }
1638*67e74705SXin Li 
1639*67e74705SXin Li     TypeResult Ty;
1640*67e74705SXin Li     if (Tok.is(tok::identifier)) {
1641*67e74705SXin Li       // FIXME: check whether the next token is '<', first!
1642*67e74705SXin Li       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1643*67e74705SXin Li                                      *Tok.getIdentifierInfo(),
1644*67e74705SXin Li                                      Tok.getLocation());
1645*67e74705SXin Li     } else if (Tok.is(tok::annot_template_id)) {
1646*67e74705SXin Li       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1647*67e74705SXin Li       if (TemplateId->Kind != TNK_Type_template &&
1648*67e74705SXin Li           TemplateId->Kind != TNK_Dependent_template_name) {
1649*67e74705SXin Li         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1650*67e74705SXin Li           << Tok.getAnnotationRange();
1651*67e74705SXin Li         return true;
1652*67e74705SXin Li       }
1653*67e74705SXin Li 
1654*67e74705SXin Li       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1655*67e74705SXin Li                                          TemplateId->NumArgs);
1656*67e74705SXin Li 
1657*67e74705SXin Li       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1658*67e74705SXin Li                                      TemplateId->TemplateKWLoc,
1659*67e74705SXin Li                                      TemplateId->Template,
1660*67e74705SXin Li                                      TemplateId->TemplateNameLoc,
1661*67e74705SXin Li                                      TemplateId->LAngleLoc,
1662*67e74705SXin Li                                      TemplateArgsPtr,
1663*67e74705SXin Li                                      TemplateId->RAngleLoc);
1664*67e74705SXin Li     } else {
1665*67e74705SXin Li       Diag(Tok, diag::err_expected_type_name_after_typename)
1666*67e74705SXin Li         << SS.getRange();
1667*67e74705SXin Li       return true;
1668*67e74705SXin Li     }
1669*67e74705SXin Li 
1670*67e74705SXin Li     SourceLocation EndLoc = Tok.getLastLoc();
1671*67e74705SXin Li     Tok.setKind(tok::annot_typename);
1672*67e74705SXin Li     setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1673*67e74705SXin Li     Tok.setAnnotationEndLoc(EndLoc);
1674*67e74705SXin Li     Tok.setLocation(TypenameLoc);
1675*67e74705SXin Li     PP.AnnotateCachedTokens(Tok);
1676*67e74705SXin Li     return false;
1677*67e74705SXin Li   }
1678*67e74705SXin Li 
1679*67e74705SXin Li   // Remembers whether the token was originally a scope annotation.
1680*67e74705SXin Li   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1681*67e74705SXin Li 
1682*67e74705SXin Li   CXXScopeSpec SS;
1683*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1684*67e74705SXin Li     if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1685*67e74705SXin Li       return true;
1686*67e74705SXin Li 
1687*67e74705SXin Li   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1688*67e74705SXin Li                                                    SS, !WasScopeAnnotation);
1689*67e74705SXin Li }
1690*67e74705SXin Li 
1691*67e74705SXin Li /// \brief Try to annotate a type or scope token, having already parsed an
1692*67e74705SXin Li /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1693*67e74705SXin Li /// specifier was extracted from an existing tok::annot_cxxscope annotation.
TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,bool NeedType,CXXScopeSpec & SS,bool IsNewScope)1694*67e74705SXin Li bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1695*67e74705SXin Li                                                        bool NeedType,
1696*67e74705SXin Li                                                        CXXScopeSpec &SS,
1697*67e74705SXin Li                                                        bool IsNewScope) {
1698*67e74705SXin Li   if (Tok.is(tok::identifier)) {
1699*67e74705SXin Li     IdentifierInfo *CorrectedII = nullptr;
1700*67e74705SXin Li     // Determine whether the identifier is a type name.
1701*67e74705SXin Li     if (ParsedType Ty = Actions.getTypeName(
1702*67e74705SXin Li             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1703*67e74705SXin Li             false, NextToken().is(tok::period), nullptr,
1704*67e74705SXin Li             /*IsCtorOrDtorName=*/false,
1705*67e74705SXin Li             /*NonTrivialTypeSourceInfo*/ true,
1706*67e74705SXin Li             NeedType ? &CorrectedII : nullptr)) {
1707*67e74705SXin Li       // A FixIt was applied as a result of typo correction
1708*67e74705SXin Li       if (CorrectedII)
1709*67e74705SXin Li         Tok.setIdentifierInfo(CorrectedII);
1710*67e74705SXin Li 
1711*67e74705SXin Li       SourceLocation BeginLoc = Tok.getLocation();
1712*67e74705SXin Li       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1713*67e74705SXin Li         BeginLoc = SS.getBeginLoc();
1714*67e74705SXin Li 
1715*67e74705SXin Li       /// An Objective-C object type followed by '<' is a specialization of
1716*67e74705SXin Li       /// a parameterized class type or a protocol-qualified type.
1717*67e74705SXin Li       if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1718*67e74705SXin Li           (Ty.get()->isObjCObjectType() ||
1719*67e74705SXin Li            Ty.get()->isObjCObjectPointerType())) {
1720*67e74705SXin Li         // Consume the name.
1721*67e74705SXin Li         SourceLocation IdentifierLoc = ConsumeToken();
1722*67e74705SXin Li         SourceLocation NewEndLoc;
1723*67e74705SXin Li         TypeResult NewType
1724*67e74705SXin Li           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1725*67e74705SXin Li                                                    /*consumeLastToken=*/false,
1726*67e74705SXin Li                                                    NewEndLoc);
1727*67e74705SXin Li         if (NewType.isUsable())
1728*67e74705SXin Li           Ty = NewType.get();
1729*67e74705SXin Li       }
1730*67e74705SXin Li 
1731*67e74705SXin Li       // This is a typename. Replace the current token in-place with an
1732*67e74705SXin Li       // annotation type token.
1733*67e74705SXin Li       Tok.setKind(tok::annot_typename);
1734*67e74705SXin Li       setTypeAnnotation(Tok, Ty);
1735*67e74705SXin Li       Tok.setAnnotationEndLoc(Tok.getLocation());
1736*67e74705SXin Li       Tok.setLocation(BeginLoc);
1737*67e74705SXin Li 
1738*67e74705SXin Li       // In case the tokens were cached, have Preprocessor replace
1739*67e74705SXin Li       // them with the annotation token.
1740*67e74705SXin Li       PP.AnnotateCachedTokens(Tok);
1741*67e74705SXin Li       return false;
1742*67e74705SXin Li     }
1743*67e74705SXin Li 
1744*67e74705SXin Li     if (!getLangOpts().CPlusPlus) {
1745*67e74705SXin Li       // If we're in C, we can't have :: tokens at all (the lexer won't return
1746*67e74705SXin Li       // them).  If the identifier is not a type, then it can't be scope either,
1747*67e74705SXin Li       // just early exit.
1748*67e74705SXin Li       return false;
1749*67e74705SXin Li     }
1750*67e74705SXin Li 
1751*67e74705SXin Li     // If this is a template-id, annotate with a template-id or type token.
1752*67e74705SXin Li     if (NextToken().is(tok::less)) {
1753*67e74705SXin Li       TemplateTy Template;
1754*67e74705SXin Li       UnqualifiedId TemplateName;
1755*67e74705SXin Li       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1756*67e74705SXin Li       bool MemberOfUnknownSpecialization;
1757*67e74705SXin Li       if (TemplateNameKind TNK =
1758*67e74705SXin Li               Actions.isTemplateName(getCurScope(), SS,
1759*67e74705SXin Li                                      /*hasTemplateKeyword=*/false, TemplateName,
1760*67e74705SXin Li                                      /*ObjectType=*/nullptr, EnteringContext,
1761*67e74705SXin Li                                      Template, MemberOfUnknownSpecialization)) {
1762*67e74705SXin Li         // Consume the identifier.
1763*67e74705SXin Li         ConsumeToken();
1764*67e74705SXin Li         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1765*67e74705SXin Li                                     TemplateName)) {
1766*67e74705SXin Li           // If an unrecoverable error occurred, we need to return true here,
1767*67e74705SXin Li           // because the token stream is in a damaged state.  We may not return
1768*67e74705SXin Li           // a valid identifier.
1769*67e74705SXin Li           return true;
1770*67e74705SXin Li         }
1771*67e74705SXin Li       }
1772*67e74705SXin Li     }
1773*67e74705SXin Li 
1774*67e74705SXin Li     // The current token, which is either an identifier or a
1775*67e74705SXin Li     // template-id, is not part of the annotation. Fall through to
1776*67e74705SXin Li     // push that token back into the stream and complete the C++ scope
1777*67e74705SXin Li     // specifier annotation.
1778*67e74705SXin Li   }
1779*67e74705SXin Li 
1780*67e74705SXin Li   if (Tok.is(tok::annot_template_id)) {
1781*67e74705SXin Li     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1782*67e74705SXin Li     if (TemplateId->Kind == TNK_Type_template) {
1783*67e74705SXin Li       // A template-id that refers to a type was parsed into a
1784*67e74705SXin Li       // template-id annotation in a context where we weren't allowed
1785*67e74705SXin Li       // to produce a type annotation token. Update the template-id
1786*67e74705SXin Li       // annotation token to a type annotation token now.
1787*67e74705SXin Li       AnnotateTemplateIdTokenAsType();
1788*67e74705SXin Li       return false;
1789*67e74705SXin Li     }
1790*67e74705SXin Li   }
1791*67e74705SXin Li 
1792*67e74705SXin Li   if (SS.isEmpty())
1793*67e74705SXin Li     return false;
1794*67e74705SXin Li 
1795*67e74705SXin Li   // A C++ scope specifier that isn't followed by a typename.
1796*67e74705SXin Li   AnnotateScopeToken(SS, IsNewScope);
1797*67e74705SXin Li   return false;
1798*67e74705SXin Li }
1799*67e74705SXin Li 
1800*67e74705SXin Li /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1801*67e74705SXin Li /// annotates C++ scope specifiers and template-ids.  This returns
1802*67e74705SXin Li /// true if there was an error that could not be recovered from.
1803*67e74705SXin Li ///
1804*67e74705SXin Li /// Note that this routine emits an error if you call it with ::new or ::delete
1805*67e74705SXin Li /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateCXXScopeToken(bool EnteringContext)1806*67e74705SXin Li bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1807*67e74705SXin Li   assert(getLangOpts().CPlusPlus &&
1808*67e74705SXin Li          "Call sites of this function should be guarded by checking for C++");
1809*67e74705SXin Li   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1810*67e74705SXin Li           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1811*67e74705SXin Li           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1812*67e74705SXin Li          "Cannot be a type or scope token!");
1813*67e74705SXin Li 
1814*67e74705SXin Li   CXXScopeSpec SS;
1815*67e74705SXin Li   if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1816*67e74705SXin Li     return true;
1817*67e74705SXin Li   if (SS.isEmpty())
1818*67e74705SXin Li     return false;
1819*67e74705SXin Li 
1820*67e74705SXin Li   AnnotateScopeToken(SS, true);
1821*67e74705SXin Li   return false;
1822*67e74705SXin Li }
1823*67e74705SXin Li 
isTokenEqualOrEqualTypo()1824*67e74705SXin Li bool Parser::isTokenEqualOrEqualTypo() {
1825*67e74705SXin Li   tok::TokenKind Kind = Tok.getKind();
1826*67e74705SXin Li   switch (Kind) {
1827*67e74705SXin Li   default:
1828*67e74705SXin Li     return false;
1829*67e74705SXin Li   case tok::ampequal:            // &=
1830*67e74705SXin Li   case tok::starequal:           // *=
1831*67e74705SXin Li   case tok::plusequal:           // +=
1832*67e74705SXin Li   case tok::minusequal:          // -=
1833*67e74705SXin Li   case tok::exclaimequal:        // !=
1834*67e74705SXin Li   case tok::slashequal:          // /=
1835*67e74705SXin Li   case tok::percentequal:        // %=
1836*67e74705SXin Li   case tok::lessequal:           // <=
1837*67e74705SXin Li   case tok::lesslessequal:       // <<=
1838*67e74705SXin Li   case tok::greaterequal:        // >=
1839*67e74705SXin Li   case tok::greatergreaterequal: // >>=
1840*67e74705SXin Li   case tok::caretequal:          // ^=
1841*67e74705SXin Li   case tok::pipeequal:           // |=
1842*67e74705SXin Li   case tok::equalequal:          // ==
1843*67e74705SXin Li     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1844*67e74705SXin Li         << Kind
1845*67e74705SXin Li         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1846*67e74705SXin Li   case tok::equal:
1847*67e74705SXin Li     return true;
1848*67e74705SXin Li   }
1849*67e74705SXin Li }
1850*67e74705SXin Li 
handleUnexpectedCodeCompletionToken()1851*67e74705SXin Li SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1852*67e74705SXin Li   assert(Tok.is(tok::code_completion));
1853*67e74705SXin Li   PrevTokLocation = Tok.getLocation();
1854*67e74705SXin Li 
1855*67e74705SXin Li   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1856*67e74705SXin Li     if (S->getFlags() & Scope::FnScope) {
1857*67e74705SXin Li       Actions.CodeCompleteOrdinaryName(getCurScope(),
1858*67e74705SXin Li                                        Sema::PCC_RecoveryInFunction);
1859*67e74705SXin Li       cutOffParsing();
1860*67e74705SXin Li       return PrevTokLocation;
1861*67e74705SXin Li     }
1862*67e74705SXin Li 
1863*67e74705SXin Li     if (S->getFlags() & Scope::ClassScope) {
1864*67e74705SXin Li       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1865*67e74705SXin Li       cutOffParsing();
1866*67e74705SXin Li       return PrevTokLocation;
1867*67e74705SXin Li     }
1868*67e74705SXin Li   }
1869*67e74705SXin Li 
1870*67e74705SXin Li   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1871*67e74705SXin Li   cutOffParsing();
1872*67e74705SXin Li   return PrevTokLocation;
1873*67e74705SXin Li }
1874*67e74705SXin Li 
1875*67e74705SXin Li // Code-completion pass-through functions
1876*67e74705SXin Li 
CodeCompleteDirective(bool InConditional)1877*67e74705SXin Li void Parser::CodeCompleteDirective(bool InConditional) {
1878*67e74705SXin Li   Actions.CodeCompletePreprocessorDirective(InConditional);
1879*67e74705SXin Li }
1880*67e74705SXin Li 
CodeCompleteInConditionalExclusion()1881*67e74705SXin Li void Parser::CodeCompleteInConditionalExclusion() {
1882*67e74705SXin Li   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1883*67e74705SXin Li }
1884*67e74705SXin Li 
CodeCompleteMacroName(bool IsDefinition)1885*67e74705SXin Li void Parser::CodeCompleteMacroName(bool IsDefinition) {
1886*67e74705SXin Li   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1887*67e74705SXin Li }
1888*67e74705SXin Li 
CodeCompletePreprocessorExpression()1889*67e74705SXin Li void Parser::CodeCompletePreprocessorExpression() {
1890*67e74705SXin Li   Actions.CodeCompletePreprocessorExpression();
1891*67e74705SXin Li }
1892*67e74705SXin Li 
CodeCompleteMacroArgument(IdentifierInfo * Macro,MacroInfo * MacroInfo,unsigned ArgumentIndex)1893*67e74705SXin Li void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1894*67e74705SXin Li                                        MacroInfo *MacroInfo,
1895*67e74705SXin Li                                        unsigned ArgumentIndex) {
1896*67e74705SXin Li   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1897*67e74705SXin Li                                                 ArgumentIndex);
1898*67e74705SXin Li }
1899*67e74705SXin Li 
CodeCompleteNaturalLanguage()1900*67e74705SXin Li void Parser::CodeCompleteNaturalLanguage() {
1901*67e74705SXin Li   Actions.CodeCompleteNaturalLanguage();
1902*67e74705SXin Li }
1903*67e74705SXin Li 
ParseMicrosoftIfExistsCondition(IfExistsCondition & Result)1904*67e74705SXin Li bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1905*67e74705SXin Li   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1906*67e74705SXin Li          "Expected '__if_exists' or '__if_not_exists'");
1907*67e74705SXin Li   Result.IsIfExists = Tok.is(tok::kw___if_exists);
1908*67e74705SXin Li   Result.KeywordLoc = ConsumeToken();
1909*67e74705SXin Li 
1910*67e74705SXin Li   BalancedDelimiterTracker T(*this, tok::l_paren);
1911*67e74705SXin Li   if (T.consumeOpen()) {
1912*67e74705SXin Li     Diag(Tok, diag::err_expected_lparen_after)
1913*67e74705SXin Li       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1914*67e74705SXin Li     return true;
1915*67e74705SXin Li   }
1916*67e74705SXin Li 
1917*67e74705SXin Li   // Parse nested-name-specifier.
1918*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1919*67e74705SXin Li     ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
1920*67e74705SXin Li                                    /*EnteringContext=*/false);
1921*67e74705SXin Li 
1922*67e74705SXin Li   // Check nested-name specifier.
1923*67e74705SXin Li   if (Result.SS.isInvalid()) {
1924*67e74705SXin Li     T.skipToEnd();
1925*67e74705SXin Li     return true;
1926*67e74705SXin Li   }
1927*67e74705SXin Li 
1928*67e74705SXin Li   // Parse the unqualified-id.
1929*67e74705SXin Li   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1930*67e74705SXin Li   if (ParseUnqualifiedId(Result.SS, false, true, true, nullptr, TemplateKWLoc,
1931*67e74705SXin Li                          Result.Name)) {
1932*67e74705SXin Li     T.skipToEnd();
1933*67e74705SXin Li     return true;
1934*67e74705SXin Li   }
1935*67e74705SXin Li 
1936*67e74705SXin Li   if (T.consumeClose())
1937*67e74705SXin Li     return true;
1938*67e74705SXin Li 
1939*67e74705SXin Li   // Check if the symbol exists.
1940*67e74705SXin Li   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1941*67e74705SXin Li                                                Result.IsIfExists, Result.SS,
1942*67e74705SXin Li                                                Result.Name)) {
1943*67e74705SXin Li   case Sema::IER_Exists:
1944*67e74705SXin Li     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1945*67e74705SXin Li     break;
1946*67e74705SXin Li 
1947*67e74705SXin Li   case Sema::IER_DoesNotExist:
1948*67e74705SXin Li     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1949*67e74705SXin Li     break;
1950*67e74705SXin Li 
1951*67e74705SXin Li   case Sema::IER_Dependent:
1952*67e74705SXin Li     Result.Behavior = IEB_Dependent;
1953*67e74705SXin Li     break;
1954*67e74705SXin Li 
1955*67e74705SXin Li   case Sema::IER_Error:
1956*67e74705SXin Li     return true;
1957*67e74705SXin Li   }
1958*67e74705SXin Li 
1959*67e74705SXin Li   return false;
1960*67e74705SXin Li }
1961*67e74705SXin Li 
ParseMicrosoftIfExistsExternalDeclaration()1962*67e74705SXin Li void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1963*67e74705SXin Li   IfExistsCondition Result;
1964*67e74705SXin Li   if (ParseMicrosoftIfExistsCondition(Result))
1965*67e74705SXin Li     return;
1966*67e74705SXin Li 
1967*67e74705SXin Li   BalancedDelimiterTracker Braces(*this, tok::l_brace);
1968*67e74705SXin Li   if (Braces.consumeOpen()) {
1969*67e74705SXin Li     Diag(Tok, diag::err_expected) << tok::l_brace;
1970*67e74705SXin Li     return;
1971*67e74705SXin Li   }
1972*67e74705SXin Li 
1973*67e74705SXin Li   switch (Result.Behavior) {
1974*67e74705SXin Li   case IEB_Parse:
1975*67e74705SXin Li     // Parse declarations below.
1976*67e74705SXin Li     break;
1977*67e74705SXin Li 
1978*67e74705SXin Li   case IEB_Dependent:
1979*67e74705SXin Li     llvm_unreachable("Cannot have a dependent external declaration");
1980*67e74705SXin Li 
1981*67e74705SXin Li   case IEB_Skip:
1982*67e74705SXin Li     Braces.skipToEnd();
1983*67e74705SXin Li     return;
1984*67e74705SXin Li   }
1985*67e74705SXin Li 
1986*67e74705SXin Li   // Parse the declarations.
1987*67e74705SXin Li   // FIXME: Support module import within __if_exists?
1988*67e74705SXin Li   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1989*67e74705SXin Li     ParsedAttributesWithRange attrs(AttrFactory);
1990*67e74705SXin Li     MaybeParseCXX11Attributes(attrs);
1991*67e74705SXin Li     MaybeParseMicrosoftAttributes(attrs);
1992*67e74705SXin Li     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1993*67e74705SXin Li     if (Result && !getCurScope()->getParent())
1994*67e74705SXin Li       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1995*67e74705SXin Li   }
1996*67e74705SXin Li   Braces.consumeClose();
1997*67e74705SXin Li }
1998*67e74705SXin Li 
ParseModuleImport(SourceLocation AtLoc)1999*67e74705SXin Li Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
2000*67e74705SXin Li   assert(Tok.isObjCAtKeyword(tok::objc_import) &&
2001*67e74705SXin Li          "Improper start to module import");
2002*67e74705SXin Li   SourceLocation ImportLoc = ConsumeToken();
2003*67e74705SXin Li 
2004*67e74705SXin Li   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2005*67e74705SXin Li 
2006*67e74705SXin Li   // Parse the module path.
2007*67e74705SXin Li   do {
2008*67e74705SXin Li     if (!Tok.is(tok::identifier)) {
2009*67e74705SXin Li       if (Tok.is(tok::code_completion)) {
2010*67e74705SXin Li         Actions.CodeCompleteModuleImport(ImportLoc, Path);
2011*67e74705SXin Li         cutOffParsing();
2012*67e74705SXin Li         return nullptr;
2013*67e74705SXin Li       }
2014*67e74705SXin Li 
2015*67e74705SXin Li       Diag(Tok, diag::err_module_expected_ident);
2016*67e74705SXin Li       SkipUntil(tok::semi);
2017*67e74705SXin Li       return nullptr;
2018*67e74705SXin Li     }
2019*67e74705SXin Li 
2020*67e74705SXin Li     // Record this part of the module path.
2021*67e74705SXin Li     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2022*67e74705SXin Li     ConsumeToken();
2023*67e74705SXin Li 
2024*67e74705SXin Li     if (Tok.is(tok::period)) {
2025*67e74705SXin Li       ConsumeToken();
2026*67e74705SXin Li       continue;
2027*67e74705SXin Li     }
2028*67e74705SXin Li 
2029*67e74705SXin Li     break;
2030*67e74705SXin Li   } while (true);
2031*67e74705SXin Li 
2032*67e74705SXin Li   if (PP.hadModuleLoaderFatalFailure()) {
2033*67e74705SXin Li     // With a fatal failure in the module loader, we abort parsing.
2034*67e74705SXin Li     cutOffParsing();
2035*67e74705SXin Li     return nullptr;
2036*67e74705SXin Li   }
2037*67e74705SXin Li 
2038*67e74705SXin Li   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
2039*67e74705SXin Li   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2040*67e74705SXin Li   if (Import.isInvalid())
2041*67e74705SXin Li     return nullptr;
2042*67e74705SXin Li 
2043*67e74705SXin Li   return Actions.ConvertDeclToDeclGroup(Import.get());
2044*67e74705SXin Li }
2045*67e74705SXin Li 
2046*67e74705SXin Li /// \brief Try recover parser when module annotation appears where it must not
2047*67e74705SXin Li /// be found.
2048*67e74705SXin Li /// \returns false if the recover was successful and parsing may be continued, or
2049*67e74705SXin Li /// true if parser must bail out to top level and handle the token there.
parseMisplacedModuleImport()2050*67e74705SXin Li bool Parser::parseMisplacedModuleImport() {
2051*67e74705SXin Li   while (true) {
2052*67e74705SXin Li     switch (Tok.getKind()) {
2053*67e74705SXin Li     case tok::annot_module_end:
2054*67e74705SXin Li       // Inform caller that recovery failed, the error must be handled at upper
2055*67e74705SXin Li       // level.
2056*67e74705SXin Li       return true;
2057*67e74705SXin Li     case tok::annot_module_begin:
2058*67e74705SXin Li       Actions.diagnoseMisplacedModuleImport(reinterpret_cast<Module *>(
2059*67e74705SXin Li         Tok.getAnnotationValue()), Tok.getLocation());
2060*67e74705SXin Li       return true;
2061*67e74705SXin Li     case tok::annot_module_include:
2062*67e74705SXin Li       // Module import found where it should not be, for instance, inside a
2063*67e74705SXin Li       // namespace. Recover by importing the module.
2064*67e74705SXin Li       Actions.ActOnModuleInclude(Tok.getLocation(),
2065*67e74705SXin Li                                  reinterpret_cast<Module *>(
2066*67e74705SXin Li                                  Tok.getAnnotationValue()));
2067*67e74705SXin Li       ConsumeToken();
2068*67e74705SXin Li       // If there is another module import, process it.
2069*67e74705SXin Li       continue;
2070*67e74705SXin Li     default:
2071*67e74705SXin Li       return false;
2072*67e74705SXin Li     }
2073*67e74705SXin Li   }
2074*67e74705SXin Li   return false;
2075*67e74705SXin Li }
2076*67e74705SXin Li 
diagnoseOverflow()2077*67e74705SXin Li bool BalancedDelimiterTracker::diagnoseOverflow() {
2078*67e74705SXin Li   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2079*67e74705SXin Li     << P.getLangOpts().BracketDepth;
2080*67e74705SXin Li   P.Diag(P.Tok, diag::note_bracket_depth);
2081*67e74705SXin Li   P.cutOffParsing();
2082*67e74705SXin Li   return true;
2083*67e74705SXin Li }
2084*67e74705SXin Li 
expectAndConsume(unsigned DiagID,const char * Msg,tok::TokenKind SkipToTok)2085*67e74705SXin Li bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2086*67e74705SXin Li                                                 const char *Msg,
2087*67e74705SXin Li                                                 tok::TokenKind SkipToTok) {
2088*67e74705SXin Li   LOpen = P.Tok.getLocation();
2089*67e74705SXin Li   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2090*67e74705SXin Li     if (SkipToTok != tok::unknown)
2091*67e74705SXin Li       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2092*67e74705SXin Li     return true;
2093*67e74705SXin Li   }
2094*67e74705SXin Li 
2095*67e74705SXin Li   if (getDepth() < MaxDepth)
2096*67e74705SXin Li     return false;
2097*67e74705SXin Li 
2098*67e74705SXin Li   return diagnoseOverflow();
2099*67e74705SXin Li }
2100*67e74705SXin Li 
diagnoseMissingClose()2101*67e74705SXin Li bool BalancedDelimiterTracker::diagnoseMissingClose() {
2102*67e74705SXin Li   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2103*67e74705SXin Li 
2104*67e74705SXin Li   if (P.Tok.is(tok::annot_module_end))
2105*67e74705SXin Li     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2106*67e74705SXin Li   else
2107*67e74705SXin Li     P.Diag(P.Tok, diag::err_expected) << Close;
2108*67e74705SXin Li   P.Diag(LOpen, diag::note_matching) << Kind;
2109*67e74705SXin Li 
2110*67e74705SXin Li   // If we're not already at some kind of closing bracket, skip to our closing
2111*67e74705SXin Li   // token.
2112*67e74705SXin Li   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2113*67e74705SXin Li       P.Tok.isNot(tok::r_square) &&
2114*67e74705SXin Li       P.SkipUntil(Close, FinalToken,
2115*67e74705SXin Li                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2116*67e74705SXin Li       P.Tok.is(Close))
2117*67e74705SXin Li     LClose = P.ConsumeAnyToken();
2118*67e74705SXin Li   return true;
2119*67e74705SXin Li }
2120*67e74705SXin Li 
skipToEnd()2121*67e74705SXin Li void BalancedDelimiterTracker::skipToEnd() {
2122*67e74705SXin Li   P.SkipUntil(Close, Parser::StopBeforeMatch);
2123*67e74705SXin Li   consumeClose();
2124*67e74705SXin Li }
2125