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