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