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   // If the main file is a header, we're only pretending it's a TU; don't warn.
556   bool NoTopLevelDecls = ParseTopLevelDecl(Result, true);
557   if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
558       !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
559     Diag(diag::ext_empty_translation_unit);
560 
561   return NoTopLevelDecls;
562 }
563 
564 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
565 /// action tells us to.  This returns true if the EOF was encountered.
566 ///
567 ///   top-level-declaration:
568 ///           declaration
569 /// [C++20]   module-import-declaration
570 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl) {
571   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
572 
573   // Skip over the EOF token, flagging end of previous input for incremental
574   // processing
575   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
576     ConsumeToken();
577 
578   Result = nullptr;
579   switch (Tok.getKind()) {
580   case tok::annot_pragma_unused:
581     HandlePragmaUnused();
582     return false;
583 
584   case tok::kw_export:
585     switch (NextToken().getKind()) {
586     case tok::kw_module:
587       goto module_decl;
588 
589     // Note: no need to handle kw_import here. We only form kw_import under
590     // the Modules TS, and in that case 'export import' is parsed as an
591     // export-declaration containing an import-declaration.
592 
593     // Recognize context-sensitive C++20 'export module' and 'export import'
594     // declarations.
595     case tok::identifier: {
596       IdentifierInfo *II = NextToken().getIdentifierInfo();
597       if ((II == Ident_module || II == Ident_import) &&
598           GetLookAheadToken(2).isNot(tok::coloncolon)) {
599         if (II == Ident_module)
600           goto module_decl;
601         else
602           goto import_decl;
603       }
604       break;
605     }
606 
607     default:
608       break;
609     }
610     break;
611 
612   case tok::kw_module:
613   module_decl:
614     Result = ParseModuleDecl(IsFirstDecl);
615     return false;
616 
617   // tok::kw_import is handled by ParseExternalDeclaration. (Under the Modules
618   // TS, an import can occur within an export block.)
619   import_decl: {
620     Decl *ImportDecl = ParseModuleImport(SourceLocation());
621     Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
622     return false;
623   }
624 
625   case tok::annot_module_include:
626     Actions.ActOnModuleInclude(Tok.getLocation(),
627                                reinterpret_cast<Module *>(
628                                    Tok.getAnnotationValue()));
629     ConsumeAnnotationToken();
630     return false;
631 
632   case tok::annot_module_begin:
633     Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
634                                                     Tok.getAnnotationValue()));
635     ConsumeAnnotationToken();
636     return false;
637 
638   case tok::annot_module_end:
639     Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
640                                                   Tok.getAnnotationValue()));
641     ConsumeAnnotationToken();
642     return false;
643 
644   case tok::eof:
645     // Check whether -fmax-tokens= was reached.
646     if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
647       PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
648           << PP.getTokenCount() << PP.getMaxTokens();
649       SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
650       if (OverrideLoc.isValid()) {
651         PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
652       }
653     }
654 
655     // Late template parsing can begin.
656     Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
657     if (!PP.isIncrementalProcessingEnabled())
658       Actions.ActOnEndOfTranslationUnit();
659     //else don't tell Sema that we ended parsing: more input might come.
660     return true;
661 
662   case tok::identifier:
663     // C++2a [basic.link]p3:
664     //   A token sequence beginning with 'export[opt] module' or
665     //   'export[opt] import' and not immediately followed by '::'
666     //   is never interpreted as the declaration of a top-level-declaration.
667     if ((Tok.getIdentifierInfo() == Ident_module ||
668          Tok.getIdentifierInfo() == Ident_import) &&
669         NextToken().isNot(tok::coloncolon)) {
670       if (Tok.getIdentifierInfo() == Ident_module)
671         goto module_decl;
672       else
673         goto import_decl;
674     }
675     break;
676 
677   default:
678     break;
679   }
680 
681   ParsedAttributesWithRange attrs(AttrFactory);
682   MaybeParseCXX11Attributes(attrs);
683 
684   Result = ParseExternalDeclaration(attrs);
685   return false;
686 }
687 
688 /// ParseExternalDeclaration:
689 ///
690 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
691 ///         function-definition
692 ///         declaration
693 /// [GNU]   asm-definition
694 /// [GNU]   __extension__ external-declaration
695 /// [OBJC]  objc-class-definition
696 /// [OBJC]  objc-class-declaration
697 /// [OBJC]  objc-alias-declaration
698 /// [OBJC]  objc-protocol-definition
699 /// [OBJC]  objc-method-definition
700 /// [OBJC]  @end
701 /// [C++]   linkage-specification
702 /// [GNU] asm-definition:
703 ///         simple-asm-expr ';'
704 /// [C++11] empty-declaration
705 /// [C++11] attribute-declaration
706 ///
707 /// [C++11] empty-declaration:
708 ///           ';'
709 ///
710 /// [C++0x/GNU] 'extern' 'template' declaration
711 ///
712 /// [Modules-TS] module-import-declaration
713 ///
714 Parser::DeclGroupPtrTy
715 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
716                                  ParsingDeclSpec *DS) {
717   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
718   ParenBraceBracketBalancer BalancerRAIIObj(*this);
719 
720   if (PP.isCodeCompletionReached()) {
721     cutOffParsing();
722     return nullptr;
723   }
724 
725   Decl *SingleDecl = nullptr;
726   switch (Tok.getKind()) {
727   case tok::annot_pragma_vis:
728     HandlePragmaVisibility();
729     return nullptr;
730   case tok::annot_pragma_pack:
731     HandlePragmaPack();
732     return nullptr;
733   case tok::annot_pragma_msstruct:
734     HandlePragmaMSStruct();
735     return nullptr;
736   case tok::annot_pragma_align:
737     HandlePragmaAlign();
738     return nullptr;
739   case tok::annot_pragma_weak:
740     HandlePragmaWeak();
741     return nullptr;
742   case tok::annot_pragma_weakalias:
743     HandlePragmaWeakAlias();
744     return nullptr;
745   case tok::annot_pragma_redefine_extname:
746     HandlePragmaRedefineExtname();
747     return nullptr;
748   case tok::annot_pragma_fp_contract:
749     HandlePragmaFPContract();
750     return nullptr;
751   case tok::annot_pragma_fenv_access:
752     HandlePragmaFEnvAccess();
753     return nullptr;
754   case tok::annot_pragma_float_control:
755     HandlePragmaFloatControl();
756     return nullptr;
757   case tok::annot_pragma_fp:
758     HandlePragmaFP();
759     break;
760   case tok::annot_pragma_opencl_extension:
761     HandlePragmaOpenCLExtension();
762     return nullptr;
763   case tok::annot_pragma_openmp: {
764     AccessSpecifier AS = AS_none;
765     return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
766   }
767   case tok::annot_pragma_ms_pointers_to_members:
768     HandlePragmaMSPointersToMembers();
769     return nullptr;
770   case tok::annot_pragma_ms_vtordisp:
771     HandlePragmaMSVtorDisp();
772     return nullptr;
773   case tok::annot_pragma_ms_pragma:
774     HandlePragmaMSPragma();
775     return nullptr;
776   case tok::annot_pragma_dump:
777     HandlePragmaDump();
778     return nullptr;
779   case tok::annot_pragma_attribute:
780     HandlePragmaAttribute();
781     return nullptr;
782   case tok::semi:
783     // Either a C++11 empty-declaration or attribute-declaration.
784     SingleDecl =
785         Actions.ActOnEmptyDeclaration(getCurScope(), attrs, Tok.getLocation());
786     ConsumeExtraSemi(OutsideFunction);
787     break;
788   case tok::r_brace:
789     Diag(Tok, diag::err_extraneous_closing_brace);
790     ConsumeBrace();
791     return nullptr;
792   case tok::eof:
793     Diag(Tok, diag::err_expected_external_declaration);
794     return nullptr;
795   case tok::kw___extension__: {
796     // __extension__ silences extension warnings in the subexpression.
797     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
798     ConsumeToken();
799     return ParseExternalDeclaration(attrs);
800   }
801   case tok::kw_asm: {
802     ProhibitAttributes(attrs);
803 
804     SourceLocation StartLoc = Tok.getLocation();
805     SourceLocation EndLoc;
806 
807     ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
808 
809     // Check if GNU-style InlineAsm is disabled.
810     // Empty asm string is allowed because it will not introduce
811     // any assembly code.
812     if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
813       const auto *SL = cast<StringLiteral>(Result.get());
814       if (!SL->getString().trim().empty())
815         Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
816     }
817 
818     ExpectAndConsume(tok::semi, diag::err_expected_after,
819                      "top-level asm block");
820 
821     if (Result.isInvalid())
822       return nullptr;
823     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
824     break;
825   }
826   case tok::at:
827     return ParseObjCAtDirectives(attrs);
828   case tok::minus:
829   case tok::plus:
830     if (!getLangOpts().ObjC) {
831       Diag(Tok, diag::err_expected_external_declaration);
832       ConsumeToken();
833       return nullptr;
834     }
835     SingleDecl = ParseObjCMethodDefinition();
836     break;
837   case tok::code_completion:
838     if (CurParsedObjCImpl) {
839       // Code-complete Objective-C methods even without leading '-'/'+' prefix.
840       Actions.CodeCompleteObjCMethodDecl(getCurScope(),
841                                          /*IsInstanceMethod=*/None,
842                                          /*ReturnType=*/nullptr);
843     }
844     Actions.CodeCompleteOrdinaryName(
845         getCurScope(),
846         CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
847     cutOffParsing();
848     return nullptr;
849   case tok::kw_import:
850     SingleDecl = ParseModuleImport(SourceLocation());
851     break;
852   case tok::kw_export:
853     if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
854       SingleDecl = ParseExportDeclaration();
855       break;
856     }
857     // This must be 'export template'. Parse it so we can diagnose our lack
858     // of support.
859     LLVM_FALLTHROUGH;
860   case tok::kw_using:
861   case tok::kw_namespace:
862   case tok::kw_typedef:
863   case tok::kw_template:
864   case tok::kw_static_assert:
865   case tok::kw__Static_assert:
866     // A function definition cannot start with any of these keywords.
867     {
868       SourceLocation DeclEnd;
869       return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
870     }
871 
872   case tok::kw_static:
873     // Parse (then ignore) 'static' prior to a template instantiation. This is
874     // a GCC extension that we intentionally do not support.
875     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
876       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
877         << 0;
878       SourceLocation DeclEnd;
879       return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
880     }
881     goto dont_know;
882 
883   case tok::kw_inline:
884     if (getLangOpts().CPlusPlus) {
885       tok::TokenKind NextKind = NextToken().getKind();
886 
887       // Inline namespaces. Allowed as an extension even in C++03.
888       if (NextKind == tok::kw_namespace) {
889         SourceLocation DeclEnd;
890         return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
891       }
892 
893       // Parse (then ignore) 'inline' prior to a template instantiation. This is
894       // a GCC extension that we intentionally do not support.
895       if (NextKind == tok::kw_template) {
896         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
897           << 1;
898         SourceLocation DeclEnd;
899         return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
900       }
901     }
902     goto dont_know;
903 
904   case tok::kw_extern:
905     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
906       // Extern templates
907       SourceLocation ExternLoc = ConsumeToken();
908       SourceLocation TemplateLoc = ConsumeToken();
909       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
910              diag::warn_cxx98_compat_extern_template :
911              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
912       SourceLocation DeclEnd;
913       return Actions.ConvertDeclToDeclGroup(
914           ParseExplicitInstantiation(DeclaratorContext::FileContext, ExternLoc,
915                                      TemplateLoc, DeclEnd, attrs));
916     }
917     goto dont_know;
918 
919   case tok::kw___if_exists:
920   case tok::kw___if_not_exists:
921     ParseMicrosoftIfExistsExternalDeclaration();
922     return nullptr;
923 
924   case tok::kw_module:
925     Diag(Tok, diag::err_unexpected_module_decl);
926     SkipUntil(tok::semi);
927     return nullptr;
928 
929   default:
930   dont_know:
931     if (Tok.isEditorPlaceholder()) {
932       ConsumeToken();
933       return nullptr;
934     }
935     // We can't tell whether this is a function-definition or declaration yet.
936     return ParseDeclarationOrFunctionDefinition(attrs, DS);
937   }
938 
939   // This routine returns a DeclGroup, if the thing we parsed only contains a
940   // single decl, convert it now.
941   return Actions.ConvertDeclToDeclGroup(SingleDecl);
942 }
943 
944 /// Determine whether the current token, if it occurs after a
945 /// declarator, continues a declaration or declaration list.
946 bool Parser::isDeclarationAfterDeclarator() {
947   // Check for '= delete' or '= default'
948   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
949     const Token &KW = NextToken();
950     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
951       return false;
952   }
953 
954   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
955     Tok.is(tok::comma) ||           // int X(),  -> not a function def
956     Tok.is(tok::semi)  ||           // int X();  -> not a function def
957     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
958     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
959     (getLangOpts().CPlusPlus &&
960      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
961 }
962 
963 /// Determine whether the current token, if it occurs after a
964 /// declarator, indicates the start of a function definition.
965 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
966   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
967   if (Tok.is(tok::l_brace))   // int X() {}
968     return true;
969 
970   // Handle K&R C argument lists: int X(f) int f; {}
971   if (!getLangOpts().CPlusPlus &&
972       Declarator.getFunctionTypeInfo().isKNRPrototype())
973     return isDeclarationSpecifier();
974 
975   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
976     const Token &KW = NextToken();
977     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
978   }
979 
980   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
981          Tok.is(tok::kw_try);          // X() try { ... }
982 }
983 
984 /// Parse either a function-definition or a declaration.  We can't tell which
985 /// we have until we read up to the compound-statement in function-definition.
986 /// TemplateParams, if non-NULL, provides the template parameters when we're
987 /// parsing a C++ template-declaration.
988 ///
989 ///       function-definition: [C99 6.9.1]
990 ///         decl-specs      declarator declaration-list[opt] compound-statement
991 /// [C90] function-definition: [C99 6.7.1] - implicit int result
992 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
993 ///
994 ///       declaration: [C99 6.7]
995 ///         declaration-specifiers init-declarator-list[opt] ';'
996 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
997 /// [OMP]   threadprivate-directive
998 /// [OMP]   allocate-directive                         [TODO]
999 ///
1000 Parser::DeclGroupPtrTy
1001 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
1002                                        ParsingDeclSpec &DS,
1003                                        AccessSpecifier AS) {
1004   MaybeParseMicrosoftAttributes(DS.getAttributes());
1005   // Parse the common declaration-specifiers piece.
1006   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1007                              DeclSpecContext::DSC_top_level);
1008 
1009   // If we had a free-standing type definition with a missing semicolon, we
1010   // may get this far before the problem becomes obvious.
1011   if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1012                                    DS, AS, DeclSpecContext::DSC_top_level))
1013     return nullptr;
1014 
1015   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1016   // declaration-specifiers init-declarator-list[opt] ';'
1017   if (Tok.is(tok::semi)) {
1018     auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1019       assert(DeclSpec::isDeclRep(TKind));
1020       switch(TKind) {
1021       case DeclSpec::TST_class:
1022         return 5;
1023       case DeclSpec::TST_struct:
1024         return 6;
1025       case DeclSpec::TST_union:
1026         return 5;
1027       case DeclSpec::TST_enum:
1028         return 4;
1029       case DeclSpec::TST_interface:
1030         return 9;
1031       default:
1032         llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1033       }
1034 
1035     };
1036     // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1037     SourceLocation CorrectLocationForAttributes =
1038         DeclSpec::isDeclRep(DS.getTypeSpecType())
1039             ? DS.getTypeSpecTypeLoc().getLocWithOffset(
1040                   LengthOfTSTToken(DS.getTypeSpecType()))
1041             : SourceLocation();
1042     ProhibitAttributes(attrs, CorrectLocationForAttributes);
1043     ConsumeToken();
1044     RecordDecl *AnonRecord = nullptr;
1045     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1046                                                        DS, AnonRecord);
1047     DS.complete(TheDecl);
1048     if (getLangOpts().OpenCL)
1049       Actions.setCurrentOpenCLExtensionForDecl(TheDecl);
1050     if (AnonRecord) {
1051       Decl* decls[] = {AnonRecord, TheDecl};
1052       return Actions.BuildDeclaratorGroup(decls);
1053     }
1054     return Actions.ConvertDeclToDeclGroup(TheDecl);
1055   }
1056 
1057   DS.takeAttributesFrom(attrs);
1058 
1059   // ObjC2 allows prefix attributes on class interfaces and protocols.
1060   // FIXME: This still needs better diagnostics. We should only accept
1061   // attributes here, no types, etc.
1062   if (getLangOpts().ObjC && Tok.is(tok::at)) {
1063     SourceLocation AtLoc = ConsumeToken(); // the "@"
1064     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1065         !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1066         !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1067       Diag(Tok, diag::err_objc_unexpected_attr);
1068       SkipUntil(tok::semi);
1069       return nullptr;
1070     }
1071 
1072     DS.abort();
1073 
1074     const char *PrevSpec = nullptr;
1075     unsigned DiagID;
1076     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1077                            Actions.getASTContext().getPrintingPolicy()))
1078       Diag(AtLoc, DiagID) << PrevSpec;
1079 
1080     if (Tok.isObjCAtKeyword(tok::objc_protocol))
1081       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1082 
1083     if (Tok.isObjCAtKeyword(tok::objc_implementation))
1084       return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1085 
1086     return Actions.ConvertDeclToDeclGroup(
1087             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1088   }
1089 
1090   // If the declspec consisted only of 'extern' and we have a string
1091   // literal following it, this must be a C++ linkage specifier like
1092   // 'extern "C"'.
1093   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1094       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1095       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1096     Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::FileContext);
1097     return Actions.ConvertDeclToDeclGroup(TheDecl);
1098   }
1099 
1100   return ParseDeclGroup(DS, DeclaratorContext::FileContext);
1101 }
1102 
1103 Parser::DeclGroupPtrTy
1104 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
1105                                              ParsingDeclSpec *DS,
1106                                              AccessSpecifier AS) {
1107   if (DS) {
1108     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
1109   } else {
1110     ParsingDeclSpec PDS(*this);
1111     // Must temporarily exit the objective-c container scope for
1112     // parsing c constructs and re-enter objc container scope
1113     // afterwards.
1114     ObjCDeclContextSwitch ObjCDC(*this);
1115 
1116     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1117   }
1118 }
1119 
1120 /// ParseFunctionDefinition - We parsed and verified that the specified
1121 /// Declarator is well formed.  If this is a K&R-style function, read the
1122 /// parameters declaration-list, then start the compound-statement.
1123 ///
1124 ///       function-definition: [C99 6.9.1]
1125 ///         decl-specs      declarator declaration-list[opt] compound-statement
1126 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1127 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
1128 /// [C++] function-definition: [C++ 8.4]
1129 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
1130 ///         function-body
1131 /// [C++] function-definition: [C++ 8.4]
1132 ///         decl-specifier-seq[opt] declarator function-try-block
1133 ///
1134 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1135                                       const ParsedTemplateInfo &TemplateInfo,
1136                                       LateParsedAttrList *LateParsedAttrs) {
1137   // Poison SEH identifiers so they are flagged as illegal in function bodies.
1138   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1139   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1140   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1141 
1142   // If this is C90 and the declspecs were completely missing, fudge in an
1143   // implicit int.  We do this here because this is the only place where
1144   // declaration-specifiers are completely optional in the grammar.
1145   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
1146     const char *PrevSpec;
1147     unsigned DiagID;
1148     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1149     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1150                                            D.getIdentifierLoc(),
1151                                            PrevSpec, DiagID,
1152                                            Policy);
1153     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1154   }
1155 
1156   // If this declaration was formed with a K&R-style identifier list for the
1157   // arguments, parse declarations for all of the args next.
1158   // int foo(a,b) int a; float b; {}
1159   if (FTI.isKNRPrototype())
1160     ParseKNRParamDeclarations(D);
1161 
1162   // We should have either an opening brace or, in a C++ constructor,
1163   // we may have a colon.
1164   if (Tok.isNot(tok::l_brace) &&
1165       (!getLangOpts().CPlusPlus ||
1166        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1167         Tok.isNot(tok::equal)))) {
1168     Diag(Tok, diag::err_expected_fn_body);
1169 
1170     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1171     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1172 
1173     // If we didn't find the '{', bail out.
1174     if (Tok.isNot(tok::l_brace))
1175       return nullptr;
1176   }
1177 
1178   // Check to make sure that any normal attributes are allowed to be on
1179   // a definition.  Late parsed attributes are checked at the end.
1180   if (Tok.isNot(tok::equal)) {
1181     for (const ParsedAttr &AL : D.getAttributes())
1182       if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
1183         Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1184   }
1185 
1186   // In delayed template parsing mode, for function template we consume the
1187   // tokens and store them for late parsing at the end of the translation unit.
1188   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1189       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1190       Actions.canDelayFunctionBody(D)) {
1191     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1192 
1193     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1194                                    Scope::CompoundStmtScope);
1195     Scope *ParentScope = getCurScope()->getParent();
1196 
1197     D.setFunctionDefinitionKind(FDK_Definition);
1198     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1199                                         TemplateParameterLists);
1200     D.complete(DP);
1201     D.getMutableDeclSpec().abort();
1202 
1203     if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1204         trySkippingFunctionBody()) {
1205       BodyScope.Exit();
1206       return Actions.ActOnSkippedFunctionBody(DP);
1207     }
1208 
1209     CachedTokens Toks;
1210     LexTemplateFunctionForLateParsing(Toks);
1211 
1212     if (DP) {
1213       FunctionDecl *FnD = DP->getAsFunction();
1214       Actions.CheckForFunctionRedefinition(FnD);
1215       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1216     }
1217     return DP;
1218   }
1219   else if (CurParsedObjCImpl &&
1220            !TemplateInfo.TemplateParams &&
1221            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1222             Tok.is(tok::colon)) &&
1223       Actions.CurContext->isTranslationUnit()) {
1224     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1225                                    Scope::CompoundStmtScope);
1226     Scope *ParentScope = getCurScope()->getParent();
1227 
1228     D.setFunctionDefinitionKind(FDK_Definition);
1229     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1230                                               MultiTemplateParamsArg());
1231     D.complete(FuncDecl);
1232     D.getMutableDeclSpec().abort();
1233     if (FuncDecl) {
1234       // Consume the tokens and store them for later parsing.
1235       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1236       CurParsedObjCImpl->HasCFunction = true;
1237       return FuncDecl;
1238     }
1239     // FIXME: Should we really fall through here?
1240   }
1241 
1242   // Enter a scope for the function body.
1243   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1244                                  Scope::CompoundStmtScope);
1245 
1246   // Tell the actions module that we have entered a function definition with the
1247   // specified Declarator for the function.
1248   Sema::SkipBodyInfo SkipBody;
1249   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1250                                               TemplateInfo.TemplateParams
1251                                                   ? *TemplateInfo.TemplateParams
1252                                                   : MultiTemplateParamsArg(),
1253                                               &SkipBody);
1254 
1255   if (SkipBody.ShouldSkip) {
1256     SkipFunctionBody();
1257     return Res;
1258   }
1259 
1260   // Break out of the ParsingDeclarator context before we parse the body.
1261   D.complete(Res);
1262 
1263   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1264   // safe because we're always the sole owner.
1265   D.getMutableDeclSpec().abort();
1266 
1267   // With abbreviated function templates - we need to explicitly add depth to
1268   // account for the implicit template parameter list induced by the template.
1269   if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
1270     if (Template->isAbbreviated() &&
1271         Template->getTemplateParameters()->getParam(0)->isImplicit())
1272       // First template parameter is implicit - meaning no explicit template
1273       // parameter list was specified.
1274       CurTemplateDepthTracker.addDepth(1);
1275 
1276   if (TryConsumeToken(tok::equal)) {
1277     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1278 
1279     bool Delete = false;
1280     SourceLocation KWLoc;
1281     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1282       Diag(KWLoc, getLangOpts().CPlusPlus11
1283                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1284                       : diag::ext_defaulted_deleted_function)
1285         << 1 /* deleted */;
1286       Actions.SetDeclDeleted(Res, KWLoc);
1287       Delete = true;
1288     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1289       Diag(KWLoc, getLangOpts().CPlusPlus11
1290                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1291                       : diag::ext_defaulted_deleted_function)
1292         << 0 /* defaulted */;
1293       Actions.SetDeclDefaulted(Res, KWLoc);
1294     } else {
1295       llvm_unreachable("function definition after = not 'delete' or 'default'");
1296     }
1297 
1298     if (Tok.is(tok::comma)) {
1299       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1300         << Delete;
1301       SkipUntil(tok::semi);
1302     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1303                                 Delete ? "delete" : "default")) {
1304       SkipUntil(tok::semi);
1305     }
1306 
1307     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1308     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1309     return Res;
1310   }
1311 
1312   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1313       trySkippingFunctionBody()) {
1314     BodyScope.Exit();
1315     Actions.ActOnSkippedFunctionBody(Res);
1316     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1317   }
1318 
1319   if (Tok.is(tok::kw_try))
1320     return ParseFunctionTryBlock(Res, BodyScope);
1321 
1322   // If we have a colon, then we're probably parsing a C++
1323   // ctor-initializer.
1324   if (Tok.is(tok::colon)) {
1325     ParseConstructorInitializer(Res);
1326 
1327     // Recover from error.
1328     if (!Tok.is(tok::l_brace)) {
1329       BodyScope.Exit();
1330       Actions.ActOnFinishFunctionBody(Res, nullptr);
1331       return Res;
1332     }
1333   } else
1334     Actions.ActOnDefaultCtorInitializers(Res);
1335 
1336   // Late attributes are parsed in the same scope as the function body.
1337   if (LateParsedAttrs)
1338     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1339 
1340   return ParseFunctionStatementBody(Res, BodyScope);
1341 }
1342 
1343 void Parser::SkipFunctionBody() {
1344   if (Tok.is(tok::equal)) {
1345     SkipUntil(tok::semi);
1346     return;
1347   }
1348 
1349   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1350   if (IsFunctionTryBlock)
1351     ConsumeToken();
1352 
1353   CachedTokens Skipped;
1354   if (ConsumeAndStoreFunctionPrologue(Skipped))
1355     SkipMalformedDecl();
1356   else {
1357     SkipUntil(tok::r_brace);
1358     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1359       SkipUntil(tok::l_brace);
1360       SkipUntil(tok::r_brace);
1361     }
1362   }
1363 }
1364 
1365 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1366 /// types for a function with a K&R-style identifier list for arguments.
1367 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1368   // We know that the top-level of this declarator is a function.
1369   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1370 
1371   // Enter function-declaration scope, limiting any declarators to the
1372   // function prototype scope, including parameter declarators.
1373   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1374                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1375 
1376   // Read all the argument declarations.
1377   while (isDeclarationSpecifier()) {
1378     SourceLocation DSStart = Tok.getLocation();
1379 
1380     // Parse the common declaration-specifiers piece.
1381     DeclSpec DS(AttrFactory);
1382     ParseDeclarationSpecifiers(DS);
1383 
1384     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1385     // least one declarator'.
1386     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1387     // the declarations though.  It's trivial to ignore them, really hard to do
1388     // anything else with them.
1389     if (TryConsumeToken(tok::semi)) {
1390       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1391       continue;
1392     }
1393 
1394     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1395     // than register.
1396     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1397         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1398       Diag(DS.getStorageClassSpecLoc(),
1399            diag::err_invalid_storage_class_in_func_decl);
1400       DS.ClearStorageClassSpecs();
1401     }
1402     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1403       Diag(DS.getThreadStorageClassSpecLoc(),
1404            diag::err_invalid_storage_class_in_func_decl);
1405       DS.ClearStorageClassSpecs();
1406     }
1407 
1408     // Parse the first declarator attached to this declspec.
1409     Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeListContext);
1410     ParseDeclarator(ParmDeclarator);
1411 
1412     // Handle the full declarator list.
1413     while (1) {
1414       // If attributes are present, parse them.
1415       MaybeParseGNUAttributes(ParmDeclarator);
1416 
1417       // Ask the actions module to compute the type for this declarator.
1418       Decl *Param =
1419         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1420 
1421       if (Param &&
1422           // A missing identifier has already been diagnosed.
1423           ParmDeclarator.getIdentifier()) {
1424 
1425         // Scan the argument list looking for the correct param to apply this
1426         // type.
1427         for (unsigned i = 0; ; ++i) {
1428           // C99 6.9.1p6: those declarators shall declare only identifiers from
1429           // the identifier list.
1430           if (i == FTI.NumParams) {
1431             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1432               << ParmDeclarator.getIdentifier();
1433             break;
1434           }
1435 
1436           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1437             // Reject redefinitions of parameters.
1438             if (FTI.Params[i].Param) {
1439               Diag(ParmDeclarator.getIdentifierLoc(),
1440                    diag::err_param_redefinition)
1441                  << ParmDeclarator.getIdentifier();
1442             } else {
1443               FTI.Params[i].Param = Param;
1444             }
1445             break;
1446           }
1447         }
1448       }
1449 
1450       // If we don't have a comma, it is either the end of the list (a ';') or
1451       // an error, bail out.
1452       if (Tok.isNot(tok::comma))
1453         break;
1454 
1455       ParmDeclarator.clear();
1456 
1457       // Consume the comma.
1458       ParmDeclarator.setCommaLoc(ConsumeToken());
1459 
1460       // Parse the next declarator.
1461       ParseDeclarator(ParmDeclarator);
1462     }
1463 
1464     // Consume ';' and continue parsing.
1465     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1466       continue;
1467 
1468     // Otherwise recover by skipping to next semi or mandatory function body.
1469     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1470       break;
1471     TryConsumeToken(tok::semi);
1472   }
1473 
1474   // The actions module must verify that all arguments were declared.
1475   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1476 }
1477 
1478 
1479 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1480 /// allowed to be a wide string, and is not subject to character translation.
1481 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1482 /// asm label as opposed to an asm statement, because such a construct does not
1483 /// behave well.
1484 ///
1485 /// [GNU] asm-string-literal:
1486 ///         string-literal
1487 ///
1488 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1489   if (!isTokenStringLiteral()) {
1490     Diag(Tok, diag::err_expected_string_literal)
1491       << /*Source='in...'*/0 << "'asm'";
1492     return ExprError();
1493   }
1494 
1495   ExprResult AsmString(ParseStringLiteralExpression());
1496   if (!AsmString.isInvalid()) {
1497     const auto *SL = cast<StringLiteral>(AsmString.get());
1498     if (!SL->isAscii()) {
1499       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1500         << SL->isWide()
1501         << SL->getSourceRange();
1502       return ExprError();
1503     }
1504     if (ForAsmLabel && SL->getString().empty()) {
1505       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1506           << 2 /* an empty */ << SL->getSourceRange();
1507       return ExprError();
1508     }
1509   }
1510   return AsmString;
1511 }
1512 
1513 /// ParseSimpleAsm
1514 ///
1515 /// [GNU] simple-asm-expr:
1516 ///         'asm' '(' asm-string-literal ')'
1517 ///
1518 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1519   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1520   SourceLocation Loc = ConsumeToken();
1521 
1522   if (isGNUAsmQualifier(Tok)) {
1523     // Remove from the end of 'asm' to the end of the asm qualifier.
1524     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1525                              PP.getLocForEndOfToken(Tok.getLocation()));
1526     Diag(Tok, diag::err_global_asm_qualifier_ignored)
1527         << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1528         << FixItHint::CreateRemoval(RemovalRange);
1529     ConsumeToken();
1530   }
1531 
1532   BalancedDelimiterTracker T(*this, tok::l_paren);
1533   if (T.consumeOpen()) {
1534     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1535     return ExprError();
1536   }
1537 
1538   ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1539 
1540   if (!Result.isInvalid()) {
1541     // Close the paren and get the location of the end bracket
1542     T.consumeClose();
1543     if (EndLoc)
1544       *EndLoc = T.getCloseLocation();
1545   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1546     if (EndLoc)
1547       *EndLoc = Tok.getLocation();
1548     ConsumeParen();
1549   }
1550 
1551   return Result;
1552 }
1553 
1554 /// Get the TemplateIdAnnotation from the token and put it in the
1555 /// cleanup pool so that it gets destroyed when parsing the current top level
1556 /// declaration is finished.
1557 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1558   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1559   TemplateIdAnnotation *
1560       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1561   return Id;
1562 }
1563 
1564 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1565   // Push the current token back into the token stream (or revert it if it is
1566   // cached) and use an annotation scope token for current token.
1567   if (PP.isBacktrackEnabled())
1568     PP.RevertCachedTokens(1);
1569   else
1570     PP.EnterToken(Tok, /*IsReinject=*/true);
1571   Tok.setKind(tok::annot_cxxscope);
1572   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1573   Tok.setAnnotationRange(SS.getRange());
1574 
1575   // In case the tokens were cached, have Preprocessor replace them
1576   // with the annotation token.  We don't need to do this if we've
1577   // just reverted back to a prior state.
1578   if (IsNewAnnotation)
1579     PP.AnnotateCachedTokens(Tok);
1580 }
1581 
1582 /// Attempt to classify the name at the current token position. This may
1583 /// form a type, scope or primary expression annotation, or replace the token
1584 /// with a typo-corrected keyword. This is only appropriate when the current
1585 /// name must refer to an entity which has already been declared.
1586 ///
1587 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1588 ///        no typo correction will be performed.
1589 Parser::AnnotatedNameKind
1590 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) {
1591   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1592 
1593   const bool EnteringContext = false;
1594   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1595 
1596   CXXScopeSpec SS;
1597   if (getLangOpts().CPlusPlus &&
1598       ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1599                                      /*ObjectHadErrors=*/false,
1600                                      EnteringContext))
1601     return ANK_Error;
1602 
1603   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1604     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1605       return ANK_Error;
1606     return ANK_Unresolved;
1607   }
1608 
1609   IdentifierInfo *Name = Tok.getIdentifierInfo();
1610   SourceLocation NameLoc = Tok.getLocation();
1611 
1612   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1613   // typo-correct to tentatively-declared identifiers.
1614   if (isTentativelyDeclared(Name)) {
1615     // Identifier has been tentatively declared, and thus cannot be resolved as
1616     // an expression. Fall back to annotating it as a type.
1617     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1618       return ANK_Error;
1619     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1620   }
1621 
1622   Token Next = NextToken();
1623 
1624   // Look up and classify the identifier. We don't perform any typo-correction
1625   // after a scope specifier, because in general we can't recover from typos
1626   // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1627   // jump back into scope specifier parsing).
1628   Sema::NameClassification Classification = Actions.ClassifyName(
1629       getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1630 
1631   // If name lookup found nothing and we guessed that this was a template name,
1632   // double-check before committing to that interpretation. C++20 requires that
1633   // we interpret this as a template-id if it can be, but if it can't be, then
1634   // this is an error recovery case.
1635   if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1636       isTemplateArgumentList(1) == TPResult::False) {
1637     // It's not a template-id; re-classify without the '<' as a hint.
1638     Token FakeNext = Next;
1639     FakeNext.setKind(tok::unknown);
1640     Classification =
1641         Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1642                              SS.isEmpty() ? CCC : nullptr);
1643   }
1644 
1645   switch (Classification.getKind()) {
1646   case Sema::NC_Error:
1647     return ANK_Error;
1648 
1649   case Sema::NC_Keyword:
1650     // The identifier was typo-corrected to a keyword.
1651     Tok.setIdentifierInfo(Name);
1652     Tok.setKind(Name->getTokenID());
1653     PP.TypoCorrectToken(Tok);
1654     if (SS.isNotEmpty())
1655       AnnotateScopeToken(SS, !WasScopeAnnotation);
1656     // We've "annotated" this as a keyword.
1657     return ANK_Success;
1658 
1659   case Sema::NC_Unknown:
1660     // It's not something we know about. Leave it unannotated.
1661     break;
1662 
1663   case Sema::NC_Type: {
1664     SourceLocation BeginLoc = NameLoc;
1665     if (SS.isNotEmpty())
1666       BeginLoc = SS.getBeginLoc();
1667 
1668     /// An Objective-C object type followed by '<' is a specialization of
1669     /// a parameterized class type or a protocol-qualified type.
1670     ParsedType Ty = Classification.getType();
1671     if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1672         (Ty.get()->isObjCObjectType() ||
1673          Ty.get()->isObjCObjectPointerType())) {
1674       // Consume the name.
1675       SourceLocation IdentifierLoc = ConsumeToken();
1676       SourceLocation NewEndLoc;
1677       TypeResult NewType
1678           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1679                                                    /*consumeLastToken=*/false,
1680                                                    NewEndLoc);
1681       if (NewType.isUsable())
1682         Ty = NewType.get();
1683       else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1684         return ANK_Error;
1685     }
1686 
1687     Tok.setKind(tok::annot_typename);
1688     setTypeAnnotation(Tok, Ty);
1689     Tok.setAnnotationEndLoc(Tok.getLocation());
1690     Tok.setLocation(BeginLoc);
1691     PP.AnnotateCachedTokens(Tok);
1692     return ANK_Success;
1693   }
1694 
1695   case Sema::NC_OverloadSet:
1696     Tok.setKind(tok::annot_overload_set);
1697     setExprAnnotation(Tok, Classification.getExpression());
1698     Tok.setAnnotationEndLoc(NameLoc);
1699     if (SS.isNotEmpty())
1700       Tok.setLocation(SS.getBeginLoc());
1701     PP.AnnotateCachedTokens(Tok);
1702     return ANK_Success;
1703 
1704   case Sema::NC_NonType:
1705     Tok.setKind(tok::annot_non_type);
1706     setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1707     Tok.setLocation(NameLoc);
1708     Tok.setAnnotationEndLoc(NameLoc);
1709     PP.AnnotateCachedTokens(Tok);
1710     if (SS.isNotEmpty())
1711       AnnotateScopeToken(SS, !WasScopeAnnotation);
1712     return ANK_Success;
1713 
1714   case Sema::NC_UndeclaredNonType:
1715   case Sema::NC_DependentNonType:
1716     Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1717                     ? tok::annot_non_type_undeclared
1718                     : tok::annot_non_type_dependent);
1719     setIdentifierAnnotation(Tok, Name);
1720     Tok.setLocation(NameLoc);
1721     Tok.setAnnotationEndLoc(NameLoc);
1722     PP.AnnotateCachedTokens(Tok);
1723     if (SS.isNotEmpty())
1724       AnnotateScopeToken(SS, !WasScopeAnnotation);
1725     return ANK_Success;
1726 
1727   case Sema::NC_TypeTemplate:
1728     if (Next.isNot(tok::less)) {
1729       // This may be a type template being used as a template template argument.
1730       if (SS.isNotEmpty())
1731         AnnotateScopeToken(SS, !WasScopeAnnotation);
1732       return ANK_TemplateName;
1733     }
1734     LLVM_FALLTHROUGH;
1735   case Sema::NC_VarTemplate:
1736   case Sema::NC_FunctionTemplate:
1737   case Sema::NC_UndeclaredTemplate: {
1738     // We have a type, variable or function template followed by '<'.
1739     ConsumeToken();
1740     UnqualifiedId Id;
1741     Id.setIdentifier(Name, NameLoc);
1742     if (AnnotateTemplateIdToken(
1743             TemplateTy::make(Classification.getTemplateName()),
1744             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1745       return ANK_Error;
1746     return ANK_Success;
1747   }
1748   case Sema::NC_Concept: {
1749     UnqualifiedId Id;
1750     Id.setIdentifier(Name, NameLoc);
1751     if (Next.is(tok::less))
1752       // We have a concept name followed by '<'. Consume the identifier token so
1753       // we reach the '<' and annotate it.
1754       ConsumeToken();
1755     if (AnnotateTemplateIdToken(
1756             TemplateTy::make(Classification.getTemplateName()),
1757             Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1758             /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true))
1759       return ANK_Error;
1760     return ANK_Success;
1761   }
1762   }
1763 
1764   // Unable to classify the name, but maybe we can annotate a scope specifier.
1765   if (SS.isNotEmpty())
1766     AnnotateScopeToken(SS, !WasScopeAnnotation);
1767   return ANK_Unresolved;
1768 }
1769 
1770 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1771   assert(Tok.isNot(tok::identifier));
1772   Diag(Tok, diag::ext_keyword_as_ident)
1773     << PP.getSpelling(Tok)
1774     << DisableKeyword;
1775   if (DisableKeyword)
1776     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1777   Tok.setKind(tok::identifier);
1778   return true;
1779 }
1780 
1781 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1782 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1783 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1784 /// with a single annotation token representing the typename or C++ scope
1785 /// respectively.
1786 /// This simplifies handling of C++ scope specifiers and allows efficient
1787 /// backtracking without the need to re-parse and resolve nested-names and
1788 /// typenames.
1789 /// It will mainly be called when we expect to treat identifiers as typenames
1790 /// (if they are typenames). For example, in C we do not expect identifiers
1791 /// inside expressions to be treated as typenames so it will not be called
1792 /// for expressions in C.
1793 /// The benefit for C/ObjC is that a typename will be annotated and
1794 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1795 /// will not be called twice, once to check whether we have a declaration
1796 /// specifier, and another one to get the actual type inside
1797 /// ParseDeclarationSpecifiers).
1798 ///
1799 /// This returns true if an error occurred.
1800 ///
1801 /// Note that this routine emits an error if you call it with ::new or ::delete
1802 /// as the current tokens, so only call it in contexts where these are invalid.
1803 bool Parser::TryAnnotateTypeOrScopeToken() {
1804   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1805           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1806           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1807           Tok.is(tok::kw___super)) &&
1808          "Cannot be a type or scope token!");
1809 
1810   if (Tok.is(tok::kw_typename)) {
1811     // MSVC lets you do stuff like:
1812     //   typename typedef T_::D D;
1813     //
1814     // We will consume the typedef token here and put it back after we have
1815     // parsed the first identifier, transforming it into something more like:
1816     //   typename T_::D typedef D;
1817     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1818       Token TypedefToken;
1819       PP.Lex(TypedefToken);
1820       bool Result = TryAnnotateTypeOrScopeToken();
1821       PP.EnterToken(Tok, /*IsReinject=*/true);
1822       Tok = TypedefToken;
1823       if (!Result)
1824         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1825       return Result;
1826     }
1827 
1828     // Parse a C++ typename-specifier, e.g., "typename T::type".
1829     //
1830     //   typename-specifier:
1831     //     'typename' '::' [opt] nested-name-specifier identifier
1832     //     'typename' '::' [opt] nested-name-specifier template [opt]
1833     //            simple-template-id
1834     SourceLocation TypenameLoc = ConsumeToken();
1835     CXXScopeSpec SS;
1836     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1837                                        /*ObjectHadErrors=*/false,
1838                                        /*EnteringContext=*/false, nullptr,
1839                                        /*IsTypename*/ true))
1840       return true;
1841     if (SS.isEmpty()) {
1842       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1843           Tok.is(tok::annot_decltype)) {
1844         // Attempt to recover by skipping the invalid 'typename'
1845         if (Tok.is(tok::annot_decltype) ||
1846             (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
1847           unsigned DiagID = diag::err_expected_qualified_after_typename;
1848           // MS compatibility: MSVC permits using known types with typename.
1849           // e.g. "typedef typename T* pointer_type"
1850           if (getLangOpts().MicrosoftExt)
1851             DiagID = diag::warn_expected_qualified_after_typename;
1852           Diag(Tok.getLocation(), DiagID);
1853           return false;
1854         }
1855       }
1856       if (Tok.isEditorPlaceholder())
1857         return true;
1858 
1859       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1860       return true;
1861     }
1862 
1863     TypeResult Ty;
1864     if (Tok.is(tok::identifier)) {
1865       // FIXME: check whether the next token is '<', first!
1866       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1867                                      *Tok.getIdentifierInfo(),
1868                                      Tok.getLocation());
1869     } else if (Tok.is(tok::annot_template_id)) {
1870       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1871       if (!TemplateId->mightBeType()) {
1872         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1873           << Tok.getAnnotationRange();
1874         return true;
1875       }
1876 
1877       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1878                                          TemplateId->NumArgs);
1879 
1880       Ty = TemplateId->isInvalid()
1881                ? TypeError()
1882                : Actions.ActOnTypenameType(
1883                      getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
1884                      TemplateId->Template, TemplateId->Name,
1885                      TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
1886                      TemplateArgsPtr, TemplateId->RAngleLoc);
1887     } else {
1888       Diag(Tok, diag::err_expected_type_name_after_typename)
1889         << SS.getRange();
1890       return true;
1891     }
1892 
1893     SourceLocation EndLoc = Tok.getLastLoc();
1894     Tok.setKind(tok::annot_typename);
1895     setTypeAnnotation(Tok, Ty);
1896     Tok.setAnnotationEndLoc(EndLoc);
1897     Tok.setLocation(TypenameLoc);
1898     PP.AnnotateCachedTokens(Tok);
1899     return false;
1900   }
1901 
1902   // Remembers whether the token was originally a scope annotation.
1903   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1904 
1905   CXXScopeSpec SS;
1906   if (getLangOpts().CPlusPlus)
1907     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1908                                        /*ObjectHadErrors=*/false,
1909                                        /*EnteringContext*/ false))
1910       return true;
1911 
1912   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
1913 }
1914 
1915 /// Try to annotate a type or scope token, having already parsed an
1916 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1917 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1918 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
1919                                                        bool IsNewScope) {
1920   if (Tok.is(tok::identifier)) {
1921     // Determine whether the identifier is a type name.
1922     if (ParsedType Ty = Actions.getTypeName(
1923             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1924             false, NextToken().is(tok::period), nullptr,
1925             /*IsCtorOrDtorName=*/false,
1926             /*NonTrivialTypeSourceInfo*/true,
1927             /*IsClassTemplateDeductionContext*/true)) {
1928       SourceLocation BeginLoc = Tok.getLocation();
1929       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1930         BeginLoc = SS.getBeginLoc();
1931 
1932       /// An Objective-C object type followed by '<' is a specialization of
1933       /// a parameterized class type or a protocol-qualified type.
1934       if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1935           (Ty.get()->isObjCObjectType() ||
1936            Ty.get()->isObjCObjectPointerType())) {
1937         // Consume the name.
1938         SourceLocation IdentifierLoc = ConsumeToken();
1939         SourceLocation NewEndLoc;
1940         TypeResult NewType
1941           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1942                                                    /*consumeLastToken=*/false,
1943                                                    NewEndLoc);
1944         if (NewType.isUsable())
1945           Ty = NewType.get();
1946         else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1947           return false;
1948       }
1949 
1950       // This is a typename. Replace the current token in-place with an
1951       // annotation type token.
1952       Tok.setKind(tok::annot_typename);
1953       setTypeAnnotation(Tok, Ty);
1954       Tok.setAnnotationEndLoc(Tok.getLocation());
1955       Tok.setLocation(BeginLoc);
1956 
1957       // In case the tokens were cached, have Preprocessor replace
1958       // them with the annotation token.
1959       PP.AnnotateCachedTokens(Tok);
1960       return false;
1961     }
1962 
1963     if (!getLangOpts().CPlusPlus) {
1964       // If we're in C, we can't have :: tokens at all (the lexer won't return
1965       // them).  If the identifier is not a type, then it can't be scope either,
1966       // just early exit.
1967       return false;
1968     }
1969 
1970     // If this is a template-id, annotate with a template-id or type token.
1971     // FIXME: This appears to be dead code. We already have formed template-id
1972     // tokens when parsing the scope specifier; this can never form a new one.
1973     if (NextToken().is(tok::less)) {
1974       TemplateTy Template;
1975       UnqualifiedId TemplateName;
1976       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1977       bool MemberOfUnknownSpecialization;
1978       if (TemplateNameKind TNK = Actions.isTemplateName(
1979               getCurScope(), SS,
1980               /*hasTemplateKeyword=*/false, TemplateName,
1981               /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
1982               MemberOfUnknownSpecialization)) {
1983         // Only annotate an undeclared template name as a template-id if the
1984         // following tokens have the form of a template argument list.
1985         if (TNK != TNK_Undeclared_template ||
1986             isTemplateArgumentList(1) != TPResult::False) {
1987           // Consume the identifier.
1988           ConsumeToken();
1989           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1990                                       TemplateName)) {
1991             // If an unrecoverable error occurred, we need to return true here,
1992             // because the token stream is in a damaged state.  We may not
1993             // return a valid identifier.
1994             return true;
1995           }
1996         }
1997       }
1998     }
1999 
2000     // The current token, which is either an identifier or a
2001     // template-id, is not part of the annotation. Fall through to
2002     // push that token back into the stream and complete the C++ scope
2003     // specifier annotation.
2004   }
2005 
2006   if (Tok.is(tok::annot_template_id)) {
2007     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2008     if (TemplateId->Kind == TNK_Type_template) {
2009       // A template-id that refers to a type was parsed into a
2010       // template-id annotation in a context where we weren't allowed
2011       // to produce a type annotation token. Update the template-id
2012       // annotation token to a type annotation token now.
2013       AnnotateTemplateIdTokenAsType(SS);
2014       return false;
2015     }
2016   }
2017 
2018   if (SS.isEmpty())
2019     return false;
2020 
2021   // A C++ scope specifier that isn't followed by a typename.
2022   AnnotateScopeToken(SS, IsNewScope);
2023   return false;
2024 }
2025 
2026 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2027 /// annotates C++ scope specifiers and template-ids.  This returns
2028 /// true if there was an error that could not be recovered from.
2029 ///
2030 /// Note that this routine emits an error if you call it with ::new or ::delete
2031 /// as the current tokens, so only call it in contexts where these are invalid.
2032 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2033   assert(getLangOpts().CPlusPlus &&
2034          "Call sites of this function should be guarded by checking for C++");
2035   assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2036 
2037   CXXScopeSpec SS;
2038   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2039                                      /*ObjectHadErrors=*/false,
2040                                      EnteringContext))
2041     return true;
2042   if (SS.isEmpty())
2043     return false;
2044 
2045   AnnotateScopeToken(SS, true);
2046   return false;
2047 }
2048 
2049 bool Parser::isTokenEqualOrEqualTypo() {
2050   tok::TokenKind Kind = Tok.getKind();
2051   switch (Kind) {
2052   default:
2053     return false;
2054   case tok::ampequal:            // &=
2055   case tok::starequal:           // *=
2056   case tok::plusequal:           // +=
2057   case tok::minusequal:          // -=
2058   case tok::exclaimequal:        // !=
2059   case tok::slashequal:          // /=
2060   case tok::percentequal:        // %=
2061   case tok::lessequal:           // <=
2062   case tok::lesslessequal:       // <<=
2063   case tok::greaterequal:        // >=
2064   case tok::greatergreaterequal: // >>=
2065   case tok::caretequal:          // ^=
2066   case tok::pipeequal:           // |=
2067   case tok::equalequal:          // ==
2068     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2069         << Kind
2070         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2071     LLVM_FALLTHROUGH;
2072   case tok::equal:
2073     return true;
2074   }
2075 }
2076 
2077 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2078   assert(Tok.is(tok::code_completion));
2079   PrevTokLocation = Tok.getLocation();
2080 
2081   for (Scope *S = getCurScope(); S; S = S->getParent()) {
2082     if (S->getFlags() & Scope::FnScope) {
2083       Actions.CodeCompleteOrdinaryName(getCurScope(),
2084                                        Sema::PCC_RecoveryInFunction);
2085       cutOffParsing();
2086       return PrevTokLocation;
2087     }
2088 
2089     if (S->getFlags() & Scope::ClassScope) {
2090       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2091       cutOffParsing();
2092       return PrevTokLocation;
2093     }
2094   }
2095 
2096   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2097   cutOffParsing();
2098   return PrevTokLocation;
2099 }
2100 
2101 // Code-completion pass-through functions
2102 
2103 void Parser::CodeCompleteDirective(bool InConditional) {
2104   Actions.CodeCompletePreprocessorDirective(InConditional);
2105 }
2106 
2107 void Parser::CodeCompleteInConditionalExclusion() {
2108   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2109 }
2110 
2111 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2112   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2113 }
2114 
2115 void Parser::CodeCompletePreprocessorExpression() {
2116   Actions.CodeCompletePreprocessorExpression();
2117 }
2118 
2119 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2120                                        MacroInfo *MacroInfo,
2121                                        unsigned ArgumentIndex) {
2122   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2123                                                 ArgumentIndex);
2124 }
2125 
2126 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2127   Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2128 }
2129 
2130 void Parser::CodeCompleteNaturalLanguage() {
2131   Actions.CodeCompleteNaturalLanguage();
2132 }
2133 
2134 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2135   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2136          "Expected '__if_exists' or '__if_not_exists'");
2137   Result.IsIfExists = Tok.is(tok::kw___if_exists);
2138   Result.KeywordLoc = ConsumeToken();
2139 
2140   BalancedDelimiterTracker T(*this, tok::l_paren);
2141   if (T.consumeOpen()) {
2142     Diag(Tok, diag::err_expected_lparen_after)
2143       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2144     return true;
2145   }
2146 
2147   // Parse nested-name-specifier.
2148   if (getLangOpts().CPlusPlus)
2149     ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2150                                    /*ObjectHadErrors=*/false,
2151                                    /*EnteringContext=*/false);
2152 
2153   // Check nested-name specifier.
2154   if (Result.SS.isInvalid()) {
2155     T.skipToEnd();
2156     return true;
2157   }
2158 
2159   // Parse the unqualified-id.
2160   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2161   if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2162                          /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2163                          /*AllowDestructorName*/ true,
2164                          /*AllowConstructorName*/ true,
2165                          /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2166                          Result.Name)) {
2167     T.skipToEnd();
2168     return true;
2169   }
2170 
2171   if (T.consumeClose())
2172     return true;
2173 
2174   // Check if the symbol exists.
2175   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2176                                                Result.IsIfExists, Result.SS,
2177                                                Result.Name)) {
2178   case Sema::IER_Exists:
2179     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2180     break;
2181 
2182   case Sema::IER_DoesNotExist:
2183     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2184     break;
2185 
2186   case Sema::IER_Dependent:
2187     Result.Behavior = IEB_Dependent;
2188     break;
2189 
2190   case Sema::IER_Error:
2191     return true;
2192   }
2193 
2194   return false;
2195 }
2196 
2197 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2198   IfExistsCondition Result;
2199   if (ParseMicrosoftIfExistsCondition(Result))
2200     return;
2201 
2202   BalancedDelimiterTracker Braces(*this, tok::l_brace);
2203   if (Braces.consumeOpen()) {
2204     Diag(Tok, diag::err_expected) << tok::l_brace;
2205     return;
2206   }
2207 
2208   switch (Result.Behavior) {
2209   case IEB_Parse:
2210     // Parse declarations below.
2211     break;
2212 
2213   case IEB_Dependent:
2214     llvm_unreachable("Cannot have a dependent external declaration");
2215 
2216   case IEB_Skip:
2217     Braces.skipToEnd();
2218     return;
2219   }
2220 
2221   // Parse the declarations.
2222   // FIXME: Support module import within __if_exists?
2223   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2224     ParsedAttributesWithRange attrs(AttrFactory);
2225     MaybeParseCXX11Attributes(attrs);
2226     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2227     if (Result && !getCurScope()->getParent())
2228       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2229   }
2230   Braces.consumeClose();
2231 }
2232 
2233 /// Parse a declaration beginning with the 'module' keyword or C++20
2234 /// context-sensitive keyword (optionally preceded by 'export').
2235 ///
2236 ///   module-declaration:   [Modules TS + P0629R0]
2237 ///     'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2238 ///
2239 ///   global-module-fragment:  [C++2a]
2240 ///     'module' ';' top-level-declaration-seq[opt]
2241 ///   module-declaration:      [C++2a]
2242 ///     'export'[opt] 'module' module-name module-partition[opt]
2243 ///            attribute-specifier-seq[opt] ';'
2244 ///   private-module-fragment: [C++2a]
2245 ///     'module' ':' 'private' ';' top-level-declaration-seq[opt]
2246 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) {
2247   SourceLocation StartLoc = Tok.getLocation();
2248 
2249   Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2250                                  ? Sema::ModuleDeclKind::Interface
2251                                  : Sema::ModuleDeclKind::Implementation;
2252 
2253   assert(
2254       (Tok.is(tok::kw_module) ||
2255        (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2256       "not a module declaration");
2257   SourceLocation ModuleLoc = ConsumeToken();
2258 
2259   // Attributes appear after the module name, not before.
2260   // FIXME: Suggest moving the attributes later with a fixit.
2261   DiagnoseAndSkipCXX11Attributes();
2262 
2263   // Parse a global-module-fragment, if present.
2264   if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2265     SourceLocation SemiLoc = ConsumeToken();
2266     if (!IsFirstDecl) {
2267       Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2268         << SourceRange(StartLoc, SemiLoc);
2269       return nullptr;
2270     }
2271     if (MDK == Sema::ModuleDeclKind::Interface) {
2272       Diag(StartLoc, diag::err_module_fragment_exported)
2273         << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2274     }
2275     return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2276   }
2277 
2278   // Parse a private-module-fragment, if present.
2279   if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2280       NextToken().is(tok::kw_private)) {
2281     if (MDK == Sema::ModuleDeclKind::Interface) {
2282       Diag(StartLoc, diag::err_module_fragment_exported)
2283         << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2284     }
2285     ConsumeToken();
2286     SourceLocation PrivateLoc = ConsumeToken();
2287     DiagnoseAndSkipCXX11Attributes();
2288     ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2289     return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2290   }
2291 
2292   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2293   if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2294     return nullptr;
2295 
2296   // Parse the optional module-partition.
2297   if (Tok.is(tok::colon)) {
2298     SourceLocation ColonLoc = ConsumeToken();
2299     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2300     if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false))
2301       return nullptr;
2302 
2303     // FIXME: Support module partition declarations.
2304     Diag(ColonLoc, diag::err_unsupported_module_partition)
2305       << SourceRange(ColonLoc, Partition.back().second);
2306     // Recover by parsing as a non-partition.
2307   }
2308 
2309   // We don't support any module attributes yet; just parse them and diagnose.
2310   ParsedAttributesWithRange Attrs(AttrFactory);
2311   MaybeParseCXX11Attributes(Attrs);
2312   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2313 
2314   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2315 
2316   return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl);
2317 }
2318 
2319 /// Parse a module import declaration. This is essentially the same for
2320 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2321 /// and the trailing optional attributes (in C++).
2322 ///
2323 /// [ObjC]  @import declaration:
2324 ///           '@' 'import' module-name ';'
2325 /// [ModTS] module-import-declaration:
2326 ///           'import' module-name attribute-specifier-seq[opt] ';'
2327 /// [C++2a] module-import-declaration:
2328 ///           'export'[opt] 'import' module-name
2329 ///                   attribute-specifier-seq[opt] ';'
2330 ///           'export'[opt] 'import' module-partition
2331 ///                   attribute-specifier-seq[opt] ';'
2332 ///           'export'[opt] 'import' header-name
2333 ///                   attribute-specifier-seq[opt] ';'
2334 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
2335   SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2336 
2337   SourceLocation ExportLoc;
2338   TryConsumeToken(tok::kw_export, ExportLoc);
2339 
2340   assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2341                             : Tok.isObjCAtKeyword(tok::objc_import)) &&
2342          "Improper start to module import");
2343   bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2344   SourceLocation ImportLoc = ConsumeToken();
2345 
2346   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2347   Module *HeaderUnit = nullptr;
2348 
2349   if (Tok.is(tok::header_name)) {
2350     // This is a header import that the preprocessor decided we should skip
2351     // because it was malformed in some way. Parse and ignore it; it's already
2352     // been diagnosed.
2353     ConsumeToken();
2354   } else if (Tok.is(tok::annot_header_unit)) {
2355     // This is a header import that the preprocessor mapped to a module import.
2356     HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2357     ConsumeAnnotationToken();
2358   } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
2359     SourceLocation ColonLoc = ConsumeToken();
2360     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2361       return nullptr;
2362 
2363     // FIXME: Support module partition import.
2364     Diag(ColonLoc, diag::err_unsupported_module_partition)
2365       << SourceRange(ColonLoc, Path.back().second);
2366     return nullptr;
2367   } else {
2368     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2369       return nullptr;
2370   }
2371 
2372   ParsedAttributesWithRange Attrs(AttrFactory);
2373   MaybeParseCXX11Attributes(Attrs);
2374   // We don't support any module import attributes yet.
2375   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2376 
2377   if (PP.hadModuleLoaderFatalFailure()) {
2378     // With a fatal failure in the module loader, we abort parsing.
2379     cutOffParsing();
2380     return nullptr;
2381   }
2382 
2383   DeclResult Import;
2384   if (HeaderUnit)
2385     Import =
2386         Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2387   else if (!Path.empty())
2388     Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path);
2389   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2390   if (Import.isInvalid())
2391     return nullptr;
2392 
2393   // Using '@import' in framework headers requires modules to be enabled so that
2394   // the header is parseable. Emit a warning to make the user aware.
2395   if (IsObjCAtImport && AtLoc.isValid()) {
2396     auto &SrcMgr = PP.getSourceManager();
2397     auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
2398     if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
2399                   .endswith(".framework"))
2400       Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2401   }
2402 
2403   return Import.get();
2404 }
2405 
2406 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2407 /// grammar).
2408 ///
2409 ///         module-name:
2410 ///           module-name-qualifier[opt] identifier
2411 ///         module-name-qualifier:
2412 ///           module-name-qualifier[opt] identifier '.'
2413 bool Parser::ParseModuleName(
2414     SourceLocation UseLoc,
2415     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2416     bool IsImport) {
2417   // Parse the module path.
2418   while (true) {
2419     if (!Tok.is(tok::identifier)) {
2420       if (Tok.is(tok::code_completion)) {
2421         Actions.CodeCompleteModuleImport(UseLoc, Path);
2422         cutOffParsing();
2423         return true;
2424       }
2425 
2426       Diag(Tok, diag::err_module_expected_ident) << IsImport;
2427       SkipUntil(tok::semi);
2428       return true;
2429     }
2430 
2431     // Record this part of the module path.
2432     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2433     ConsumeToken();
2434 
2435     if (Tok.isNot(tok::period))
2436       return false;
2437 
2438     ConsumeToken();
2439   }
2440 }
2441 
2442 /// Try recover parser when module annotation appears where it must not
2443 /// be found.
2444 /// \returns false if the recover was successful and parsing may be continued, or
2445 /// true if parser must bail out to top level and handle the token there.
2446 bool Parser::parseMisplacedModuleImport() {
2447   while (true) {
2448     switch (Tok.getKind()) {
2449     case tok::annot_module_end:
2450       // If we recovered from a misplaced module begin, we expect to hit a
2451       // misplaced module end too. Stay in the current context when this
2452       // happens.
2453       if (MisplacedModuleBeginCount) {
2454         --MisplacedModuleBeginCount;
2455         Actions.ActOnModuleEnd(Tok.getLocation(),
2456                                reinterpret_cast<Module *>(
2457                                    Tok.getAnnotationValue()));
2458         ConsumeAnnotationToken();
2459         continue;
2460       }
2461       // Inform caller that recovery failed, the error must be handled at upper
2462       // level. This will generate the desired "missing '}' at end of module"
2463       // diagnostics on the way out.
2464       return true;
2465     case tok::annot_module_begin:
2466       // Recover by entering the module (Sema will diagnose).
2467       Actions.ActOnModuleBegin(Tok.getLocation(),
2468                                reinterpret_cast<Module *>(
2469                                    Tok.getAnnotationValue()));
2470       ConsumeAnnotationToken();
2471       ++MisplacedModuleBeginCount;
2472       continue;
2473     case tok::annot_module_include:
2474       // Module import found where it should not be, for instance, inside a
2475       // namespace. Recover by importing the module.
2476       Actions.ActOnModuleInclude(Tok.getLocation(),
2477                                  reinterpret_cast<Module *>(
2478                                      Tok.getAnnotationValue()));
2479       ConsumeAnnotationToken();
2480       // If there is another module import, process it.
2481       continue;
2482     default:
2483       return false;
2484     }
2485   }
2486   return false;
2487 }
2488 
2489 bool BalancedDelimiterTracker::diagnoseOverflow() {
2490   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2491     << P.getLangOpts().BracketDepth;
2492   P.Diag(P.Tok, diag::note_bracket_depth);
2493   P.cutOffParsing();
2494   return true;
2495 }
2496 
2497 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2498                                                 const char *Msg,
2499                                                 tok::TokenKind SkipToTok) {
2500   LOpen = P.Tok.getLocation();
2501   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2502     if (SkipToTok != tok::unknown)
2503       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2504     return true;
2505   }
2506 
2507   if (getDepth() < P.getLangOpts().BracketDepth)
2508     return false;
2509 
2510   return diagnoseOverflow();
2511 }
2512 
2513 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2514   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2515 
2516   if (P.Tok.is(tok::annot_module_end))
2517     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2518   else
2519     P.Diag(P.Tok, diag::err_expected) << Close;
2520   P.Diag(LOpen, diag::note_matching) << Kind;
2521 
2522   // If we're not already at some kind of closing bracket, skip to our closing
2523   // token.
2524   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2525       P.Tok.isNot(tok::r_square) &&
2526       P.SkipUntil(Close, FinalToken,
2527                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2528       P.Tok.is(Close))
2529     LClose = P.ConsumeAnyToken();
2530   return true;
2531 }
2532 
2533 void BalancedDelimiterTracker::skipToEnd() {
2534   P.SkipUntil(Close, Parser::StopBeforeMatch);
2535   consumeClose();
2536 }
2537