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