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