]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Parse/Parser.cpp
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Parse / Parser.cpp
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, unsigned TST) {
178   if (!Tok.is(tok::semi)) return;
179
180   bool HadMultipleSemis = false;
181   SourceLocation StartLoc = Tok.getLocation();
182   SourceLocation EndLoc = Tok.getLocation();
183   ConsumeToken();
184
185   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
186     HadMultipleSemis = true;
187     EndLoc = Tok.getLocation();
188     ConsumeToken();
189   }
190
191   // C++11 allows extra semicolons at namespace scope, but not in any of the
192   // other contexts.
193   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
194     if (getLangOpts().CPlusPlus11)
195       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
196           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
197     else
198       Diag(StartLoc, diag::ext_extra_semi_cxx11)
199           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
200     return;
201   }
202
203   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
204     Diag(StartLoc, diag::ext_extra_semi)
205         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
206                                     Actions.getASTContext().getPrintingPolicy())
207         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
208   else
209     // A single semicolon is valid after a member function definition.
210     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
211       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
212 }
213
214 bool Parser::expectIdentifier() {
215   if (Tok.is(tok::identifier))
216     return false;
217   if (const auto *II = Tok.getIdentifierInfo()) {
218     if (II->isCPlusPlusKeyword(getLangOpts())) {
219       Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
220           << tok::identifier << Tok.getIdentifierInfo();
221       // Objective-C++: Recover by treating this keyword as a valid identifier.
222       return false;
223     }
224   }
225   Diag(Tok, diag::err_expected) << tok::identifier;
226   return true;
227 }
228
229 //===----------------------------------------------------------------------===//
230 // Error recovery.
231 //===----------------------------------------------------------------------===//
232
233 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
234   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
235 }
236
237 /// SkipUntil - Read tokens until we get to the specified token, then consume
238 /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
239 /// token will ever occur, this skips to the next token, or to some likely
240 /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
241 /// character.
242 ///
243 /// If SkipUntil finds the specified token, it returns true, otherwise it
244 /// returns false.
245 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
246   // We always want this function to skip at least one token if the first token
247   // isn't T and if not at EOF.
248   bool isFirstTokenSkipped = true;
249   while (1) {
250     // If we found one of the tokens, stop and return true.
251     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
252       if (Tok.is(Toks[i])) {
253         if (HasFlagsSet(Flags, StopBeforeMatch)) {
254           // Noop, don't consume the token.
255         } else {
256           ConsumeAnyToken();
257         }
258         return true;
259       }
260     }
261
262     // Important special case: The caller has given up and just wants us to
263     // skip the rest of the file. Do this without recursing, since we can
264     // get here precisely because the caller detected too much recursion.
265     if (Toks.size() == 1 && Toks[0] == tok::eof &&
266         !HasFlagsSet(Flags, StopAtSemi) &&
267         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
268       while (Tok.isNot(tok::eof))
269         ConsumeAnyToken();
270       return true;
271     }
272
273     switch (Tok.getKind()) {
274     case tok::eof:
275       // Ran out of tokens.
276       return false;
277
278     case tok::annot_pragma_openmp:
279     case tok::annot_pragma_openmp_end:
280       // Stop before an OpenMP pragma boundary.
281     case tok::annot_module_begin:
282     case tok::annot_module_end:
283     case tok::annot_module_include:
284       // Stop before we change submodules. They generally indicate a "good"
285       // place to pick up parsing again (except in the special case where
286       // we're trying to skip to EOF).
287       return false;
288
289     case tok::code_completion:
290       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
291         handleUnexpectedCodeCompletionToken();
292       return false;
293
294     case tok::l_paren:
295       // Recursively skip properly-nested parens.
296       ConsumeParen();
297       if (HasFlagsSet(Flags, StopAtCodeCompletion))
298         SkipUntil(tok::r_paren, StopAtCodeCompletion);
299       else
300         SkipUntil(tok::r_paren);
301       break;
302     case tok::l_square:
303       // Recursively skip properly-nested square brackets.
304       ConsumeBracket();
305       if (HasFlagsSet(Flags, StopAtCodeCompletion))
306         SkipUntil(tok::r_square, StopAtCodeCompletion);
307       else
308         SkipUntil(tok::r_square);
309       break;
310     case tok::l_brace:
311       // Recursively skip properly-nested braces.
312       ConsumeBrace();
313       if (HasFlagsSet(Flags, StopAtCodeCompletion))
314         SkipUntil(tok::r_brace, StopAtCodeCompletion);
315       else
316         SkipUntil(tok::r_brace);
317       break;
318     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)
1178             << AL.getName();
1179   }
1180
1181   // In delayed template parsing mode, for function template we consume the
1182   // tokens and store them for late parsing at the end of the translation unit.
1183   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1184       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1185       Actions.canDelayFunctionBody(D)) {
1186     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1187
1188     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1189                                    Scope::CompoundStmtScope);
1190     Scope *ParentScope = getCurScope()->getParent();
1191
1192     D.setFunctionDefinitionKind(FDK_Definition);
1193     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1194                                         TemplateParameterLists);
1195     D.complete(DP);
1196     D.getMutableDeclSpec().abort();
1197
1198     if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1199         trySkippingFunctionBody()) {
1200       BodyScope.Exit();
1201       return Actions.ActOnSkippedFunctionBody(DP);
1202     }
1203
1204     CachedTokens Toks;
1205     LexTemplateFunctionForLateParsing(Toks);
1206
1207     if (DP) {
1208       FunctionDecl *FnD = DP->getAsFunction();
1209       Actions.CheckForFunctionRedefinition(FnD);
1210       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1211     }
1212     return DP;
1213   }
1214   else if (CurParsedObjCImpl &&
1215            !TemplateInfo.TemplateParams &&
1216            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1217             Tok.is(tok::colon)) &&
1218       Actions.CurContext->isTranslationUnit()) {
1219     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1220                                    Scope::CompoundStmtScope);
1221     Scope *ParentScope = getCurScope()->getParent();
1222
1223     D.setFunctionDefinitionKind(FDK_Definition);
1224     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1225                                               MultiTemplateParamsArg());
1226     D.complete(FuncDecl);
1227     D.getMutableDeclSpec().abort();
1228     if (FuncDecl) {
1229       // Consume the tokens and store them for later parsing.
1230       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1231       CurParsedObjCImpl->HasCFunction = true;
1232       return FuncDecl;
1233     }
1234     // FIXME: Should we really fall through here?
1235   }
1236
1237   // Enter a scope for the function body.
1238   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1239                                  Scope::CompoundStmtScope);
1240
1241   // Tell the actions module that we have entered a function definition with the
1242   // specified Declarator for the function.
1243   Sema::SkipBodyInfo SkipBody;
1244   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1245                                               TemplateInfo.TemplateParams
1246                                                   ? *TemplateInfo.TemplateParams
1247                                                   : MultiTemplateParamsArg(),
1248                                               &SkipBody);
1249
1250   if (SkipBody.ShouldSkip) {
1251     SkipFunctionBody();
1252     return Res;
1253   }
1254
1255   // Break out of the ParsingDeclarator context before we parse the body.
1256   D.complete(Res);
1257
1258   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1259   // safe because we're always the sole owner.
1260   D.getMutableDeclSpec().abort();
1261
1262   if (TryConsumeToken(tok::equal)) {
1263     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1264
1265     bool Delete = false;
1266     SourceLocation KWLoc;
1267     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1268       Diag(KWLoc, getLangOpts().CPlusPlus11
1269                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1270                       : diag::ext_defaulted_deleted_function)
1271         << 1 /* deleted */;
1272       Actions.SetDeclDeleted(Res, KWLoc);
1273       Delete = true;
1274     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1275       Diag(KWLoc, getLangOpts().CPlusPlus11
1276                       ? diag::warn_cxx98_compat_defaulted_deleted_function
1277                       : diag::ext_defaulted_deleted_function)
1278         << 0 /* defaulted */;
1279       Actions.SetDeclDefaulted(Res, KWLoc);
1280     } else {
1281       llvm_unreachable("function definition after = not 'delete' or 'default'");
1282     }
1283
1284     if (Tok.is(tok::comma)) {
1285       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1286         << Delete;
1287       SkipUntil(tok::semi);
1288     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1289                                 Delete ? "delete" : "default")) {
1290       SkipUntil(tok::semi);
1291     }
1292
1293     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1294     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1295     return Res;
1296   }
1297
1298   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1299       trySkippingFunctionBody()) {
1300     BodyScope.Exit();
1301     Actions.ActOnSkippedFunctionBody(Res);
1302     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1303   }
1304
1305   if (Tok.is(tok::kw_try))
1306     return ParseFunctionTryBlock(Res, BodyScope);
1307
1308   // If we have a colon, then we're probably parsing a C++
1309   // ctor-initializer.
1310   if (Tok.is(tok::colon)) {
1311     ParseConstructorInitializer(Res);
1312
1313     // Recover from error.
1314     if (!Tok.is(tok::l_brace)) {
1315       BodyScope.Exit();
1316       Actions.ActOnFinishFunctionBody(Res, nullptr);
1317       return Res;
1318     }
1319   } else
1320     Actions.ActOnDefaultCtorInitializers(Res);
1321
1322   // Late attributes are parsed in the same scope as the function body.
1323   if (LateParsedAttrs)
1324     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1325
1326   return ParseFunctionStatementBody(Res, BodyScope);
1327 }
1328
1329 void Parser::SkipFunctionBody() {
1330   if (Tok.is(tok::equal)) {
1331     SkipUntil(tok::semi);
1332     return;
1333   }
1334
1335   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1336   if (IsFunctionTryBlock)
1337     ConsumeToken();
1338
1339   CachedTokens Skipped;
1340   if (ConsumeAndStoreFunctionPrologue(Skipped))
1341     SkipMalformedDecl();
1342   else {
1343     SkipUntil(tok::r_brace);
1344     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1345       SkipUntil(tok::l_brace);
1346       SkipUntil(tok::r_brace);
1347     }
1348   }
1349 }
1350
1351 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1352 /// types for a function with a K&R-style identifier list for arguments.
1353 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1354   // We know that the top-level of this declarator is a function.
1355   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1356
1357   // Enter function-declaration scope, limiting any declarators to the
1358   // function prototype scope, including parameter declarators.
1359   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1360                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1361
1362   // Read all the argument declarations.
1363   while (isDeclarationSpecifier()) {
1364     SourceLocation DSStart = Tok.getLocation();
1365
1366     // Parse the common declaration-specifiers piece.
1367     DeclSpec DS(AttrFactory);
1368     ParseDeclarationSpecifiers(DS);
1369
1370     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1371     // least one declarator'.
1372     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1373     // the declarations though.  It's trivial to ignore them, really hard to do
1374     // anything else with them.
1375     if (TryConsumeToken(tok::semi)) {
1376       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1377       continue;
1378     }
1379
1380     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1381     // than register.
1382     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1383         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1384       Diag(DS.getStorageClassSpecLoc(),
1385            diag::err_invalid_storage_class_in_func_decl);
1386       DS.ClearStorageClassSpecs();
1387     }
1388     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1389       Diag(DS.getThreadStorageClassSpecLoc(),
1390            diag::err_invalid_storage_class_in_func_decl);
1391       DS.ClearStorageClassSpecs();
1392     }
1393
1394     // Parse the first declarator attached to this declspec.
1395     Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeListContext);
1396     ParseDeclarator(ParmDeclarator);
1397
1398     // Handle the full declarator list.
1399     while (1) {
1400       // If attributes are present, parse them.
1401       MaybeParseGNUAttributes(ParmDeclarator);
1402
1403       // Ask the actions module to compute the type for this declarator.
1404       Decl *Param =
1405         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1406
1407       if (Param &&
1408           // A missing identifier has already been diagnosed.
1409           ParmDeclarator.getIdentifier()) {
1410
1411         // Scan the argument list looking for the correct param to apply this
1412         // type.
1413         for (unsigned i = 0; ; ++i) {
1414           // C99 6.9.1p6: those declarators shall declare only identifiers from
1415           // the identifier list.
1416           if (i == FTI.NumParams) {
1417             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1418               << ParmDeclarator.getIdentifier();
1419             break;
1420           }
1421
1422           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1423             // Reject redefinitions of parameters.
1424             if (FTI.Params[i].Param) {
1425               Diag(ParmDeclarator.getIdentifierLoc(),
1426                    diag::err_param_redefinition)
1427                  << ParmDeclarator.getIdentifier();
1428             } else {
1429               FTI.Params[i].Param = Param;
1430             }
1431             break;
1432           }
1433         }
1434       }
1435
1436       // If we don't have a comma, it is either the end of the list (a ';') or
1437       // an error, bail out.
1438       if (Tok.isNot(tok::comma))
1439         break;
1440
1441       ParmDeclarator.clear();
1442
1443       // Consume the comma.
1444       ParmDeclarator.setCommaLoc(ConsumeToken());
1445
1446       // Parse the next declarator.
1447       ParseDeclarator(ParmDeclarator);
1448     }
1449
1450     // Consume ';' and continue parsing.
1451     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1452       continue;
1453
1454     // Otherwise recover by skipping to next semi or mandatory function body.
1455     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1456       break;
1457     TryConsumeToken(tok::semi);
1458   }
1459
1460   // The actions module must verify that all arguments were declared.
1461   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1462 }
1463
1464
1465 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1466 /// allowed to be a wide string, and is not subject to character translation.
1467 ///
1468 /// [GNU] asm-string-literal:
1469 ///         string-literal
1470 ///
1471 ExprResult Parser::ParseAsmStringLiteral() {
1472   if (!isTokenStringLiteral()) {
1473     Diag(Tok, diag::err_expected_string_literal)
1474       << /*Source='in...'*/0 << "'asm'";
1475     return ExprError();
1476   }
1477
1478   ExprResult AsmString(ParseStringLiteralExpression());
1479   if (!AsmString.isInvalid()) {
1480     const auto *SL = cast<StringLiteral>(AsmString.get());
1481     if (!SL->isAscii()) {
1482       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1483         << SL->isWide()
1484         << SL->getSourceRange();
1485       return ExprError();
1486     }
1487   }
1488   return AsmString;
1489 }
1490
1491 /// ParseSimpleAsm
1492 ///
1493 /// [GNU] simple-asm-expr:
1494 ///         'asm' '(' asm-string-literal ')'
1495 ///
1496 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1497   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1498   SourceLocation Loc = ConsumeToken();
1499
1500   if (Tok.is(tok::kw_volatile)) {
1501     // Remove from the end of 'asm' to the end of 'volatile'.
1502     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1503                              PP.getLocForEndOfToken(Tok.getLocation()));
1504
1505     Diag(Tok, diag::warn_file_asm_volatile)
1506       << FixItHint::CreateRemoval(RemovalRange);
1507     ConsumeToken();
1508   }
1509
1510   BalancedDelimiterTracker T(*this, tok::l_paren);
1511   if (T.consumeOpen()) {
1512     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1513     return ExprError();
1514   }
1515
1516   ExprResult Result(ParseAsmStringLiteral());
1517
1518   if (!Result.isInvalid()) {
1519     // Close the paren and get the location of the end bracket
1520     T.consumeClose();
1521     if (EndLoc)
1522       *EndLoc = T.getCloseLocation();
1523   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1524     if (EndLoc)
1525       *EndLoc = Tok.getLocation();
1526     ConsumeParen();
1527   }
1528
1529   return Result;
1530 }
1531
1532 /// Get the TemplateIdAnnotation from the token and put it in the
1533 /// cleanup pool so that it gets destroyed when parsing the current top level
1534 /// declaration is finished.
1535 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1536   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1537   TemplateIdAnnotation *
1538       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1539   return Id;
1540 }
1541
1542 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1543   // Push the current token back into the token stream (or revert it if it is
1544   // cached) and use an annotation scope token for current token.
1545   if (PP.isBacktrackEnabled())
1546     PP.RevertCachedTokens(1);
1547   else
1548     PP.EnterToken(Tok, /*IsReinject=*/true);
1549   Tok.setKind(tok::annot_cxxscope);
1550   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1551   Tok.setAnnotationRange(SS.getRange());
1552
1553   // In case the tokens were cached, have Preprocessor replace them
1554   // with the annotation token.  We don't need to do this if we've
1555   // just reverted back to a prior state.
1556   if (IsNewAnnotation)
1557     PP.AnnotateCachedTokens(Tok);
1558 }
1559
1560 /// Attempt to classify the name at the current token position. This may
1561 /// form a type, scope or primary expression annotation, or replace the token
1562 /// with a typo-corrected keyword. This is only appropriate when the current
1563 /// name must refer to an entity which has already been declared.
1564 ///
1565 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1566 ///        and might possibly have a dependent nested name specifier.
1567 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1568 ///        no typo correction will be performed.
1569 Parser::AnnotatedNameKind
1570 Parser::TryAnnotateName(bool IsAddressOfOperand,
1571                         CorrectionCandidateCallback *CCC) {
1572   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1573
1574   const bool EnteringContext = false;
1575   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1576
1577   CXXScopeSpec SS;
1578   if (getLangOpts().CPlusPlus &&
1579       ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1580     return ANK_Error;
1581
1582   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1583     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1584       return ANK_Error;
1585     return ANK_Unresolved;
1586   }
1587
1588   IdentifierInfo *Name = Tok.getIdentifierInfo();
1589   SourceLocation NameLoc = Tok.getLocation();
1590
1591   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1592   // typo-correct to tentatively-declared identifiers.
1593   if (isTentativelyDeclared(Name)) {
1594     // Identifier has been tentatively declared, and thus cannot be resolved as
1595     // an expression. Fall back to annotating it as a type.
1596     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1597       return ANK_Error;
1598     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1599   }
1600
1601   Token Next = NextToken();
1602
1603   // Look up and classify the identifier. We don't perform any typo-correction
1604   // after a scope specifier, because in general we can't recover from typos
1605   // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1606   // jump back into scope specifier parsing).
1607   Sema::NameClassification Classification =
1608       Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1609                            IsAddressOfOperand, SS.isEmpty() ? CCC : nullptr);
1610
1611   // If name lookup found nothing and we guessed that this was a template name,
1612   // double-check before committing to that interpretation. C++20 requires that
1613   // we interpret this as a template-id if it can be, but if it can't be, then
1614   // this is an error recovery case.
1615   if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1616       isTemplateArgumentList(1) == TPResult::False) {
1617     // It's not a template-id; re-classify without the '<' as a hint.
1618     Token FakeNext = Next;
1619     FakeNext.setKind(tok::unknown);
1620     Classification =
1621         Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1622                              IsAddressOfOperand, SS.isEmpty() ? CCC : nullptr);
1623   }
1624
1625   switch (Classification.getKind()) {
1626   case Sema::NC_Error:
1627     return ANK_Error;
1628
1629   case Sema::NC_Keyword:
1630     // The identifier was typo-corrected to a keyword.
1631     Tok.setIdentifierInfo(Name);
1632     Tok.setKind(Name->getTokenID());
1633     PP.TypoCorrectToken(Tok);
1634     if (SS.isNotEmpty())
1635       AnnotateScopeToken(SS, !WasScopeAnnotation);
1636     // We've "annotated" this as a keyword.
1637     return ANK_Success;
1638
1639   case Sema::NC_Unknown:
1640     // It's not something we know about. Leave it unannotated.
1641     break;
1642
1643   case Sema::NC_Type: {
1644     SourceLocation BeginLoc = NameLoc;
1645     if (SS.isNotEmpty())
1646       BeginLoc = SS.getBeginLoc();
1647
1648     /// An Objective-C object type followed by '<' is a specialization of
1649     /// a parameterized class type or a protocol-qualified type.
1650     ParsedType Ty = Classification.getType();
1651     if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1652         (Ty.get()->isObjCObjectType() ||
1653          Ty.get()->isObjCObjectPointerType())) {
1654       // Consume the name.
1655       SourceLocation IdentifierLoc = ConsumeToken();
1656       SourceLocation NewEndLoc;
1657       TypeResult NewType
1658           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1659                                                    /*consumeLastToken=*/false,
1660                                                    NewEndLoc);
1661       if (NewType.isUsable())
1662         Ty = NewType.get();
1663       else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1664         return ANK_Error;
1665     }
1666
1667     Tok.setKind(tok::annot_typename);
1668     setTypeAnnotation(Tok, Ty);
1669     Tok.setAnnotationEndLoc(Tok.getLocation());
1670     Tok.setLocation(BeginLoc);
1671     PP.AnnotateCachedTokens(Tok);
1672     return ANK_Success;
1673   }
1674
1675   case Sema::NC_Expression:
1676     Tok.setKind(tok::annot_primary_expr);
1677     setExprAnnotation(Tok, Classification.getExpression());
1678     Tok.setAnnotationEndLoc(NameLoc);
1679     if (SS.isNotEmpty())
1680       Tok.setLocation(SS.getBeginLoc());
1681     PP.AnnotateCachedTokens(Tok);
1682     return ANK_Success;
1683
1684   case Sema::NC_TypeTemplate:
1685     if (Next.isNot(tok::less)) {
1686       // This may be a type template being used as a template template argument.
1687       if (SS.isNotEmpty())
1688         AnnotateScopeToken(SS, !WasScopeAnnotation);
1689       return ANK_TemplateName;
1690     }
1691     LLVM_FALLTHROUGH;
1692   case Sema::NC_VarTemplate:
1693   case Sema::NC_FunctionTemplate:
1694   case Sema::NC_UndeclaredTemplate: {
1695     // We have a type, variable or function template followed by '<'.
1696     ConsumeToken();
1697     UnqualifiedId Id;
1698     Id.setIdentifier(Name, NameLoc);
1699     if (AnnotateTemplateIdToken(
1700             TemplateTy::make(Classification.getTemplateName()),
1701             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1702       return ANK_Error;
1703     return ANK_Success;
1704   }
1705
1706   case Sema::NC_NestedNameSpecifier:
1707     llvm_unreachable("already parsed nested name specifier");
1708   }
1709
1710   // Unable to classify the name, but maybe we can annotate a scope specifier.
1711   if (SS.isNotEmpty())
1712     AnnotateScopeToken(SS, !WasScopeAnnotation);
1713   return ANK_Unresolved;
1714 }
1715
1716 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1717   assert(Tok.isNot(tok::identifier));
1718   Diag(Tok, diag::ext_keyword_as_ident)
1719     << PP.getSpelling(Tok)
1720     << DisableKeyword;
1721   if (DisableKeyword)
1722     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1723   Tok.setKind(tok::identifier);
1724   return true;
1725 }
1726
1727 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1728 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1729 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1730 /// with a single annotation token representing the typename or C++ scope
1731 /// respectively.
1732 /// This simplifies handling of C++ scope specifiers and allows efficient
1733 /// backtracking without the need to re-parse and resolve nested-names and
1734 /// typenames.
1735 /// It will mainly be called when we expect to treat identifiers as typenames
1736 /// (if they are typenames). For example, in C we do not expect identifiers
1737 /// inside expressions to be treated as typenames so it will not be called
1738 /// for expressions in C.
1739 /// The benefit for C/ObjC is that a typename will be annotated and
1740 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1741 /// will not be called twice, once to check whether we have a declaration
1742 /// specifier, and another one to get the actual type inside
1743 /// ParseDeclarationSpecifiers).
1744 ///
1745 /// This returns true if an error occurred.
1746 ///
1747 /// Note that this routine emits an error if you call it with ::new or ::delete
1748 /// as the current tokens, so only call it in contexts where these are invalid.
1749 bool Parser::TryAnnotateTypeOrScopeToken() {
1750   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1751           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1752           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1753           Tok.is(tok::kw___super)) &&
1754          "Cannot be a type or scope token!");
1755
1756   if (Tok.is(tok::kw_typename)) {
1757     // MSVC lets you do stuff like:
1758     //   typename typedef T_::D D;
1759     //
1760     // We will consume the typedef token here and put it back after we have
1761     // parsed the first identifier, transforming it into something more like:
1762     //   typename T_::D typedef D;
1763     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1764       Token TypedefToken;
1765       PP.Lex(TypedefToken);
1766       bool Result = TryAnnotateTypeOrScopeToken();
1767       PP.EnterToken(Tok, /*IsReinject=*/true);
1768       Tok = TypedefToken;
1769       if (!Result)
1770         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1771       return Result;
1772     }
1773
1774     // Parse a C++ typename-specifier, e.g., "typename T::type".
1775     //
1776     //   typename-specifier:
1777     //     'typename' '::' [opt] nested-name-specifier identifier
1778     //     'typename' '::' [opt] nested-name-specifier template [opt]
1779     //            simple-template-id
1780     SourceLocation TypenameLoc = ConsumeToken();
1781     CXXScopeSpec SS;
1782     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1783                                        /*EnteringContext=*/false, nullptr,
1784                                        /*IsTypename*/ true))
1785       return true;
1786     if (!SS.isSet()) {
1787       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1788           Tok.is(tok::annot_decltype)) {
1789         // Attempt to recover by skipping the invalid 'typename'
1790         if (Tok.is(tok::annot_decltype) ||
1791             (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
1792           unsigned DiagID = diag::err_expected_qualified_after_typename;
1793           // MS compatibility: MSVC permits using known types with typename.
1794           // e.g. "typedef typename T* pointer_type"
1795           if (getLangOpts().MicrosoftExt)
1796             DiagID = diag::warn_expected_qualified_after_typename;
1797           Diag(Tok.getLocation(), DiagID);
1798           return false;
1799         }
1800       }
1801       if (Tok.isEditorPlaceholder())
1802         return true;
1803
1804       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1805       return true;
1806     }
1807
1808     TypeResult Ty;
1809     if (Tok.is(tok::identifier)) {
1810       // FIXME: check whether the next token is '<', first!
1811       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1812                                      *Tok.getIdentifierInfo(),
1813                                      Tok.getLocation());
1814     } else if (Tok.is(tok::annot_template_id)) {
1815       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1816       if (TemplateId->Kind != TNK_Type_template &&
1817           TemplateId->Kind != TNK_Dependent_template_name &&
1818           TemplateId->Kind != TNK_Undeclared_template) {
1819         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1820           << Tok.getAnnotationRange();
1821         return true;
1822       }
1823
1824       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1825                                          TemplateId->NumArgs);
1826
1827       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1828                                      TemplateId->TemplateKWLoc,
1829                                      TemplateId->Template,
1830                                      TemplateId->Name,
1831                                      TemplateId->TemplateNameLoc,
1832                                      TemplateId->LAngleLoc,
1833                                      TemplateArgsPtr,
1834                                      TemplateId->RAngleLoc);
1835     } else {
1836       Diag(Tok, diag::err_expected_type_name_after_typename)
1837         << SS.getRange();
1838       return true;
1839     }
1840
1841     SourceLocation EndLoc = Tok.getLastLoc();
1842     Tok.setKind(tok::annot_typename);
1843     setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1844     Tok.setAnnotationEndLoc(EndLoc);
1845     Tok.setLocation(TypenameLoc);
1846     PP.AnnotateCachedTokens(Tok);
1847     return false;
1848   }
1849
1850   // Remembers whether the token was originally a scope annotation.
1851   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1852
1853   CXXScopeSpec SS;
1854   if (getLangOpts().CPlusPlus)
1855     if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext*/false))
1856       return true;
1857
1858   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
1859 }
1860
1861 /// Try to annotate a type or scope token, having already parsed an
1862 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1863 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1864 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
1865                                                        bool IsNewScope) {
1866   if (Tok.is(tok::identifier)) {
1867     // Determine whether the identifier is a type name.
1868     if (ParsedType Ty = Actions.getTypeName(
1869             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1870             false, NextToken().is(tok::period), nullptr,
1871             /*IsCtorOrDtorName=*/false,
1872             /*NonTrivialTypeSourceInfo*/true,
1873             /*IsClassTemplateDeductionContext*/true)) {
1874       SourceLocation BeginLoc = Tok.getLocation();
1875       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1876         BeginLoc = SS.getBeginLoc();
1877
1878       /// An Objective-C object type followed by '<' is a specialization of
1879       /// a parameterized class type or a protocol-qualified type.
1880       if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1881           (Ty.get()->isObjCObjectType() ||
1882            Ty.get()->isObjCObjectPointerType())) {
1883         // Consume the name.
1884         SourceLocation IdentifierLoc = ConsumeToken();
1885         SourceLocation NewEndLoc;
1886         TypeResult NewType
1887           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1888                                                    /*consumeLastToken=*/false,
1889                                                    NewEndLoc);
1890         if (NewType.isUsable())
1891           Ty = NewType.get();
1892         else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1893           return false;
1894       }
1895
1896       // This is a typename. Replace the current token in-place with an
1897       // annotation type token.
1898       Tok.setKind(tok::annot_typename);
1899       setTypeAnnotation(Tok, Ty);
1900       Tok.setAnnotationEndLoc(Tok.getLocation());
1901       Tok.setLocation(BeginLoc);
1902
1903       // In case the tokens were cached, have Preprocessor replace
1904       // them with the annotation token.
1905       PP.AnnotateCachedTokens(Tok);
1906       return false;
1907     }
1908
1909     if (!getLangOpts().CPlusPlus) {
1910       // If we're in C, we can't have :: tokens at all (the lexer won't return
1911       // them).  If the identifier is not a type, then it can't be scope either,
1912       // just early exit.
1913       return false;
1914     }
1915
1916     // If this is a template-id, annotate with a template-id or type token.
1917     // FIXME: This appears to be dead code. We already have formed template-id
1918     // tokens when parsing the scope specifier; this can never form a new one.
1919     if (NextToken().is(tok::less)) {
1920       TemplateTy Template;
1921       UnqualifiedId TemplateName;
1922       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1923       bool MemberOfUnknownSpecialization;
1924       if (TemplateNameKind TNK = Actions.isTemplateName(
1925               getCurScope(), SS,
1926               /*hasTemplateKeyword=*/false, TemplateName,
1927               /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
1928               MemberOfUnknownSpecialization)) {
1929         // Only annotate an undeclared template name as a template-id if the
1930         // following tokens have the form of a template argument list.
1931         if (TNK != TNK_Undeclared_template ||
1932             isTemplateArgumentList(1) != TPResult::False) {
1933           // Consume the identifier.
1934           ConsumeToken();
1935           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1936                                       TemplateName)) {
1937             // If an unrecoverable error occurred, we need to return true here,
1938             // because the token stream is in a damaged state.  We may not
1939             // return a valid identifier.
1940             return true;
1941           }
1942         }
1943       }
1944     }
1945
1946     // The current token, which is either an identifier or a
1947     // template-id, is not part of the annotation. Fall through to
1948     // push that token back into the stream and complete the C++ scope
1949     // specifier annotation.
1950   }
1951
1952   if (Tok.is(tok::annot_template_id)) {
1953     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1954     if (TemplateId->Kind == TNK_Type_template) {
1955       // A template-id that refers to a type was parsed into a
1956       // template-id annotation in a context where we weren't allowed
1957       // to produce a type annotation token. Update the template-id
1958       // annotation token to a type annotation token now.
1959       AnnotateTemplateIdTokenAsType();
1960       return false;
1961     }
1962   }
1963
1964   if (SS.isEmpty())
1965     return false;
1966
1967   // A C++ scope specifier that isn't followed by a typename.
1968   AnnotateScopeToken(SS, IsNewScope);
1969   return false;
1970 }
1971
1972 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1973 /// annotates C++ scope specifiers and template-ids.  This returns
1974 /// true if there was an error that could not be recovered from.
1975 ///
1976 /// Note that this routine emits an error if you call it with ::new or ::delete
1977 /// as the current tokens, so only call it in contexts where these are invalid.
1978 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1979   assert(getLangOpts().CPlusPlus &&
1980          "Call sites of this function should be guarded by checking for C++");
1981   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1982           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1983           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1984          "Cannot be a type or scope token!");
1985
1986   CXXScopeSpec SS;
1987   if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1988     return true;
1989   if (SS.isEmpty())
1990     return false;
1991
1992   AnnotateScopeToken(SS, true);
1993   return false;
1994 }
1995
1996 bool Parser::isTokenEqualOrEqualTypo() {
1997   tok::TokenKind Kind = Tok.getKind();
1998   switch (Kind) {
1999   default:
2000     return false;
2001   case tok::ampequal:            // &=
2002   case tok::starequal:           // *=
2003   case tok::plusequal:           // +=
2004   case tok::minusequal:          // -=
2005   case tok::exclaimequal:        // !=
2006   case tok::slashequal:          // /=
2007   case tok::percentequal:        // %=
2008   case tok::lessequal:           // <=
2009   case tok::lesslessequal:       // <<=
2010   case tok::greaterequal:        // >=
2011   case tok::greatergreaterequal: // >>=
2012   case tok::caretequal:          // ^=
2013   case tok::pipeequal:           // |=
2014   case tok::equalequal:          // ==
2015     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2016         << Kind
2017         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2018     LLVM_FALLTHROUGH;
2019   case tok::equal:
2020     return true;
2021   }
2022 }
2023
2024 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2025   assert(Tok.is(tok::code_completion));
2026   PrevTokLocation = Tok.getLocation();
2027
2028   for (Scope *S = getCurScope(); S; S = S->getParent()) {
2029     if (S->getFlags() & Scope::FnScope) {
2030       Actions.CodeCompleteOrdinaryName(getCurScope(),
2031                                        Sema::PCC_RecoveryInFunction);
2032       cutOffParsing();
2033       return PrevTokLocation;
2034     }
2035
2036     if (S->getFlags() & Scope::ClassScope) {
2037       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2038       cutOffParsing();
2039       return PrevTokLocation;
2040     }
2041   }
2042
2043   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2044   cutOffParsing();
2045   return PrevTokLocation;
2046 }
2047
2048 // Code-completion pass-through functions
2049
2050 void Parser::CodeCompleteDirective(bool InConditional) {
2051   Actions.CodeCompletePreprocessorDirective(InConditional);
2052 }
2053
2054 void Parser::CodeCompleteInConditionalExclusion() {
2055   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2056 }
2057
2058 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2059   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2060 }
2061
2062 void Parser::CodeCompletePreprocessorExpression() {
2063   Actions.CodeCompletePreprocessorExpression();
2064 }
2065
2066 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2067                                        MacroInfo *MacroInfo,
2068                                        unsigned ArgumentIndex) {
2069   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2070                                                 ArgumentIndex);
2071 }
2072
2073 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2074   Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2075 }
2076
2077 void Parser::CodeCompleteNaturalLanguage() {
2078   Actions.CodeCompleteNaturalLanguage();
2079 }
2080
2081 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2082   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2083          "Expected '__if_exists' or '__if_not_exists'");
2084   Result.IsIfExists = Tok.is(tok::kw___if_exists);
2085   Result.KeywordLoc = ConsumeToken();
2086
2087   BalancedDelimiterTracker T(*this, tok::l_paren);
2088   if (T.consumeOpen()) {
2089     Diag(Tok, diag::err_expected_lparen_after)
2090       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2091     return true;
2092   }
2093
2094   // Parse nested-name-specifier.
2095   if (getLangOpts().CPlusPlus)
2096     ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
2097                                    /*EnteringContext=*/false);
2098
2099   // Check nested-name specifier.
2100   if (Result.SS.isInvalid()) {
2101     T.skipToEnd();
2102     return true;
2103   }
2104
2105   // Parse the unqualified-id.
2106   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2107   if (ParseUnqualifiedId(
2108           Result.SS, /*EnteringContext*/false, /*AllowDestructorName*/true,
2109           /*AllowConstructorName*/true, /*AllowDeductionGuide*/false, nullptr,
2110           &TemplateKWLoc, Result.Name)) {
2111     T.skipToEnd();
2112     return true;
2113   }
2114
2115   if (T.consumeClose())
2116     return true;
2117
2118   // Check if the symbol exists.
2119   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2120                                                Result.IsIfExists, Result.SS,
2121                                                Result.Name)) {
2122   case Sema::IER_Exists:
2123     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2124     break;
2125
2126   case Sema::IER_DoesNotExist:
2127     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2128     break;
2129
2130   case Sema::IER_Dependent:
2131     Result.Behavior = IEB_Dependent;
2132     break;
2133
2134   case Sema::IER_Error:
2135     return true;
2136   }
2137
2138   return false;
2139 }
2140
2141 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2142   IfExistsCondition Result;
2143   if (ParseMicrosoftIfExistsCondition(Result))
2144     return;
2145
2146   BalancedDelimiterTracker Braces(*this, tok::l_brace);
2147   if (Braces.consumeOpen()) {
2148     Diag(Tok, diag::err_expected) << tok::l_brace;
2149     return;
2150   }
2151
2152   switch (Result.Behavior) {
2153   case IEB_Parse:
2154     // Parse declarations below.
2155     break;
2156
2157   case IEB_Dependent:
2158     llvm_unreachable("Cannot have a dependent external declaration");
2159
2160   case IEB_Skip:
2161     Braces.skipToEnd();
2162     return;
2163   }
2164
2165   // Parse the declarations.
2166   // FIXME: Support module import within __if_exists?
2167   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2168     ParsedAttributesWithRange attrs(AttrFactory);
2169     MaybeParseCXX11Attributes(attrs);
2170     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2171     if (Result && !getCurScope()->getParent())
2172       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2173   }
2174   Braces.consumeClose();
2175 }
2176
2177 /// Parse a declaration beginning with the 'module' keyword or C++20
2178 /// context-sensitive keyword (optionally preceded by 'export').
2179 ///
2180 ///   module-declaration:   [Modules TS + P0629R0]
2181 ///     'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2182 ///
2183 ///   global-module-fragment:  [C++2a]
2184 ///     'module' ';' top-level-declaration-seq[opt]
2185 ///   module-declaration:      [C++2a]
2186 ///     'export'[opt] 'module' module-name module-partition[opt]
2187 ///            attribute-specifier-seq[opt] ';'
2188 ///   private-module-fragment: [C++2a]
2189 ///     'module' ':' 'private' ';' top-level-declaration-seq[opt]
2190 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) {
2191   SourceLocation StartLoc = Tok.getLocation();
2192
2193   Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2194                                  ? Sema::ModuleDeclKind::Interface
2195                                  : Sema::ModuleDeclKind::Implementation;
2196
2197   assert(
2198       (Tok.is(tok::kw_module) ||
2199        (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2200       "not a module declaration");
2201   SourceLocation ModuleLoc = ConsumeToken();
2202
2203   // Attributes appear after the module name, not before.
2204   // FIXME: Suggest moving the attributes later with a fixit.
2205   DiagnoseAndSkipCXX11Attributes();
2206
2207   // Parse a global-module-fragment, if present.
2208   if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2209     SourceLocation SemiLoc = ConsumeToken();
2210     if (!IsFirstDecl) {
2211       Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2212         << SourceRange(StartLoc, SemiLoc);
2213       return nullptr;
2214     }
2215     if (MDK == Sema::ModuleDeclKind::Interface) {
2216       Diag(StartLoc, diag::err_module_fragment_exported)
2217         << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2218     }
2219     return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2220   }
2221
2222   // Parse a private-module-fragment, if present.
2223   if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2224       NextToken().is(tok::kw_private)) {
2225     if (MDK == Sema::ModuleDeclKind::Interface) {
2226       Diag(StartLoc, diag::err_module_fragment_exported)
2227         << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2228     }
2229     ConsumeToken();
2230     SourceLocation PrivateLoc = ConsumeToken();
2231     DiagnoseAndSkipCXX11Attributes();
2232     ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2233     return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2234   }
2235
2236   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2237   if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2238     return nullptr;
2239
2240   // Parse the optional module-partition.
2241   if (Tok.is(tok::colon)) {
2242     SourceLocation ColonLoc = ConsumeToken();
2243     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2244     if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false))
2245       return nullptr;
2246
2247     // FIXME: Support module partition declarations.
2248     Diag(ColonLoc, diag::err_unsupported_module_partition)
2249       << SourceRange(ColonLoc, Partition.back().second);
2250     // Recover by parsing as a non-partition.
2251   }
2252
2253   // We don't support any module attributes yet; just parse them and diagnose.
2254   ParsedAttributesWithRange Attrs(AttrFactory);
2255   MaybeParseCXX11Attributes(Attrs);
2256   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2257
2258   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2259
2260   return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl);
2261 }
2262
2263 /// Parse a module import declaration. This is essentially the same for
2264 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2265 /// and the trailing optional attributes (in C++).
2266 ///
2267 /// [ObjC]  @import declaration:
2268 ///           '@' 'import' module-name ';'
2269 /// [ModTS] module-import-declaration:
2270 ///           'import' module-name attribute-specifier-seq[opt] ';'
2271 /// [C++2a] module-import-declaration:
2272 ///           'export'[opt] 'import' module-name
2273 ///                   attribute-specifier-seq[opt] ';'
2274 ///           'export'[opt] 'import' module-partition
2275 ///                   attribute-specifier-seq[opt] ';'
2276 ///           'export'[opt] 'import' header-name
2277 ///                   attribute-specifier-seq[opt] ';'
2278 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
2279   SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2280
2281   SourceLocation ExportLoc;
2282   TryConsumeToken(tok::kw_export, ExportLoc);
2283
2284   assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2285                             : Tok.isObjCAtKeyword(tok::objc_import)) &&
2286          "Improper start to module import");
2287   bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2288   SourceLocation ImportLoc = ConsumeToken();
2289
2290   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2291   Module *HeaderUnit = nullptr;
2292
2293   if (Tok.is(tok::header_name)) {
2294     // This is a header import that the preprocessor decided we should skip
2295     // because it was malformed in some way. Parse and ignore it; it's already
2296     // been diagnosed.
2297     ConsumeToken();
2298   } else if (Tok.is(tok::annot_header_unit)) {
2299     // This is a header import that the preprocessor mapped to a module import.
2300     HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2301     ConsumeAnnotationToken();
2302   } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
2303     SourceLocation ColonLoc = ConsumeToken();
2304     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2305       return nullptr;
2306
2307     // FIXME: Support module partition import.
2308     Diag(ColonLoc, diag::err_unsupported_module_partition)
2309       << SourceRange(ColonLoc, Path.back().second);
2310     return nullptr;
2311   } else {
2312     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2313       return nullptr;
2314   }
2315
2316   ParsedAttributesWithRange Attrs(AttrFactory);
2317   MaybeParseCXX11Attributes(Attrs);
2318   // We don't support any module import attributes yet.
2319   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2320
2321   if (PP.hadModuleLoaderFatalFailure()) {
2322     // With a fatal failure in the module loader, we abort parsing.
2323     cutOffParsing();
2324     return nullptr;
2325   }
2326
2327   DeclResult Import;
2328   if (HeaderUnit)
2329     Import =
2330         Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2331   else if (!Path.empty())
2332     Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path);
2333   ExpectAndConsumeSemi(diag::err_module_expected_semi);
2334   if (Import.isInvalid())
2335     return nullptr;
2336
2337   // Using '@import' in framework headers requires modules to be enabled so that
2338   // the header is parseable. Emit a warning to make the user aware.
2339   if (IsObjCAtImport && AtLoc.isValid()) {
2340     auto &SrcMgr = PP.getSourceManager();
2341     auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
2342     if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
2343                   .endswith(".framework"))
2344       Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2345   }
2346
2347   return Import.get();
2348 }
2349
2350 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2351 /// grammar).
2352 ///
2353 ///         module-name:
2354 ///           module-name-qualifier[opt] identifier
2355 ///         module-name-qualifier:
2356 ///           module-name-qualifier[opt] identifier '.'
2357 bool Parser::ParseModuleName(
2358     SourceLocation UseLoc,
2359     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2360     bool IsImport) {
2361   // Parse the module path.
2362   while (true) {
2363     if (!Tok.is(tok::identifier)) {
2364       if (Tok.is(tok::code_completion)) {
2365         Actions.CodeCompleteModuleImport(UseLoc, Path);
2366         cutOffParsing();
2367         return true;
2368       }
2369
2370       Diag(Tok, diag::err_module_expected_ident) << IsImport;
2371       SkipUntil(tok::semi);
2372       return true;
2373     }
2374
2375     // Record this part of the module path.
2376     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2377     ConsumeToken();
2378
2379     if (Tok.isNot(tok::period))
2380       return false;
2381
2382     ConsumeToken();
2383   }
2384 }
2385
2386 /// Try recover parser when module annotation appears where it must not
2387 /// be found.
2388 /// \returns false if the recover was successful and parsing may be continued, or
2389 /// true if parser must bail out to top level and handle the token there.
2390 bool Parser::parseMisplacedModuleImport() {
2391   while (true) {
2392     switch (Tok.getKind()) {
2393     case tok::annot_module_end:
2394       // If we recovered from a misplaced module begin, we expect to hit a
2395       // misplaced module end too. Stay in the current context when this
2396       // happens.
2397       if (MisplacedModuleBeginCount) {
2398         --MisplacedModuleBeginCount;
2399         Actions.ActOnModuleEnd(Tok.getLocation(),
2400                                reinterpret_cast<Module *>(
2401                                    Tok.getAnnotationValue()));
2402         ConsumeAnnotationToken();
2403         continue;
2404       }
2405       // Inform caller that recovery failed, the error must be handled at upper
2406       // level. This will generate the desired "missing '}' at end of module"
2407       // diagnostics on the way out.
2408       return true;
2409     case tok::annot_module_begin:
2410       // Recover by entering the module (Sema will diagnose).
2411       Actions.ActOnModuleBegin(Tok.getLocation(),
2412                                reinterpret_cast<Module *>(
2413                                    Tok.getAnnotationValue()));
2414       ConsumeAnnotationToken();
2415       ++MisplacedModuleBeginCount;
2416       continue;
2417     case tok::annot_module_include:
2418       // Module import found where it should not be, for instance, inside a
2419       // namespace. Recover by importing the module.
2420       Actions.ActOnModuleInclude(Tok.getLocation(),
2421                                  reinterpret_cast<Module *>(
2422                                      Tok.getAnnotationValue()));
2423       ConsumeAnnotationToken();
2424       // If there is another module import, process it.
2425       continue;
2426     default:
2427       return false;
2428     }
2429   }
2430   return false;
2431 }
2432
2433 bool BalancedDelimiterTracker::diagnoseOverflow() {
2434   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2435     << P.getLangOpts().BracketDepth;
2436   P.Diag(P.Tok, diag::note_bracket_depth);
2437   P.cutOffParsing();
2438   return true;
2439 }
2440
2441 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2442                                                 const char *Msg,
2443                                                 tok::TokenKind SkipToTok) {
2444   LOpen = P.Tok.getLocation();
2445   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2446     if (SkipToTok != tok::unknown)
2447       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2448     return true;
2449   }
2450
2451   if (getDepth() < P.getLangOpts().BracketDepth)
2452     return false;
2453
2454   return diagnoseOverflow();
2455 }
2456
2457 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2458   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2459
2460   if (P.Tok.is(tok::annot_module_end))
2461     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2462   else
2463     P.Diag(P.Tok, diag::err_expected) << Close;
2464   P.Diag(LOpen, diag::note_matching) << Kind;
2465
2466   // If we're not already at some kind of closing bracket, skip to our closing
2467   // token.
2468   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2469       P.Tok.isNot(tok::r_square) &&
2470       P.SkipUntil(Close, FinalToken,
2471                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2472       P.Tok.is(Close))
2473     LClose = P.ConsumeAnyToken();
2474   return true;
2475 }
2476
2477 void BalancedDelimiterTracker::skipToEnd() {
2478   P.SkipUntil(Close, Parser::StopBeforeMatch);
2479   consumeClose();
2480 }