xref: /freebsd/contrib/llvm-project/clang/lib/Parse/Parser.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===--- Parser.cpp - C Language Family Parser ----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file implements the Parser interfaces.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/Parse/Parser.h"
140b57cec5SDimitry Andric #include "clang/AST/ASTConsumer.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
1606c3fb27SDimitry Andric #include "clang/AST/ASTLambda.h"
175f757f3fSDimitry Andric #include "clang/AST/DeclTemplate.h"
185ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
190b57cec5SDimitry Andric #include "clang/Parse/ParseDiagnostic.h"
200b57cec5SDimitry Andric #include "clang/Parse/RAIIObjectsForParser.h"
210b57cec5SDimitry Andric #include "clang/Sema/DeclSpec.h"
220b57cec5SDimitry Andric #include "clang/Sema/ParsedTemplate.h"
230b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
24*0fca6ea1SDimitry Andric #include "clang/Sema/SemaCodeCompletion.h"
250b57cec5SDimitry Andric #include "llvm/Support/Path.h"
265f757f3fSDimitry Andric #include "llvm/Support/TimeProfiler.h"
270b57cec5SDimitry Andric using namespace clang;
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric namespace {
310b57cec5SDimitry Andric /// A comment handler that passes comments found by the preprocessor
320b57cec5SDimitry Andric /// to the parser action.
330b57cec5SDimitry Andric class ActionCommentHandler : public CommentHandler {
340b57cec5SDimitry Andric   Sema &S;
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric public:
ActionCommentHandler(Sema & S)370b57cec5SDimitry Andric   explicit ActionCommentHandler(Sema &S) : S(S) { }
380b57cec5SDimitry Andric 
HandleComment(Preprocessor & PP,SourceRange Comment)390b57cec5SDimitry Andric   bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
400b57cec5SDimitry Andric     S.ActOnComment(Comment);
410b57cec5SDimitry Andric     return false;
420b57cec5SDimitry Andric   }
430b57cec5SDimitry Andric };
440b57cec5SDimitry Andric } // end anonymous namespace
450b57cec5SDimitry Andric 
getSEHExceptKeyword()460b57cec5SDimitry Andric IdentifierInfo *Parser::getSEHExceptKeyword() {
470b57cec5SDimitry Andric   // __except is accepted as a (contextual) keyword
480b57cec5SDimitry Andric   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
490b57cec5SDimitry Andric     Ident__except = PP.getIdentifierInfo("__except");
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric   return Ident__except;
520b57cec5SDimitry Andric }
530b57cec5SDimitry Andric 
Parser(Preprocessor & pp,Sema & actions,bool skipFunctionBodies)540b57cec5SDimitry Andric Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
55fe6060f1SDimitry Andric     : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
56fe6060f1SDimitry Andric       Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
57fe6060f1SDimitry Andric       ColonIsSacred(false), InMessageExpression(false),
58fe6060f1SDimitry Andric       TemplateParameterDepth(0), ParsingInObjCContainer(false) {
590b57cec5SDimitry Andric   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
600b57cec5SDimitry Andric   Tok.startToken();
610b57cec5SDimitry Andric   Tok.setKind(tok::eof);
620b57cec5SDimitry Andric   Actions.CurScope = nullptr;
630b57cec5SDimitry Andric   NumCachedScopes = 0;
640b57cec5SDimitry Andric   CurParsedObjCImpl = nullptr;
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric   // Add #pragma handlers. These are removed and destroyed in the
670b57cec5SDimitry Andric   // destructor.
680b57cec5SDimitry Andric   initializePragmaHandlers();
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric   CommentSemaHandler.reset(new ActionCommentHandler(actions));
710b57cec5SDimitry Andric   PP.addCommentHandler(CommentSemaHandler.get());
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   PP.setCodeCompletionHandler(*this);
747a6dacacSDimitry Andric 
757a6dacacSDimitry Andric   Actions.ParseTypeFromStringCallback =
767a6dacacSDimitry Andric       [this](StringRef TypeStr, StringRef Context, SourceLocation IncludeLoc) {
777a6dacacSDimitry Andric         return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
787a6dacacSDimitry Andric       };
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
Diag(SourceLocation Loc,unsigned DiagID)810b57cec5SDimitry Andric DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
820b57cec5SDimitry Andric   return Diags.Report(Loc, DiagID);
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
Diag(const Token & Tok,unsigned DiagID)850b57cec5SDimitry Andric DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
860b57cec5SDimitry Andric   return Diag(Tok.getLocation(), DiagID);
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric /// Emits a diagnostic suggesting parentheses surrounding a
900b57cec5SDimitry Andric /// given range.
910b57cec5SDimitry Andric ///
920b57cec5SDimitry Andric /// \param Loc The location where we'll emit the diagnostic.
930b57cec5SDimitry Andric /// \param DK The kind of diagnostic to emit.
940b57cec5SDimitry Andric /// \param ParenRange Source range enclosing code that should be parenthesized.
SuggestParentheses(SourceLocation Loc,unsigned DK,SourceRange ParenRange)950b57cec5SDimitry Andric void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
960b57cec5SDimitry Andric                                 SourceRange ParenRange) {
970b57cec5SDimitry Andric   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
980b57cec5SDimitry Andric   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
990b57cec5SDimitry Andric     // We can't display the parentheses, so just dig the
1000b57cec5SDimitry Andric     // warning/error and return.
1010b57cec5SDimitry Andric     Diag(Loc, DK);
1020b57cec5SDimitry Andric     return;
1030b57cec5SDimitry Andric   }
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   Diag(Loc, DK)
1060b57cec5SDimitry Andric     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
1070b57cec5SDimitry Andric     << FixItHint::CreateInsertion(EndLoc, ")");
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric 
IsCommonTypo(tok::TokenKind ExpectedTok,const Token & Tok)1100b57cec5SDimitry Andric static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
1110b57cec5SDimitry Andric   switch (ExpectedTok) {
1120b57cec5SDimitry Andric   case tok::semi:
1130b57cec5SDimitry Andric     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
1140b57cec5SDimitry Andric   default: return false;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric 
ExpectAndConsume(tok::TokenKind ExpectedTok,unsigned DiagID,StringRef Msg)1180b57cec5SDimitry Andric bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
1190b57cec5SDimitry Andric                               StringRef Msg) {
1200b57cec5SDimitry Andric   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
1210b57cec5SDimitry Andric     ConsumeAnyToken();
1220b57cec5SDimitry Andric     return false;
1230b57cec5SDimitry Andric   }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Detect common single-character typos and resume.
1260b57cec5SDimitry Andric   if (IsCommonTypo(ExpectedTok, Tok)) {
1270b57cec5SDimitry Andric     SourceLocation Loc = Tok.getLocation();
1280b57cec5SDimitry Andric     {
1290b57cec5SDimitry Andric       DiagnosticBuilder DB = Diag(Loc, DiagID);
1300b57cec5SDimitry Andric       DB << FixItHint::CreateReplacement(
1310b57cec5SDimitry Andric                 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
1320b57cec5SDimitry Andric       if (DiagID == diag::err_expected)
1330b57cec5SDimitry Andric         DB << ExpectedTok;
1340b57cec5SDimitry Andric       else if (DiagID == diag::err_expected_after)
1350b57cec5SDimitry Andric         DB << Msg << ExpectedTok;
1360b57cec5SDimitry Andric       else
1370b57cec5SDimitry Andric         DB << Msg;
1380b57cec5SDimitry Andric     }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     // Pretend there wasn't a problem.
1410b57cec5SDimitry Andric     ConsumeAnyToken();
1420b57cec5SDimitry Andric     return false;
1430b57cec5SDimitry Andric   }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1460b57cec5SDimitry Andric   const char *Spelling = nullptr;
1470b57cec5SDimitry Andric   if (EndLoc.isValid())
1480b57cec5SDimitry Andric     Spelling = tok::getPunctuatorSpelling(ExpectedTok);
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   DiagnosticBuilder DB =
1510b57cec5SDimitry Andric       Spelling
1520b57cec5SDimitry Andric           ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
1530b57cec5SDimitry Andric           : Diag(Tok, DiagID);
1540b57cec5SDimitry Andric   if (DiagID == diag::err_expected)
1550b57cec5SDimitry Andric     DB << ExpectedTok;
1560b57cec5SDimitry Andric   else if (DiagID == diag::err_expected_after)
1570b57cec5SDimitry Andric     DB << Msg << ExpectedTok;
1580b57cec5SDimitry Andric   else
1590b57cec5SDimitry Andric     DB << Msg;
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   return true;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
ExpectAndConsumeSemi(unsigned DiagID,StringRef TokenUsed)164972a253aSDimitry Andric bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
1650b57cec5SDimitry Andric   if (TryConsumeToken(tok::semi))
1660b57cec5SDimitry Andric     return false;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   if (Tok.is(tok::code_completion)) {
1690b57cec5SDimitry Andric     handleUnexpectedCodeCompletionToken();
1700b57cec5SDimitry Andric     return false;
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
1740b57cec5SDimitry Andric       NextToken().is(tok::semi)) {
1750b57cec5SDimitry Andric     Diag(Tok, diag::err_extraneous_token_before_semi)
1760b57cec5SDimitry Andric       << PP.getSpelling(Tok)
1770b57cec5SDimitry Andric       << FixItHint::CreateRemoval(Tok.getLocation());
1780b57cec5SDimitry Andric     ConsumeAnyToken(); // The ')' or ']'.
1790b57cec5SDimitry Andric     ConsumeToken(); // The ';'.
1800b57cec5SDimitry Andric     return false;
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric 
183972a253aSDimitry Andric   return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
ConsumeExtraSemi(ExtraSemiKind Kind,DeclSpec::TST TST)186a7dea167SDimitry Andric void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
1870b57cec5SDimitry Andric   if (!Tok.is(tok::semi)) return;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   bool HadMultipleSemis = false;
1900b57cec5SDimitry Andric   SourceLocation StartLoc = Tok.getLocation();
1910b57cec5SDimitry Andric   SourceLocation EndLoc = Tok.getLocation();
1920b57cec5SDimitry Andric   ConsumeToken();
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
1950b57cec5SDimitry Andric     HadMultipleSemis = true;
1960b57cec5SDimitry Andric     EndLoc = Tok.getLocation();
1970b57cec5SDimitry Andric     ConsumeToken();
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // C++11 allows extra semicolons at namespace scope, but not in any of the
2010b57cec5SDimitry Andric   // other contexts.
2020b57cec5SDimitry Andric   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
2030b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus11)
2040b57cec5SDimitry Andric       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
2050b57cec5SDimitry Andric           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2060b57cec5SDimitry Andric     else
2070b57cec5SDimitry Andric       Diag(StartLoc, diag::ext_extra_semi_cxx11)
2080b57cec5SDimitry Andric           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2090b57cec5SDimitry Andric     return;
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
2130b57cec5SDimitry Andric     Diag(StartLoc, diag::ext_extra_semi)
214a7dea167SDimitry Andric         << Kind << DeclSpec::getSpecifierName(TST,
2150b57cec5SDimitry Andric                                     Actions.getASTContext().getPrintingPolicy())
2160b57cec5SDimitry Andric         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2170b57cec5SDimitry Andric   else
2180b57cec5SDimitry Andric     // A single semicolon is valid after a member function definition.
2190b57cec5SDimitry Andric     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
2200b57cec5SDimitry Andric       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric 
expectIdentifier()2230b57cec5SDimitry Andric bool Parser::expectIdentifier() {
2240b57cec5SDimitry Andric   if (Tok.is(tok::identifier))
2250b57cec5SDimitry Andric     return false;
2260b57cec5SDimitry Andric   if (const auto *II = Tok.getIdentifierInfo()) {
2270b57cec5SDimitry Andric     if (II->isCPlusPlusKeyword(getLangOpts())) {
2280b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
2290b57cec5SDimitry Andric           << tok::identifier << Tok.getIdentifierInfo();
2300b57cec5SDimitry Andric       // Objective-C++: Recover by treating this keyword as a valid identifier.
2310b57cec5SDimitry Andric       return false;
2320b57cec5SDimitry Andric     }
2330b57cec5SDimitry Andric   }
2340b57cec5SDimitry Andric   Diag(Tok, diag::err_expected) << tok::identifier;
2350b57cec5SDimitry Andric   return true;
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric 
checkCompoundToken(SourceLocation FirstTokLoc,tok::TokenKind FirstTokKind,CompoundToken Op)238e8d8bef9SDimitry Andric void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
239e8d8bef9SDimitry Andric                                 tok::TokenKind FirstTokKind, CompoundToken Op) {
240e8d8bef9SDimitry Andric   if (FirstTokLoc.isInvalid())
241e8d8bef9SDimitry Andric     return;
242e8d8bef9SDimitry Andric   SourceLocation SecondTokLoc = Tok.getLocation();
243e8d8bef9SDimitry Andric 
244e8d8bef9SDimitry Andric   // If either token is in a macro, we expect both tokens to come from the same
245e8d8bef9SDimitry Andric   // macro expansion.
246e8d8bef9SDimitry Andric   if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
247e8d8bef9SDimitry Andric       PP.getSourceManager().getFileID(FirstTokLoc) !=
248e8d8bef9SDimitry Andric           PP.getSourceManager().getFileID(SecondTokLoc)) {
249e8d8bef9SDimitry Andric     Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
250e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
251e8d8bef9SDimitry Andric         << static_cast<int>(Op) << SourceRange(FirstTokLoc);
252e8d8bef9SDimitry Andric     Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
253e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << Tok.getKind()
254e8d8bef9SDimitry Andric         << SourceRange(SecondTokLoc);
255e8d8bef9SDimitry Andric     return;
256e8d8bef9SDimitry Andric   }
257e8d8bef9SDimitry Andric 
258e8d8bef9SDimitry Andric   // We expect the tokens to abut.
259e8d8bef9SDimitry Andric   if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
260e8d8bef9SDimitry Andric     SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
261e8d8bef9SDimitry Andric     if (SpaceLoc.isInvalid())
262e8d8bef9SDimitry Andric       SpaceLoc = FirstTokLoc;
263e8d8bef9SDimitry Andric     Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
264e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
265e8d8bef9SDimitry Andric         << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
266e8d8bef9SDimitry Andric     return;
267e8d8bef9SDimitry Andric   }
268e8d8bef9SDimitry Andric }
269e8d8bef9SDimitry Andric 
2700b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2710b57cec5SDimitry Andric // Error recovery.
2720b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2730b57cec5SDimitry Andric 
HasFlagsSet(Parser::SkipUntilFlags L,Parser::SkipUntilFlags R)2740b57cec5SDimitry Andric static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
2750b57cec5SDimitry Andric   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric /// SkipUntil - Read tokens until we get to the specified token, then consume
2790b57cec5SDimitry Andric /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
2800b57cec5SDimitry Andric /// token will ever occur, this skips to the next token, or to some likely
2810b57cec5SDimitry Andric /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
2820b57cec5SDimitry Andric /// character.
2830b57cec5SDimitry Andric ///
2840b57cec5SDimitry Andric /// If SkipUntil finds the specified token, it returns true, otherwise it
2850b57cec5SDimitry Andric /// returns false.
SkipUntil(ArrayRef<tok::TokenKind> Toks,SkipUntilFlags Flags)2860b57cec5SDimitry Andric bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
2870b57cec5SDimitry Andric   // We always want this function to skip at least one token if the first token
2880b57cec5SDimitry Andric   // isn't T and if not at EOF.
2890b57cec5SDimitry Andric   bool isFirstTokenSkipped = true;
29004eeddc0SDimitry Andric   while (true) {
2910b57cec5SDimitry Andric     // If we found one of the tokens, stop and return true.
2920b57cec5SDimitry Andric     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
2930b57cec5SDimitry Andric       if (Tok.is(Toks[i])) {
2940b57cec5SDimitry Andric         if (HasFlagsSet(Flags, StopBeforeMatch)) {
2950b57cec5SDimitry Andric           // Noop, don't consume the token.
2960b57cec5SDimitry Andric         } else {
2970b57cec5SDimitry Andric           ConsumeAnyToken();
2980b57cec5SDimitry Andric         }
2990b57cec5SDimitry Andric         return true;
3000b57cec5SDimitry Andric       }
3010b57cec5SDimitry Andric     }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric     // Important special case: The caller has given up and just wants us to
3040b57cec5SDimitry Andric     // skip the rest of the file. Do this without recursing, since we can
3050b57cec5SDimitry Andric     // get here precisely because the caller detected too much recursion.
3060b57cec5SDimitry Andric     if (Toks.size() == 1 && Toks[0] == tok::eof &&
3070b57cec5SDimitry Andric         !HasFlagsSet(Flags, StopAtSemi) &&
3080b57cec5SDimitry Andric         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
3090b57cec5SDimitry Andric       while (Tok.isNot(tok::eof))
3100b57cec5SDimitry Andric         ConsumeAnyToken();
3110b57cec5SDimitry Andric       return true;
3120b57cec5SDimitry Andric     }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     switch (Tok.getKind()) {
3150b57cec5SDimitry Andric     case tok::eof:
3160b57cec5SDimitry Andric       // Ran out of tokens.
3170b57cec5SDimitry Andric       return false;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric     case tok::annot_pragma_openmp:
320fe6060f1SDimitry Andric     case tok::annot_attr_openmp:
3210b57cec5SDimitry Andric     case tok::annot_pragma_openmp_end:
3220b57cec5SDimitry Andric       // Stop before an OpenMP pragma boundary.
323480093f4SDimitry Andric       if (OpenMPDirectiveParsing)
324480093f4SDimitry Andric         return false;
325480093f4SDimitry Andric       ConsumeAnnotationToken();
326480093f4SDimitry Andric       break;
3275f757f3fSDimitry Andric     case tok::annot_pragma_openacc:
3285f757f3fSDimitry Andric     case tok::annot_pragma_openacc_end:
3295f757f3fSDimitry Andric       // Stop before an OpenACC pragma boundary.
3305f757f3fSDimitry Andric       if (OpenACCDirectiveParsing)
3315f757f3fSDimitry Andric         return false;
3325f757f3fSDimitry Andric       ConsumeAnnotationToken();
3335f757f3fSDimitry Andric       break;
3340b57cec5SDimitry Andric     case tok::annot_module_begin:
3350b57cec5SDimitry Andric     case tok::annot_module_end:
3360b57cec5SDimitry Andric     case tok::annot_module_include:
33706c3fb27SDimitry Andric     case tok::annot_repl_input_end:
3380b57cec5SDimitry Andric       // Stop before we change submodules. They generally indicate a "good"
3390b57cec5SDimitry Andric       // place to pick up parsing again (except in the special case where
3400b57cec5SDimitry Andric       // we're trying to skip to EOF).
3410b57cec5SDimitry Andric       return false;
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric     case tok::code_completion:
3440b57cec5SDimitry Andric       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
3450b57cec5SDimitry Andric         handleUnexpectedCodeCompletionToken();
3460b57cec5SDimitry Andric       return false;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric     case tok::l_paren:
3490b57cec5SDimitry Andric       // Recursively skip properly-nested parens.
3500b57cec5SDimitry Andric       ConsumeParen();
3510b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3520b57cec5SDimitry Andric         SkipUntil(tok::r_paren, StopAtCodeCompletion);
3530b57cec5SDimitry Andric       else
3540b57cec5SDimitry Andric         SkipUntil(tok::r_paren);
3550b57cec5SDimitry Andric       break;
3560b57cec5SDimitry Andric     case tok::l_square:
3570b57cec5SDimitry Andric       // Recursively skip properly-nested square brackets.
3580b57cec5SDimitry Andric       ConsumeBracket();
3590b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3600b57cec5SDimitry Andric         SkipUntil(tok::r_square, StopAtCodeCompletion);
3610b57cec5SDimitry Andric       else
3620b57cec5SDimitry Andric         SkipUntil(tok::r_square);
3630b57cec5SDimitry Andric       break;
3640b57cec5SDimitry Andric     case tok::l_brace:
3650b57cec5SDimitry Andric       // Recursively skip properly-nested braces.
3660b57cec5SDimitry Andric       ConsumeBrace();
3670b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3680b57cec5SDimitry Andric         SkipUntil(tok::r_brace, StopAtCodeCompletion);
3690b57cec5SDimitry Andric       else
3700b57cec5SDimitry Andric         SkipUntil(tok::r_brace);
3710b57cec5SDimitry Andric       break;
3720b57cec5SDimitry Andric     case tok::question:
3730b57cec5SDimitry Andric       // Recursively skip ? ... : pairs; these function as brackets. But
3740b57cec5SDimitry Andric       // still stop at a semicolon if requested.
3750b57cec5SDimitry Andric       ConsumeToken();
3760b57cec5SDimitry Andric       SkipUntil(tok::colon,
3770b57cec5SDimitry Andric                 SkipUntilFlags(unsigned(Flags) &
3780b57cec5SDimitry Andric                                unsigned(StopAtCodeCompletion | StopAtSemi)));
3790b57cec5SDimitry Andric       break;
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
3820b57cec5SDimitry Andric     // Since the user wasn't looking for this token (if they were, it would
3830b57cec5SDimitry Andric     // already be handled), this isn't balanced.  If there is a LHS token at a
3840b57cec5SDimitry Andric     // higher level, we will assume that this matches the unbalanced token
3850b57cec5SDimitry Andric     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
3860b57cec5SDimitry Andric     case tok::r_paren:
3870b57cec5SDimitry Andric       if (ParenCount && !isFirstTokenSkipped)
3880b57cec5SDimitry Andric         return false;  // Matches something.
3890b57cec5SDimitry Andric       ConsumeParen();
3900b57cec5SDimitry Andric       break;
3910b57cec5SDimitry Andric     case tok::r_square:
3920b57cec5SDimitry Andric       if (BracketCount && !isFirstTokenSkipped)
3930b57cec5SDimitry Andric         return false;  // Matches something.
3940b57cec5SDimitry Andric       ConsumeBracket();
3950b57cec5SDimitry Andric       break;
3960b57cec5SDimitry Andric     case tok::r_brace:
3970b57cec5SDimitry Andric       if (BraceCount && !isFirstTokenSkipped)
3980b57cec5SDimitry Andric         return false;  // Matches something.
3990b57cec5SDimitry Andric       ConsumeBrace();
4000b57cec5SDimitry Andric       break;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     case tok::semi:
4030b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtSemi))
4040b57cec5SDimitry Andric         return false;
405bdd1243dSDimitry Andric       [[fallthrough]];
4060b57cec5SDimitry Andric     default:
4070b57cec5SDimitry Andric       // Skip this token.
4080b57cec5SDimitry Andric       ConsumeAnyToken();
4090b57cec5SDimitry Andric       break;
4100b57cec5SDimitry Andric     }
4110b57cec5SDimitry Andric     isFirstTokenSkipped = false;
4120b57cec5SDimitry Andric   }
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4160b57cec5SDimitry Andric // Scope manipulation
4170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric /// EnterScope - Start a new scope.
EnterScope(unsigned ScopeFlags)4200b57cec5SDimitry Andric void Parser::EnterScope(unsigned ScopeFlags) {
4210b57cec5SDimitry Andric   if (NumCachedScopes) {
4220b57cec5SDimitry Andric     Scope *N = ScopeCache[--NumCachedScopes];
4230b57cec5SDimitry Andric     N->Init(getCurScope(), ScopeFlags);
4240b57cec5SDimitry Andric     Actions.CurScope = N;
4250b57cec5SDimitry Andric   } else {
4260b57cec5SDimitry Andric     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric /// ExitScope - Pop a scope off the scope stack.
ExitScope()4310b57cec5SDimitry Andric void Parser::ExitScope() {
4320b57cec5SDimitry Andric   assert(getCurScope() && "Scope imbalance!");
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // Inform the actions module that this scope is going away if there are any
4350b57cec5SDimitry Andric   // decls in it.
4360b57cec5SDimitry Andric   Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   Scope *OldScope = getCurScope();
4390b57cec5SDimitry Andric   Actions.CurScope = OldScope->getParent();
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   if (NumCachedScopes == ScopeCacheSize)
4420b57cec5SDimitry Andric     delete OldScope;
4430b57cec5SDimitry Andric   else
4440b57cec5SDimitry Andric     ScopeCache[NumCachedScopes++] = OldScope;
4450b57cec5SDimitry Andric }
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
4480b57cec5SDimitry Andric /// this object does nothing.
ParseScopeFlags(Parser * Self,unsigned ScopeFlags,bool ManageFlags)4490b57cec5SDimitry Andric Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
4500b57cec5SDimitry Andric                                  bool ManageFlags)
4510b57cec5SDimitry Andric   : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
4520b57cec5SDimitry Andric   if (CurScope) {
4530b57cec5SDimitry Andric     OldFlags = CurScope->getFlags();
4540b57cec5SDimitry Andric     CurScope->setFlags(ScopeFlags);
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric }
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric /// Restore the flags for the current scope to what they were before this
4590b57cec5SDimitry Andric /// object overrode them.
~ParseScopeFlags()4600b57cec5SDimitry Andric Parser::ParseScopeFlags::~ParseScopeFlags() {
4610b57cec5SDimitry Andric   if (CurScope)
4620b57cec5SDimitry Andric     CurScope->setFlags(OldFlags);
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4670b57cec5SDimitry Andric // C99 6.9: External Definitions.
4680b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4690b57cec5SDimitry Andric 
~Parser()4700b57cec5SDimitry Andric Parser::~Parser() {
4710b57cec5SDimitry Andric   // If we still have scopes active, delete the scope tree.
4720b57cec5SDimitry Andric   delete getCurScope();
4730b57cec5SDimitry Andric   Actions.CurScope = nullptr;
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   // Free the scope cache.
4760b57cec5SDimitry Andric   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
4770b57cec5SDimitry Andric     delete ScopeCache[i];
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   resetPragmaHandlers();
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   PP.removeCommentHandler(CommentSemaHandler.get());
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   PP.clearCodeCompletionHandler();
4840b57cec5SDimitry Andric 
4855ffd83dbSDimitry Andric   DestroyTemplateIds();
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric /// Initialize - Warm up the parser.
4890b57cec5SDimitry Andric ///
Initialize()4900b57cec5SDimitry Andric void Parser::Initialize() {
4910b57cec5SDimitry Andric   // Create the translation unit scope.  Install it as the current scope.
4920b57cec5SDimitry Andric   assert(getCurScope() == nullptr && "A scope is already active?");
4930b57cec5SDimitry Andric   EnterScope(Scope::DeclScope);
4940b57cec5SDimitry Andric   Actions.ActOnTranslationUnitScope(getCurScope());
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // Initialization for Objective-C context sensitive keywords recognition.
4970b57cec5SDimitry Andric   // Referenced in Parser::ParseObjCTypeQualifierList.
4980b57cec5SDimitry Andric   if (getLangOpts().ObjC) {
4990b57cec5SDimitry Andric     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
5000b57cec5SDimitry Andric     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
5010b57cec5SDimitry Andric     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
5020b57cec5SDimitry Andric     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
5030b57cec5SDimitry Andric     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
5040b57cec5SDimitry Andric     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
5050b57cec5SDimitry Andric     ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
5060b57cec5SDimitry Andric     ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
5070b57cec5SDimitry Andric     ObjCTypeQuals[objc_null_unspecified]
5080b57cec5SDimitry Andric       = &PP.getIdentifierTable().get("null_unspecified");
5090b57cec5SDimitry Andric   }
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   Ident_instancetype = nullptr;
5120b57cec5SDimitry Andric   Ident_final = nullptr;
5130b57cec5SDimitry Andric   Ident_sealed = nullptr;
514fe6060f1SDimitry Andric   Ident_abstract = nullptr;
5150b57cec5SDimitry Andric   Ident_override = nullptr;
5160b57cec5SDimitry Andric   Ident_GNU_final = nullptr;
5170b57cec5SDimitry Andric   Ident_import = nullptr;
5180b57cec5SDimitry Andric   Ident_module = nullptr;
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   Ident_super = &PP.getIdentifierTable().get("super");
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   Ident_vector = nullptr;
5230b57cec5SDimitry Andric   Ident_bool = nullptr;
524fe6060f1SDimitry Andric   Ident_Bool = nullptr;
5250b57cec5SDimitry Andric   Ident_pixel = nullptr;
5260b57cec5SDimitry Andric   if (getLangOpts().AltiVec || getLangOpts().ZVector) {
5270b57cec5SDimitry Andric     Ident_vector = &PP.getIdentifierTable().get("vector");
5280b57cec5SDimitry Andric     Ident_bool = &PP.getIdentifierTable().get("bool");
529fe6060f1SDimitry Andric     Ident_Bool = &PP.getIdentifierTable().get("_Bool");
5300b57cec5SDimitry Andric   }
5310b57cec5SDimitry Andric   if (getLangOpts().AltiVec)
5320b57cec5SDimitry Andric     Ident_pixel = &PP.getIdentifierTable().get("pixel");
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   Ident_introduced = nullptr;
5350b57cec5SDimitry Andric   Ident_deprecated = nullptr;
5360b57cec5SDimitry Andric   Ident_obsoleted = nullptr;
5370b57cec5SDimitry Andric   Ident_unavailable = nullptr;
5380b57cec5SDimitry Andric   Ident_strict = nullptr;
5390b57cec5SDimitry Andric   Ident_replacement = nullptr;
5400b57cec5SDimitry Andric 
54106c3fb27SDimitry Andric   Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
54206c3fb27SDimitry Andric       nullptr;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   Ident__except = nullptr;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   Ident__exception_code = Ident__exception_info = nullptr;
5470b57cec5SDimitry Andric   Ident__abnormal_termination = Ident___exception_code = nullptr;
5480b57cec5SDimitry Andric   Ident___exception_info = Ident___abnormal_termination = nullptr;
5490b57cec5SDimitry Andric   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
5500b57cec5SDimitry Andric   Ident_AbnormalTermination = nullptr;
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   if(getLangOpts().Borland) {
5530b57cec5SDimitry Andric     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
5540b57cec5SDimitry Andric     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
5550b57cec5SDimitry Andric     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
5560b57cec5SDimitry Andric     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
5570b57cec5SDimitry Andric     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
5580b57cec5SDimitry Andric     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
5590b57cec5SDimitry Andric     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
5600b57cec5SDimitry Andric     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
5610b57cec5SDimitry Andric     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
5640b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
5650b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
5660b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
5670b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
5680b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
5690b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
5700b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
5710b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
5720b57cec5SDimitry Andric   }
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules) {
5750b57cec5SDimitry Andric     Ident_import = PP.getIdentifierInfo("import");
5760b57cec5SDimitry Andric     Ident_module = PP.getIdentifierInfo("module");
5770b57cec5SDimitry Andric   }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   Actions.Initialize();
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   // Prime the lexer look-ahead.
5820b57cec5SDimitry Andric   ConsumeToken();
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
DestroyTemplateIds()5855ffd83dbSDimitry Andric void Parser::DestroyTemplateIds() {
5865ffd83dbSDimitry Andric   for (TemplateIdAnnotation *Id : TemplateIds)
5875ffd83dbSDimitry Andric     Id->Destroy();
5885ffd83dbSDimitry Andric   TemplateIds.clear();
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric /// Parse the first top-level declaration in a translation unit.
5920b57cec5SDimitry Andric ///
5930b57cec5SDimitry Andric ///   translation-unit:
5940b57cec5SDimitry Andric /// [C]     external-declaration
5950b57cec5SDimitry Andric /// [C]     translation-unit external-declaration
5960b57cec5SDimitry Andric /// [C++]   top-level-declaration-seq[opt]
5970b57cec5SDimitry Andric /// [C++20] global-module-fragment[opt] module-declaration
5980b57cec5SDimitry Andric ///                 top-level-declaration-seq[opt] private-module-fragment[opt]
5990b57cec5SDimitry Andric ///
6000b57cec5SDimitry Andric /// Note that in C, it is an error if there is no first declaration.
ParseFirstTopLevelDecl(DeclGroupPtrTy & Result,Sema::ModuleImportState & ImportState)60181ad6265SDimitry Andric bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
60281ad6265SDimitry Andric                                     Sema::ModuleImportState &ImportState) {
6030b57cec5SDimitry Andric   Actions.ActOnStartOfTranslationUnit();
6040b57cec5SDimitry Andric 
60581ad6265SDimitry Andric   // For C++20 modules, a module decl must be the first in the TU.  We also
60681ad6265SDimitry Andric   // need to track module imports.
60781ad6265SDimitry Andric   ImportState = Sema::ModuleImportState::FirstDecl;
60881ad6265SDimitry Andric   bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
60981ad6265SDimitry Andric 
6100b57cec5SDimitry Andric   // C11 6.9p1 says translation units must have at least one top-level
6110b57cec5SDimitry Andric   // declaration. C++ doesn't have this restriction. We also don't want to
6120b57cec5SDimitry Andric   // complain if we have a precompiled header, although technically if the PCH
6130b57cec5SDimitry Andric   // is empty we should still emit the (pedantic) diagnostic.
614e8d8bef9SDimitry Andric   // If the main file is a header, we're only pretending it's a TU; don't warn.
6150b57cec5SDimitry Andric   if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
616e8d8bef9SDimitry Andric       !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
6170b57cec5SDimitry Andric     Diag(diag::ext_empty_translation_unit);
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   return NoTopLevelDecls;
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
6230b57cec5SDimitry Andric /// action tells us to.  This returns true if the EOF was encountered.
6240b57cec5SDimitry Andric ///
6250b57cec5SDimitry Andric ///   top-level-declaration:
6260b57cec5SDimitry Andric ///           declaration
6270b57cec5SDimitry Andric /// [C++20]   module-import-declaration
ParseTopLevelDecl(DeclGroupPtrTy & Result,Sema::ModuleImportState & ImportState)62881ad6265SDimitry Andric bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
62981ad6265SDimitry Andric                                Sema::ModuleImportState &ImportState) {
6305ffd83dbSDimitry Andric   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
6310b57cec5SDimitry Andric 
6325f757f3fSDimitry Andric   // Skip over the EOF token, flagging end of previous input for incremental
6335f757f3fSDimitry Andric   // processing
6345f757f3fSDimitry Andric   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
6355f757f3fSDimitry Andric     ConsumeToken();
6365f757f3fSDimitry Andric 
6370b57cec5SDimitry Andric   Result = nullptr;
6380b57cec5SDimitry Andric   switch (Tok.getKind()) {
6390b57cec5SDimitry Andric   case tok::annot_pragma_unused:
6400b57cec5SDimitry Andric     HandlePragmaUnused();
6410b57cec5SDimitry Andric     return false;
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   case tok::kw_export:
6440b57cec5SDimitry Andric     switch (NextToken().getKind()) {
6450b57cec5SDimitry Andric     case tok::kw_module:
6460b57cec5SDimitry Andric       goto module_decl;
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric     // Note: no need to handle kw_import here. We only form kw_import under
64906c3fb27SDimitry Andric     // the Standard C++ Modules, and in that case 'export import' is parsed as
65006c3fb27SDimitry Andric     // an export-declaration containing an import-declaration.
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric     // Recognize context-sensitive C++20 'export module' and 'export import'
6530b57cec5SDimitry Andric     // declarations.
6540b57cec5SDimitry Andric     case tok::identifier: {
6550b57cec5SDimitry Andric       IdentifierInfo *II = NextToken().getIdentifierInfo();
6560b57cec5SDimitry Andric       if ((II == Ident_module || II == Ident_import) &&
6570b57cec5SDimitry Andric           GetLookAheadToken(2).isNot(tok::coloncolon)) {
6580b57cec5SDimitry Andric         if (II == Ident_module)
6590b57cec5SDimitry Andric           goto module_decl;
6600b57cec5SDimitry Andric         else
6610b57cec5SDimitry Andric           goto import_decl;
6620b57cec5SDimitry Andric       }
6630b57cec5SDimitry Andric       break;
6640b57cec5SDimitry Andric     }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric     default:
6670b57cec5SDimitry Andric       break;
6680b57cec5SDimitry Andric     }
6690b57cec5SDimitry Andric     break;
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   case tok::kw_module:
6720b57cec5SDimitry Andric   module_decl:
67381ad6265SDimitry Andric     Result = ParseModuleDecl(ImportState);
6740b57cec5SDimitry Andric     return false;
6750b57cec5SDimitry Andric 
67681ad6265SDimitry Andric   case tok::kw_import:
6770b57cec5SDimitry Andric   import_decl: {
67881ad6265SDimitry Andric     Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
6790b57cec5SDimitry Andric     Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
6800b57cec5SDimitry Andric     return false;
6810b57cec5SDimitry Andric   }
6820b57cec5SDimitry Andric 
683753f127fSDimitry Andric   case tok::annot_module_include: {
684753f127fSDimitry Andric     auto Loc = Tok.getLocation();
685753f127fSDimitry Andric     Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
686753f127fSDimitry Andric     // FIXME: We need a better way to disambiguate C++ clang modules and
687753f127fSDimitry Andric     // standard C++ modules.
688753f127fSDimitry Andric     if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
689*0fca6ea1SDimitry Andric       Actions.ActOnAnnotModuleInclude(Loc, Mod);
690753f127fSDimitry Andric     else {
691753f127fSDimitry Andric       DeclResult Import =
692753f127fSDimitry Andric           Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
693753f127fSDimitry Andric       Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
694753f127fSDimitry Andric       Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
695753f127fSDimitry Andric     }
6960b57cec5SDimitry Andric     ConsumeAnnotationToken();
6970b57cec5SDimitry Andric     return false;
698753f127fSDimitry Andric   }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   case tok::annot_module_begin:
701*0fca6ea1SDimitry Andric     Actions.ActOnAnnotModuleBegin(
702*0fca6ea1SDimitry Andric         Tok.getLocation(),
703*0fca6ea1SDimitry Andric         reinterpret_cast<Module *>(Tok.getAnnotationValue()));
7040b57cec5SDimitry Andric     ConsumeAnnotationToken();
70581ad6265SDimitry Andric     ImportState = Sema::ModuleImportState::NotACXX20Module;
7060b57cec5SDimitry Andric     return false;
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   case tok::annot_module_end:
709*0fca6ea1SDimitry Andric     Actions.ActOnAnnotModuleEnd(
710*0fca6ea1SDimitry Andric         Tok.getLocation(),
711*0fca6ea1SDimitry Andric         reinterpret_cast<Module *>(Tok.getAnnotationValue()));
7120b57cec5SDimitry Andric     ConsumeAnnotationToken();
71381ad6265SDimitry Andric     ImportState = Sema::ModuleImportState::NotACXX20Module;
7140b57cec5SDimitry Andric     return false;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   case tok::eof:
71706c3fb27SDimitry Andric   case tok::annot_repl_input_end:
7185ffd83dbSDimitry Andric     // Check whether -fmax-tokens= was reached.
7195ffd83dbSDimitry Andric     if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
7205ffd83dbSDimitry Andric       PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
7215ffd83dbSDimitry Andric           << PP.getTokenCount() << PP.getMaxTokens();
7225ffd83dbSDimitry Andric       SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
7235ffd83dbSDimitry Andric       if (OverrideLoc.isValid()) {
7245ffd83dbSDimitry Andric         PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
7255ffd83dbSDimitry Andric       }
7265ffd83dbSDimitry Andric     }
7275ffd83dbSDimitry Andric 
7280b57cec5SDimitry Andric     // Late template parsing can begin.
7295ffd83dbSDimitry Andric     Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
7300b57cec5SDimitry Andric     Actions.ActOnEndOfTranslationUnit();
7310b57cec5SDimitry Andric     //else don't tell Sema that we ended parsing: more input might come.
7320b57cec5SDimitry Andric     return true;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric   case tok::identifier:
7350b57cec5SDimitry Andric     // C++2a [basic.link]p3:
7360b57cec5SDimitry Andric     //   A token sequence beginning with 'export[opt] module' or
7370b57cec5SDimitry Andric     //   'export[opt] import' and not immediately followed by '::'
7380b57cec5SDimitry Andric     //   is never interpreted as the declaration of a top-level-declaration.
7390b57cec5SDimitry Andric     if ((Tok.getIdentifierInfo() == Ident_module ||
7400b57cec5SDimitry Andric          Tok.getIdentifierInfo() == Ident_import) &&
7410b57cec5SDimitry Andric         NextToken().isNot(tok::coloncolon)) {
7420b57cec5SDimitry Andric       if (Tok.getIdentifierInfo() == Ident_module)
7430b57cec5SDimitry Andric         goto module_decl;
7440b57cec5SDimitry Andric       else
7450b57cec5SDimitry Andric         goto import_decl;
7460b57cec5SDimitry Andric     }
7470b57cec5SDimitry Andric     break;
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   default:
7500b57cec5SDimitry Andric     break;
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
753bdd1243dSDimitry Andric   ParsedAttributes DeclAttrs(AttrFactory);
754bdd1243dSDimitry Andric   ParsedAttributes DeclSpecAttrs(AttrFactory);
755bdd1243dSDimitry Andric   // GNU attributes are applied to the declaration specification while the
756bdd1243dSDimitry Andric   // standard attributes are applied to the declaration.  We parse the two
757bdd1243dSDimitry Andric   // attribute sets into different containters so we can apply them during
758bdd1243dSDimitry Andric   // the regular parsing process.
759bdd1243dSDimitry Andric   while (MaybeParseCXX11Attributes(DeclAttrs) ||
760bdd1243dSDimitry Andric          MaybeParseGNUAttributes(DeclSpecAttrs))
761bdd1243dSDimitry Andric     ;
7620b57cec5SDimitry Andric 
763bdd1243dSDimitry Andric   Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
76481ad6265SDimitry Andric   // An empty Result might mean a line with ';' or some parsing error, ignore
76581ad6265SDimitry Andric   // it.
76681ad6265SDimitry Andric   if (Result) {
76781ad6265SDimitry Andric     if (ImportState == Sema::ModuleImportState::FirstDecl)
76881ad6265SDimitry Andric       // First decl was not modular.
76981ad6265SDimitry Andric       ImportState = Sema::ModuleImportState::NotACXX20Module;
77081ad6265SDimitry Andric     else if (ImportState == Sema::ModuleImportState::ImportAllowed)
77181ad6265SDimitry Andric       // Non-imports disallow further imports.
77281ad6265SDimitry Andric       ImportState = Sema::ModuleImportState::ImportFinished;
773bdd1243dSDimitry Andric     else if (ImportState ==
774bdd1243dSDimitry Andric              Sema::ModuleImportState::PrivateFragmentImportAllowed)
775bdd1243dSDimitry Andric       // Non-imports disallow further imports.
776bdd1243dSDimitry Andric       ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
77781ad6265SDimitry Andric   }
7780b57cec5SDimitry Andric   return false;
7790b57cec5SDimitry Andric }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric /// ParseExternalDeclaration:
7820b57cec5SDimitry Andric ///
78381ad6265SDimitry Andric /// The `Attrs` that are passed in are C++11 attributes and appertain to the
78481ad6265SDimitry Andric /// declaration.
78581ad6265SDimitry Andric ///
7860b57cec5SDimitry Andric ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
7870b57cec5SDimitry Andric ///         function-definition
7880b57cec5SDimitry Andric ///         declaration
7890b57cec5SDimitry Andric /// [GNU]   asm-definition
7900b57cec5SDimitry Andric /// [GNU]   __extension__ external-declaration
7910b57cec5SDimitry Andric /// [OBJC]  objc-class-definition
7920b57cec5SDimitry Andric /// [OBJC]  objc-class-declaration
7930b57cec5SDimitry Andric /// [OBJC]  objc-alias-declaration
7940b57cec5SDimitry Andric /// [OBJC]  objc-protocol-definition
7950b57cec5SDimitry Andric /// [OBJC]  objc-method-definition
7960b57cec5SDimitry Andric /// [OBJC]  @end
7970b57cec5SDimitry Andric /// [C++]   linkage-specification
7980b57cec5SDimitry Andric /// [GNU] asm-definition:
7990b57cec5SDimitry Andric ///         simple-asm-expr ';'
8000b57cec5SDimitry Andric /// [C++11] empty-declaration
8010b57cec5SDimitry Andric /// [C++11] attribute-declaration
8020b57cec5SDimitry Andric ///
8030b57cec5SDimitry Andric /// [C++11] empty-declaration:
8040b57cec5SDimitry Andric ///           ';'
8050b57cec5SDimitry Andric ///
8060b57cec5SDimitry Andric /// [C++0x/GNU] 'extern' 'template' declaration
8070b57cec5SDimitry Andric ///
80806c3fb27SDimitry Andric /// [C++20] module-import-declaration
8090b57cec5SDimitry Andric ///
810bdd1243dSDimitry Andric Parser::DeclGroupPtrTy
ParseExternalDeclaration(ParsedAttributes & Attrs,ParsedAttributes & DeclSpecAttrs,ParsingDeclSpec * DS)811bdd1243dSDimitry Andric Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
812bdd1243dSDimitry Andric                                  ParsedAttributes &DeclSpecAttrs,
8130b57cec5SDimitry Andric                                  ParsingDeclSpec *DS) {
8145ffd83dbSDimitry Andric   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
8150b57cec5SDimitry Andric   ParenBraceBracketBalancer BalancerRAIIObj(*this);
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   if (PP.isCodeCompletionReached()) {
8180b57cec5SDimitry Andric     cutOffParsing();
8190b57cec5SDimitry Andric     return nullptr;
8200b57cec5SDimitry Andric   }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   Decl *SingleDecl = nullptr;
8230b57cec5SDimitry Andric   switch (Tok.getKind()) {
8240b57cec5SDimitry Andric   case tok::annot_pragma_vis:
8250b57cec5SDimitry Andric     HandlePragmaVisibility();
8260b57cec5SDimitry Andric     return nullptr;
8270b57cec5SDimitry Andric   case tok::annot_pragma_pack:
8280b57cec5SDimitry Andric     HandlePragmaPack();
8290b57cec5SDimitry Andric     return nullptr;
8300b57cec5SDimitry Andric   case tok::annot_pragma_msstruct:
8310b57cec5SDimitry Andric     HandlePragmaMSStruct();
8320b57cec5SDimitry Andric     return nullptr;
8330b57cec5SDimitry Andric   case tok::annot_pragma_align:
8340b57cec5SDimitry Andric     HandlePragmaAlign();
8350b57cec5SDimitry Andric     return nullptr;
8360b57cec5SDimitry Andric   case tok::annot_pragma_weak:
8370b57cec5SDimitry Andric     HandlePragmaWeak();
8380b57cec5SDimitry Andric     return nullptr;
8390b57cec5SDimitry Andric   case tok::annot_pragma_weakalias:
8400b57cec5SDimitry Andric     HandlePragmaWeakAlias();
8410b57cec5SDimitry Andric     return nullptr;
8420b57cec5SDimitry Andric   case tok::annot_pragma_redefine_extname:
8430b57cec5SDimitry Andric     HandlePragmaRedefineExtname();
8440b57cec5SDimitry Andric     return nullptr;
8450b57cec5SDimitry Andric   case tok::annot_pragma_fp_contract:
8460b57cec5SDimitry Andric     HandlePragmaFPContract();
8470b57cec5SDimitry Andric     return nullptr;
8480b57cec5SDimitry Andric   case tok::annot_pragma_fenv_access:
849349cc55cSDimitry Andric   case tok::annot_pragma_fenv_access_ms:
8500b57cec5SDimitry Andric     HandlePragmaFEnvAccess();
8510b57cec5SDimitry Andric     return nullptr;
852e8d8bef9SDimitry Andric   case tok::annot_pragma_fenv_round:
853e8d8bef9SDimitry Andric     HandlePragmaFEnvRound();
854e8d8bef9SDimitry Andric     return nullptr;
8555f757f3fSDimitry Andric   case tok::annot_pragma_cx_limited_range:
8565f757f3fSDimitry Andric     HandlePragmaCXLimitedRange();
8575f757f3fSDimitry Andric     return nullptr;
8585ffd83dbSDimitry Andric   case tok::annot_pragma_float_control:
8595ffd83dbSDimitry Andric     HandlePragmaFloatControl();
8605ffd83dbSDimitry Andric     return nullptr;
8610b57cec5SDimitry Andric   case tok::annot_pragma_fp:
8620b57cec5SDimitry Andric     HandlePragmaFP();
8630b57cec5SDimitry Andric     break;
8640b57cec5SDimitry Andric   case tok::annot_pragma_opencl_extension:
8650b57cec5SDimitry Andric     HandlePragmaOpenCLExtension();
8660b57cec5SDimitry Andric     return nullptr;
867fe6060f1SDimitry Andric   case tok::annot_attr_openmp:
8680b57cec5SDimitry Andric   case tok::annot_pragma_openmp: {
8690b57cec5SDimitry Andric     AccessSpecifier AS = AS_none;
87081ad6265SDimitry Andric     return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
8710b57cec5SDimitry Andric   }
8725f757f3fSDimitry Andric   case tok::annot_pragma_openacc:
8735f757f3fSDimitry Andric     return ParseOpenACCDirectiveDecl();
8740b57cec5SDimitry Andric   case tok::annot_pragma_ms_pointers_to_members:
8750b57cec5SDimitry Andric     HandlePragmaMSPointersToMembers();
8760b57cec5SDimitry Andric     return nullptr;
8770b57cec5SDimitry Andric   case tok::annot_pragma_ms_vtordisp:
8780b57cec5SDimitry Andric     HandlePragmaMSVtorDisp();
8790b57cec5SDimitry Andric     return nullptr;
8800b57cec5SDimitry Andric   case tok::annot_pragma_ms_pragma:
8810b57cec5SDimitry Andric     HandlePragmaMSPragma();
8820b57cec5SDimitry Andric     return nullptr;
8830b57cec5SDimitry Andric   case tok::annot_pragma_dump:
8840b57cec5SDimitry Andric     HandlePragmaDump();
8850b57cec5SDimitry Andric     return nullptr;
8860b57cec5SDimitry Andric   case tok::annot_pragma_attribute:
8870b57cec5SDimitry Andric     HandlePragmaAttribute();
8880b57cec5SDimitry Andric     return nullptr;
8890b57cec5SDimitry Andric   case tok::semi:
8900b57cec5SDimitry Andric     // Either a C++11 empty-declaration or attribute-declaration.
8910b57cec5SDimitry Andric     SingleDecl =
89281ad6265SDimitry Andric         Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
8930b57cec5SDimitry Andric     ConsumeExtraSemi(OutsideFunction);
8940b57cec5SDimitry Andric     break;
8950b57cec5SDimitry Andric   case tok::r_brace:
8960b57cec5SDimitry Andric     Diag(Tok, diag::err_extraneous_closing_brace);
8970b57cec5SDimitry Andric     ConsumeBrace();
8980b57cec5SDimitry Andric     return nullptr;
8990b57cec5SDimitry Andric   case tok::eof:
9000b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_external_declaration);
9010b57cec5SDimitry Andric     return nullptr;
9020b57cec5SDimitry Andric   case tok::kw___extension__: {
9030b57cec5SDimitry Andric     // __extension__ silences extension warnings in the subexpression.
9040b57cec5SDimitry Andric     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
9050b57cec5SDimitry Andric     ConsumeToken();
906bdd1243dSDimitry Andric     return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
9070b57cec5SDimitry Andric   }
9080b57cec5SDimitry Andric   case tok::kw_asm: {
90981ad6265SDimitry Andric     ProhibitAttributes(Attrs);
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric     SourceLocation StartLoc = Tok.getLocation();
9120b57cec5SDimitry Andric     SourceLocation EndLoc;
9130b57cec5SDimitry Andric 
914480093f4SDimitry Andric     ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric     // Check if GNU-style InlineAsm is disabled.
9170b57cec5SDimitry Andric     // Empty asm string is allowed because it will not introduce
9180b57cec5SDimitry Andric     // any assembly code.
9190b57cec5SDimitry Andric     if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
9200b57cec5SDimitry Andric       const auto *SL = cast<StringLiteral>(Result.get());
9210b57cec5SDimitry Andric       if (!SL->getString().trim().empty())
9220b57cec5SDimitry Andric         Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
9230b57cec5SDimitry Andric     }
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric     ExpectAndConsume(tok::semi, diag::err_expected_after,
9260b57cec5SDimitry Andric                      "top-level asm block");
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric     if (Result.isInvalid())
9290b57cec5SDimitry Andric       return nullptr;
9300b57cec5SDimitry Andric     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
9310b57cec5SDimitry Andric     break;
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric   case tok::at:
934bdd1243dSDimitry Andric     return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
9350b57cec5SDimitry Andric   case tok::minus:
9360b57cec5SDimitry Andric   case tok::plus:
9370b57cec5SDimitry Andric     if (!getLangOpts().ObjC) {
9380b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_external_declaration);
9390b57cec5SDimitry Andric       ConsumeToken();
9400b57cec5SDimitry Andric       return nullptr;
9410b57cec5SDimitry Andric     }
9420b57cec5SDimitry Andric     SingleDecl = ParseObjCMethodDefinition();
9430b57cec5SDimitry Andric     break;
9440b57cec5SDimitry Andric   case tok::code_completion:
945fe6060f1SDimitry Andric     cutOffParsing();
9460b57cec5SDimitry Andric     if (CurParsedObjCImpl) {
9470b57cec5SDimitry Andric       // Code-complete Objective-C methods even without leading '-'/'+' prefix.
948*0fca6ea1SDimitry Andric       Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
949*0fca6ea1SDimitry Andric           getCurScope(),
950bdd1243dSDimitry Andric           /*IsInstanceMethod=*/std::nullopt,
9510b57cec5SDimitry Andric           /*ReturnType=*/nullptr);
9520b57cec5SDimitry Andric     }
9535f757f3fSDimitry Andric 
954*0fca6ea1SDimitry Andric     SemaCodeCompletion::ParserCompletionContext PCC;
9555f757f3fSDimitry Andric     if (CurParsedObjCImpl) {
956*0fca6ea1SDimitry Andric       PCC = SemaCodeCompletion::PCC_ObjCImplementation;
9575f757f3fSDimitry Andric     } else if (PP.isIncrementalProcessingEnabled()) {
958*0fca6ea1SDimitry Andric       PCC = SemaCodeCompletion::PCC_TopLevelOrExpression;
9595f757f3fSDimitry Andric     } else {
960*0fca6ea1SDimitry Andric       PCC = SemaCodeCompletion::PCC_Namespace;
9615f757f3fSDimitry Andric     };
962*0fca6ea1SDimitry Andric     Actions.CodeCompletion().CodeCompleteOrdinaryName(getCurScope(), PCC);
9630b57cec5SDimitry Andric     return nullptr;
96481ad6265SDimitry Andric   case tok::kw_import: {
96581ad6265SDimitry Andric     Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
96681ad6265SDimitry Andric     if (getLangOpts().CPlusPlusModules) {
96781ad6265SDimitry Andric       llvm_unreachable("not expecting a c++20 import here");
96881ad6265SDimitry Andric       ProhibitAttributes(Attrs);
96981ad6265SDimitry Andric     }
97081ad6265SDimitry Andric     SingleDecl = ParseModuleImport(SourceLocation(), IS);
97181ad6265SDimitry Andric   } break;
9720b57cec5SDimitry Andric   case tok::kw_export:
973*0fca6ea1SDimitry Andric     if (getLangOpts().CPlusPlusModules || getLangOpts().HLSL) {
97481ad6265SDimitry Andric       ProhibitAttributes(Attrs);
9750b57cec5SDimitry Andric       SingleDecl = ParseExportDeclaration();
9760b57cec5SDimitry Andric       break;
9770b57cec5SDimitry Andric     }
9780b57cec5SDimitry Andric     // This must be 'export template'. Parse it so we can diagnose our lack
9790b57cec5SDimitry Andric     // of support.
980bdd1243dSDimitry Andric     [[fallthrough]];
9810b57cec5SDimitry Andric   case tok::kw_using:
9820b57cec5SDimitry Andric   case tok::kw_namespace:
9830b57cec5SDimitry Andric   case tok::kw_typedef:
9840b57cec5SDimitry Andric   case tok::kw_template:
9850b57cec5SDimitry Andric   case tok::kw_static_assert:
9860b57cec5SDimitry Andric   case tok::kw__Static_assert:
9870b57cec5SDimitry Andric     // A function definition cannot start with any of these keywords.
9880b57cec5SDimitry Andric     {
9890b57cec5SDimitry Andric       SourceLocation DeclEnd;
99081ad6265SDimitry Andric       return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
991bdd1243dSDimitry Andric                               DeclSpecAttrs);
9920b57cec5SDimitry Andric     }
9930b57cec5SDimitry Andric 
994bdd1243dSDimitry Andric   case tok::kw_cbuffer:
995bdd1243dSDimitry Andric   case tok::kw_tbuffer:
996bdd1243dSDimitry Andric     if (getLangOpts().HLSL) {
997bdd1243dSDimitry Andric       SourceLocation DeclEnd;
998bdd1243dSDimitry Andric       return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
999bdd1243dSDimitry Andric                               DeclSpecAttrs);
1000bdd1243dSDimitry Andric     }
1001bdd1243dSDimitry Andric     goto dont_know;
1002bdd1243dSDimitry Andric 
10030b57cec5SDimitry Andric   case tok::kw_static:
10040b57cec5SDimitry Andric     // Parse (then ignore) 'static' prior to a template instantiation. This is
10050b57cec5SDimitry Andric     // a GCC extension that we intentionally do not support.
10060b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
10070b57cec5SDimitry Andric       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
10080b57cec5SDimitry Andric         << 0;
10090b57cec5SDimitry Andric       SourceLocation DeclEnd;
101081ad6265SDimitry Andric       return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1011bdd1243dSDimitry Andric                               DeclSpecAttrs);
10120b57cec5SDimitry Andric     }
10130b57cec5SDimitry Andric     goto dont_know;
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   case tok::kw_inline:
10160b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus) {
10170b57cec5SDimitry Andric       tok::TokenKind NextKind = NextToken().getKind();
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric       // Inline namespaces. Allowed as an extension even in C++03.
10200b57cec5SDimitry Andric       if (NextKind == tok::kw_namespace) {
10210b57cec5SDimitry Andric         SourceLocation DeclEnd;
102281ad6265SDimitry Andric         return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1023bdd1243dSDimitry Andric                                 DeclSpecAttrs);
10240b57cec5SDimitry Andric       }
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric       // Parse (then ignore) 'inline' prior to a template instantiation. This is
10270b57cec5SDimitry Andric       // a GCC extension that we intentionally do not support.
10280b57cec5SDimitry Andric       if (NextKind == tok::kw_template) {
10290b57cec5SDimitry Andric         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
10300b57cec5SDimitry Andric           << 1;
10310b57cec5SDimitry Andric         SourceLocation DeclEnd;
103281ad6265SDimitry Andric         return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1033bdd1243dSDimitry Andric                                 DeclSpecAttrs);
10340b57cec5SDimitry Andric       }
10350b57cec5SDimitry Andric     }
10360b57cec5SDimitry Andric     goto dont_know;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   case tok::kw_extern:
10390b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
10400b57cec5SDimitry Andric       // Extern templates
10410b57cec5SDimitry Andric       SourceLocation ExternLoc = ConsumeToken();
10420b57cec5SDimitry Andric       SourceLocation TemplateLoc = ConsumeToken();
10430b57cec5SDimitry Andric       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
10440b57cec5SDimitry Andric              diag::warn_cxx98_compat_extern_template :
10450b57cec5SDimitry Andric              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
10460b57cec5SDimitry Andric       SourceLocation DeclEnd;
1047*0fca6ea1SDimitry Andric       return ParseExplicitInstantiation(DeclaratorContext::File, ExternLoc,
1048*0fca6ea1SDimitry Andric                                         TemplateLoc, DeclEnd, Attrs);
10490b57cec5SDimitry Andric     }
10500b57cec5SDimitry Andric     goto dont_know;
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   case tok::kw___if_exists:
10530b57cec5SDimitry Andric   case tok::kw___if_not_exists:
10540b57cec5SDimitry Andric     ParseMicrosoftIfExistsExternalDeclaration();
10550b57cec5SDimitry Andric     return nullptr;
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   case tok::kw_module:
10580b57cec5SDimitry Andric     Diag(Tok, diag::err_unexpected_module_decl);
10590b57cec5SDimitry Andric     SkipUntil(tok::semi);
10600b57cec5SDimitry Andric     return nullptr;
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   default:
10630b57cec5SDimitry Andric   dont_know:
10640b57cec5SDimitry Andric     if (Tok.isEditorPlaceholder()) {
10650b57cec5SDimitry Andric       ConsumeToken();
10660b57cec5SDimitry Andric       return nullptr;
10670b57cec5SDimitry Andric     }
10685f757f3fSDimitry Andric     if (getLangOpts().IncrementalExtensions &&
1069bdd1243dSDimitry Andric         !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1070bdd1243dSDimitry Andric       return ParseTopLevelStmtDecl();
1071bdd1243dSDimitry Andric 
10720b57cec5SDimitry Andric     // We can't tell whether this is a function-definition or declaration yet.
1073bdd1243dSDimitry Andric     if (!SingleDecl)
1074bdd1243dSDimitry Andric       return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric   // This routine returns a DeclGroup, if the thing we parsed only contains a
10780b57cec5SDimitry Andric   // single decl, convert it now.
10790b57cec5SDimitry Andric   return Actions.ConvertDeclToDeclGroup(SingleDecl);
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric /// Determine whether the current token, if it occurs after a
10830b57cec5SDimitry Andric /// declarator, continues a declaration or declaration list.
isDeclarationAfterDeclarator()10840b57cec5SDimitry Andric bool Parser::isDeclarationAfterDeclarator() {
10850b57cec5SDimitry Andric   // Check for '= delete' or '= default'
10860b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
10870b57cec5SDimitry Andric     const Token &KW = NextToken();
10880b57cec5SDimitry Andric     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
10890b57cec5SDimitry Andric       return false;
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
10930b57cec5SDimitry Andric     Tok.is(tok::comma) ||           // int X(),  -> not a function def
10940b57cec5SDimitry Andric     Tok.is(tok::semi)  ||           // int X();  -> not a function def
10950b57cec5SDimitry Andric     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
10960b57cec5SDimitry Andric     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
10970b57cec5SDimitry Andric     (getLangOpts().CPlusPlus &&
10980b57cec5SDimitry Andric      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric /// Determine whether the current token, if it occurs after a
11020b57cec5SDimitry Andric /// declarator, indicates the start of a function definition.
isStartOfFunctionDefinition(const ParsingDeclarator & Declarator)11030b57cec5SDimitry Andric bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
11040b57cec5SDimitry Andric   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
11050b57cec5SDimitry Andric   if (Tok.is(tok::l_brace))   // int X() {}
11060b57cec5SDimitry Andric     return true;
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   // Handle K&R C argument lists: int X(f) int f; {}
11090b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus &&
11100b57cec5SDimitry Andric       Declarator.getFunctionTypeInfo().isKNRPrototype())
1111bdd1243dSDimitry Andric     return isDeclarationSpecifier(ImplicitTypenameContext::No);
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
11140b57cec5SDimitry Andric     const Token &KW = NextToken();
11150b57cec5SDimitry Andric     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
11160b57cec5SDimitry Andric   }
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
11190b57cec5SDimitry Andric          Tok.is(tok::kw_try);          // X() try { ... }
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric /// Parse either a function-definition or a declaration.  We can't tell which
11230b57cec5SDimitry Andric /// we have until we read up to the compound-statement in function-definition.
11240b57cec5SDimitry Andric /// TemplateParams, if non-NULL, provides the template parameters when we're
11250b57cec5SDimitry Andric /// parsing a C++ template-declaration.
11260b57cec5SDimitry Andric ///
11270b57cec5SDimitry Andric ///       function-definition: [C99 6.9.1]
11280b57cec5SDimitry Andric ///         decl-specs      declarator declaration-list[opt] compound-statement
11290b57cec5SDimitry Andric /// [C90] function-definition: [C99 6.7.1] - implicit int result
11300b57cec5SDimitry Andric /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
11310b57cec5SDimitry Andric ///
11320b57cec5SDimitry Andric ///       declaration: [C99 6.7]
11330b57cec5SDimitry Andric ///         declaration-specifiers init-declarator-list[opt] ';'
11340b57cec5SDimitry Andric /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
11350b57cec5SDimitry Andric /// [OMP]   threadprivate-directive
11360b57cec5SDimitry Andric /// [OMP]   allocate-directive                         [TODO]
11370b57cec5SDimitry Andric ///
ParseDeclOrFunctionDefInternal(ParsedAttributes & Attrs,ParsedAttributes & DeclSpecAttrs,ParsingDeclSpec & DS,AccessSpecifier AS)113881ad6265SDimitry Andric Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1139bdd1243dSDimitry Andric     ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1140bdd1243dSDimitry Andric     ParsingDeclSpec &DS, AccessSpecifier AS) {
1141bdd1243dSDimitry Andric   // Because we assume that the DeclSpec has not yet been initialised, we simply
1142bdd1243dSDimitry Andric   // overwrite the source range and attribute the provided leading declspec
1143bdd1243dSDimitry Andric   // attributes.
1144bdd1243dSDimitry Andric   assert(DS.getSourceRange().isInvalid() &&
1145bdd1243dSDimitry Andric          "expected uninitialised source range");
1146bdd1243dSDimitry Andric   DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1147bdd1243dSDimitry Andric   DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1148bdd1243dSDimitry Andric   DS.takeAttributesFrom(DeclSpecAttrs);
1149bdd1243dSDimitry Andric 
1150*0fca6ea1SDimitry Andric   ParsedTemplateInfo TemplateInfo;
11510b57cec5SDimitry Andric   MaybeParseMicrosoftAttributes(DS.getAttributes());
11520b57cec5SDimitry Andric   // Parse the common declaration-specifiers piece.
1153*0fca6ea1SDimitry Andric   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
11540b57cec5SDimitry Andric                              DeclSpecContext::DSC_top_level);
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   // If we had a free-standing type definition with a missing semicolon, we
11570b57cec5SDimitry Andric   // may get this far before the problem becomes obvious.
11580b57cec5SDimitry Andric   if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
11590b57cec5SDimitry Andric                                    DS, AS, DeclSpecContext::DSC_top_level))
11600b57cec5SDimitry Andric     return nullptr;
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
11630b57cec5SDimitry Andric   // declaration-specifiers init-declarator-list[opt] ';'
11640b57cec5SDimitry Andric   if (Tok.is(tok::semi)) {
11650b57cec5SDimitry Andric     auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
11660b57cec5SDimitry Andric       assert(DeclSpec::isDeclRep(TKind));
11670b57cec5SDimitry Andric       switch(TKind) {
11680b57cec5SDimitry Andric       case DeclSpec::TST_class:
11690b57cec5SDimitry Andric         return 5;
11700b57cec5SDimitry Andric       case DeclSpec::TST_struct:
11710b57cec5SDimitry Andric         return 6;
11720b57cec5SDimitry Andric       case DeclSpec::TST_union:
11730b57cec5SDimitry Andric         return 5;
11740b57cec5SDimitry Andric       case DeclSpec::TST_enum:
11750b57cec5SDimitry Andric         return 4;
11760b57cec5SDimitry Andric       case DeclSpec::TST_interface:
11770b57cec5SDimitry Andric         return 9;
11780b57cec5SDimitry Andric       default:
11790b57cec5SDimitry Andric         llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
11800b57cec5SDimitry Andric       }
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric     };
11830b57cec5SDimitry Andric     // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
11840b57cec5SDimitry Andric     SourceLocation CorrectLocationForAttributes =
11850b57cec5SDimitry Andric         DeclSpec::isDeclRep(DS.getTypeSpecType())
11860b57cec5SDimitry Andric             ? DS.getTypeSpecTypeLoc().getLocWithOffset(
11870b57cec5SDimitry Andric                   LengthOfTSTToken(DS.getTypeSpecType()))
11880b57cec5SDimitry Andric             : SourceLocation();
118981ad6265SDimitry Andric     ProhibitAttributes(Attrs, CorrectLocationForAttributes);
11900b57cec5SDimitry Andric     ConsumeToken();
11910b57cec5SDimitry Andric     RecordDecl *AnonRecord = nullptr;
119281ad6265SDimitry Andric     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
119381ad6265SDimitry Andric         getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
11940b57cec5SDimitry Andric     DS.complete(TheDecl);
11955f757f3fSDimitry Andric     Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
11960b57cec5SDimitry Andric     if (AnonRecord) {
11970b57cec5SDimitry Andric       Decl* decls[] = {AnonRecord, TheDecl};
11980b57cec5SDimitry Andric       return Actions.BuildDeclaratorGroup(decls);
11990b57cec5SDimitry Andric     }
12000b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(TheDecl);
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12035f757f3fSDimitry Andric   if (DS.hasTagDefinition())
12045f757f3fSDimitry Andric     Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
12055f757f3fSDimitry Andric 
12060b57cec5SDimitry Andric   // ObjC2 allows prefix attributes on class interfaces and protocols.
12070b57cec5SDimitry Andric   // FIXME: This still needs better diagnostics. We should only accept
12080b57cec5SDimitry Andric   // attributes here, no types, etc.
12090b57cec5SDimitry Andric   if (getLangOpts().ObjC && Tok.is(tok::at)) {
12100b57cec5SDimitry Andric     SourceLocation AtLoc = ConsumeToken(); // the "@"
12110b57cec5SDimitry Andric     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
12120b57cec5SDimitry Andric         !Tok.isObjCAtKeyword(tok::objc_protocol) &&
12130b57cec5SDimitry Andric         !Tok.isObjCAtKeyword(tok::objc_implementation)) {
12140b57cec5SDimitry Andric       Diag(Tok, diag::err_objc_unexpected_attr);
12150b57cec5SDimitry Andric       SkipUntil(tok::semi);
12160b57cec5SDimitry Andric       return nullptr;
12170b57cec5SDimitry Andric     }
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric     DS.abort();
122081ad6265SDimitry Andric     DS.takeAttributesFrom(Attrs);
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     const char *PrevSpec = nullptr;
12230b57cec5SDimitry Andric     unsigned DiagID;
12240b57cec5SDimitry Andric     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
12250b57cec5SDimitry Andric                            Actions.getASTContext().getPrintingPolicy()))
12260b57cec5SDimitry Andric       Diag(AtLoc, DiagID) << PrevSpec;
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric     if (Tok.isObjCAtKeyword(tok::objc_protocol))
12290b57cec5SDimitry Andric       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric     if (Tok.isObjCAtKeyword(tok::objc_implementation))
12320b57cec5SDimitry Andric       return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(
12350b57cec5SDimitry Andric             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
12360b57cec5SDimitry Andric   }
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   // If the declspec consisted only of 'extern' and we have a string
12390b57cec5SDimitry Andric   // literal following it, this must be a C++ linkage specifier like
12400b57cec5SDimitry Andric   // 'extern "C"'.
12410b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
12420b57cec5SDimitry Andric       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
12430b57cec5SDimitry Andric       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
124481ad6265SDimitry Andric     ProhibitAttributes(Attrs);
1245e8d8bef9SDimitry Andric     Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
12460b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(TheDecl);
12470b57cec5SDimitry Andric   }
12480b57cec5SDimitry Andric 
1249*0fca6ea1SDimitry Andric   return ParseDeclGroup(DS, DeclaratorContext::File, Attrs, TemplateInfo);
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
ParseDeclarationOrFunctionDefinition(ParsedAttributes & Attrs,ParsedAttributes & DeclSpecAttrs,ParsingDeclSpec * DS,AccessSpecifier AS)125281ad6265SDimitry Andric Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1253bdd1243dSDimitry Andric     ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1254bdd1243dSDimitry Andric     ParsingDeclSpec *DS, AccessSpecifier AS) {
12555f757f3fSDimitry Andric   // Add an enclosing time trace scope for a bunch of small scopes with
12565f757f3fSDimitry Andric   // "EvaluateAsConstExpr".
12575f757f3fSDimitry Andric   llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
12585f757f3fSDimitry Andric     return Tok.getLocation().printToString(
12595f757f3fSDimitry Andric         Actions.getASTContext().getSourceManager());
12605f757f3fSDimitry Andric   });
12615f757f3fSDimitry Andric 
12620b57cec5SDimitry Andric   if (DS) {
1263bdd1243dSDimitry Andric     return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
12640b57cec5SDimitry Andric   } else {
12650b57cec5SDimitry Andric     ParsingDeclSpec PDS(*this);
12660b57cec5SDimitry Andric     // Must temporarily exit the objective-c container scope for
12670b57cec5SDimitry Andric     // parsing c constructs and re-enter objc container scope
12680b57cec5SDimitry Andric     // afterwards.
12690b57cec5SDimitry Andric     ObjCDeclContextSwitch ObjCDC(*this);
12700b57cec5SDimitry Andric 
1271bdd1243dSDimitry Andric     return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
12720b57cec5SDimitry Andric   }
12730b57cec5SDimitry Andric }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric /// ParseFunctionDefinition - We parsed and verified that the specified
12760b57cec5SDimitry Andric /// Declarator is well formed.  If this is a K&R-style function, read the
12770b57cec5SDimitry Andric /// parameters declaration-list, then start the compound-statement.
12780b57cec5SDimitry Andric ///
12790b57cec5SDimitry Andric ///       function-definition: [C99 6.9.1]
12800b57cec5SDimitry Andric ///         decl-specs      declarator declaration-list[opt] compound-statement
12810b57cec5SDimitry Andric /// [C90] function-definition: [C99 6.7.1] - implicit int result
12820b57cec5SDimitry Andric /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
12830b57cec5SDimitry Andric /// [C++] function-definition: [C++ 8.4]
12840b57cec5SDimitry Andric ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
12850b57cec5SDimitry Andric ///         function-body
12860b57cec5SDimitry Andric /// [C++] function-definition: [C++ 8.4]
12870b57cec5SDimitry Andric ///         decl-specifier-seq[opt] declarator function-try-block
12880b57cec5SDimitry Andric ///
ParseFunctionDefinition(ParsingDeclarator & D,const ParsedTemplateInfo & TemplateInfo,LateParsedAttrList * LateParsedAttrs)12890b57cec5SDimitry Andric Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
12900b57cec5SDimitry Andric                                       const ParsedTemplateInfo &TemplateInfo,
12910b57cec5SDimitry Andric                                       LateParsedAttrList *LateParsedAttrs) {
12925f757f3fSDimitry Andric   llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
12935f757f3fSDimitry Andric     return Actions.GetNameForDeclarator(D).getName().getAsString();
12945f757f3fSDimitry Andric   });
12955f757f3fSDimitry Andric 
12960b57cec5SDimitry Andric   // Poison SEH identifiers so they are flagged as illegal in function bodies.
12970b57cec5SDimitry Andric   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
12980b57cec5SDimitry Andric   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
129955e4f9d5SDimitry Andric   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
13000b57cec5SDimitry Andric 
130181ad6265SDimitry Andric   // If this is C89 and the declspecs were completely missing, fudge in an
13020b57cec5SDimitry Andric   // implicit int.  We do this here because this is the only place where
13030b57cec5SDimitry Andric   // declaration-specifiers are completely optional in the grammar.
130481ad6265SDimitry Andric   if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
130581ad6265SDimitry Andric     Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
130681ad6265SDimitry Andric         << D.getDeclSpec().getSourceRange();
13070b57cec5SDimitry Andric     const char *PrevSpec;
13080b57cec5SDimitry Andric     unsigned DiagID;
13090b57cec5SDimitry Andric     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
13100b57cec5SDimitry Andric     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
13110b57cec5SDimitry Andric                                            D.getIdentifierLoc(),
13120b57cec5SDimitry Andric                                            PrevSpec, DiagID,
13130b57cec5SDimitry Andric                                            Policy);
13140b57cec5SDimitry Andric     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
13150b57cec5SDimitry Andric   }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   // If this declaration was formed with a K&R-style identifier list for the
13180b57cec5SDimitry Andric   // arguments, parse declarations for all of the args next.
13190b57cec5SDimitry Andric   // int foo(a,b) int a; float b; {}
13200b57cec5SDimitry Andric   if (FTI.isKNRPrototype())
13210b57cec5SDimitry Andric     ParseKNRParamDeclarations(D);
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric   // We should have either an opening brace or, in a C++ constructor,
13240b57cec5SDimitry Andric   // we may have a colon.
13250b57cec5SDimitry Andric   if (Tok.isNot(tok::l_brace) &&
13260b57cec5SDimitry Andric       (!getLangOpts().CPlusPlus ||
13270b57cec5SDimitry Andric        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
13280b57cec5SDimitry Andric         Tok.isNot(tok::equal)))) {
13290b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_fn_body);
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
13320b57cec5SDimitry Andric     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric     // If we didn't find the '{', bail out.
13350b57cec5SDimitry Andric     if (Tok.isNot(tok::l_brace))
13360b57cec5SDimitry Andric       return nullptr;
13370b57cec5SDimitry Andric   }
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   // Check to make sure that any normal attributes are allowed to be on
13400b57cec5SDimitry Andric   // a definition.  Late parsed attributes are checked at the end.
13410b57cec5SDimitry Andric   if (Tok.isNot(tok::equal)) {
13420b57cec5SDimitry Andric     for (const ParsedAttr &AL : D.getAttributes())
1343fe6060f1SDimitry Andric       if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1344a7dea167SDimitry Andric         Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
13450b57cec5SDimitry Andric   }
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   // In delayed template parsing mode, for function template we consume the
13480b57cec5SDimitry Andric   // tokens and store them for late parsing at the end of the translation unit.
13490b57cec5SDimitry Andric   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
13500b57cec5SDimitry Andric       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
13510b57cec5SDimitry Andric       Actions.canDelayFunctionBody(D)) {
13520b57cec5SDimitry Andric     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
13550b57cec5SDimitry Andric                                    Scope::CompoundStmtScope);
13560b57cec5SDimitry Andric     Scope *ParentScope = getCurScope()->getParent();
13570b57cec5SDimitry Andric 
1358e8d8bef9SDimitry Andric     D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13590b57cec5SDimitry Andric     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
13600b57cec5SDimitry Andric                                         TemplateParameterLists);
13610b57cec5SDimitry Andric     D.complete(DP);
13620b57cec5SDimitry Andric     D.getMutableDeclSpec().abort();
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric     if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
13650b57cec5SDimitry Andric         trySkippingFunctionBody()) {
13660b57cec5SDimitry Andric       BodyScope.Exit();
13670b57cec5SDimitry Andric       return Actions.ActOnSkippedFunctionBody(DP);
13680b57cec5SDimitry Andric     }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric     CachedTokens Toks;
13710b57cec5SDimitry Andric     LexTemplateFunctionForLateParsing(Toks);
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     if (DP) {
13740b57cec5SDimitry Andric       FunctionDecl *FnD = DP->getAsFunction();
13750b57cec5SDimitry Andric       Actions.CheckForFunctionRedefinition(FnD);
13760b57cec5SDimitry Andric       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
13770b57cec5SDimitry Andric     }
13780b57cec5SDimitry Andric     return DP;
13790b57cec5SDimitry Andric   }
13800b57cec5SDimitry Andric   else if (CurParsedObjCImpl &&
13810b57cec5SDimitry Andric            !TemplateInfo.TemplateParams &&
13820b57cec5SDimitry Andric            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
13830b57cec5SDimitry Andric             Tok.is(tok::colon)) &&
13840b57cec5SDimitry Andric       Actions.CurContext->isTranslationUnit()) {
13850b57cec5SDimitry Andric     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
13860b57cec5SDimitry Andric                                    Scope::CompoundStmtScope);
13870b57cec5SDimitry Andric     Scope *ParentScope = getCurScope()->getParent();
13880b57cec5SDimitry Andric 
1389e8d8bef9SDimitry Andric     D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13900b57cec5SDimitry Andric     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
13910b57cec5SDimitry Andric                                               MultiTemplateParamsArg());
13920b57cec5SDimitry Andric     D.complete(FuncDecl);
13930b57cec5SDimitry Andric     D.getMutableDeclSpec().abort();
13940b57cec5SDimitry Andric     if (FuncDecl) {
13950b57cec5SDimitry Andric       // Consume the tokens and store them for later parsing.
13960b57cec5SDimitry Andric       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
13970b57cec5SDimitry Andric       CurParsedObjCImpl->HasCFunction = true;
13980b57cec5SDimitry Andric       return FuncDecl;
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric     // FIXME: Should we really fall through here?
14010b57cec5SDimitry Andric   }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Enter a scope for the function body.
14040b57cec5SDimitry Andric   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
14050b57cec5SDimitry Andric                                  Scope::CompoundStmtScope);
14060b57cec5SDimitry Andric 
140781ad6265SDimitry Andric   // Parse function body eagerly if it is either '= delete;' or '= default;' as
140881ad6265SDimitry Andric   // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1409*0fca6ea1SDimitry Andric   StringLiteral *DeletedMessage = nullptr;
141081ad6265SDimitry Andric   Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
141181ad6265SDimitry Andric   SourceLocation KWLoc;
141281ad6265SDimitry Andric   if (TryConsumeToken(tok::equal)) {
141381ad6265SDimitry Andric     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
141481ad6265SDimitry Andric 
141581ad6265SDimitry Andric     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
141681ad6265SDimitry Andric       Diag(KWLoc, getLangOpts().CPlusPlus11
141781ad6265SDimitry Andric                       ? diag::warn_cxx98_compat_defaulted_deleted_function
141881ad6265SDimitry Andric                       : diag::ext_defaulted_deleted_function)
141981ad6265SDimitry Andric           << 1 /* deleted */;
142081ad6265SDimitry Andric       BodyKind = Sema::FnBodyKind::Delete;
1421*0fca6ea1SDimitry Andric       DeletedMessage = ParseCXXDeletedFunctionMessage();
142281ad6265SDimitry Andric     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
142381ad6265SDimitry Andric       Diag(KWLoc, getLangOpts().CPlusPlus11
142481ad6265SDimitry Andric                       ? diag::warn_cxx98_compat_defaulted_deleted_function
142581ad6265SDimitry Andric                       : diag::ext_defaulted_deleted_function)
142681ad6265SDimitry Andric           << 0 /* defaulted */;
142781ad6265SDimitry Andric       BodyKind = Sema::FnBodyKind::Default;
142881ad6265SDimitry Andric     } else {
142981ad6265SDimitry Andric       llvm_unreachable("function definition after = not 'delete' or 'default'");
143081ad6265SDimitry Andric     }
143181ad6265SDimitry Andric 
143281ad6265SDimitry Andric     if (Tok.is(tok::comma)) {
143381ad6265SDimitry Andric       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
143481ad6265SDimitry Andric           << (BodyKind == Sema::FnBodyKind::Delete);
143581ad6265SDimitry Andric       SkipUntil(tok::semi);
143681ad6265SDimitry Andric     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
143781ad6265SDimitry Andric                                 BodyKind == Sema::FnBodyKind::Delete
143881ad6265SDimitry Andric                                     ? "delete"
143981ad6265SDimitry Andric                                     : "default")) {
144081ad6265SDimitry Andric       SkipUntil(tok::semi);
144181ad6265SDimitry Andric     }
144281ad6265SDimitry Andric   }
144381ad6265SDimitry Andric 
1444*0fca6ea1SDimitry Andric   Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1445*0fca6ea1SDimitry Andric 
14460b57cec5SDimitry Andric   // Tell the actions module that we have entered a function definition with the
14470b57cec5SDimitry Andric   // specified Declarator for the function.
1448*0fca6ea1SDimitry Andric   SkipBodyInfo SkipBody;
14490b57cec5SDimitry Andric   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
14500b57cec5SDimitry Andric                                               TemplateInfo.TemplateParams
14510b57cec5SDimitry Andric                                                   ? *TemplateInfo.TemplateParams
14520b57cec5SDimitry Andric                                                   : MultiTemplateParamsArg(),
145381ad6265SDimitry Andric                                               &SkipBody, BodyKind);
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   if (SkipBody.ShouldSkip) {
145681ad6265SDimitry Andric     // Do NOT enter SkipFunctionBody if we already consumed the tokens.
145781ad6265SDimitry Andric     if (BodyKind == Sema::FnBodyKind::Other)
14580b57cec5SDimitry Andric       SkipFunctionBody();
145981ad6265SDimitry Andric 
146006c3fb27SDimitry Andric     // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
146106c3fb27SDimitry Andric     // and it would be popped in ActOnFinishFunctionBody.
146206c3fb27SDimitry Andric     // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
146306c3fb27SDimitry Andric     //
146406c3fb27SDimitry Andric     // Do not call PopExpressionEvaluationContext() if it is a lambda because
146506c3fb27SDimitry Andric     // one is already popped when finishing the lambda in BuildLambdaExpr().
146606c3fb27SDimitry Andric     //
146706c3fb27SDimitry Andric     // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
146806c3fb27SDimitry Andric     // and PopExpressionEvaluationContext().
146906c3fb27SDimitry Andric     if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
147006c3fb27SDimitry Andric       Actions.PopExpressionEvaluationContext();
14710b57cec5SDimitry Andric     return Res;
14720b57cec5SDimitry Andric   }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   // Break out of the ParsingDeclarator context before we parse the body.
14750b57cec5SDimitry Andric   D.complete(Res);
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   // Break out of the ParsingDeclSpec context, too.  This const_cast is
14780b57cec5SDimitry Andric   // safe because we're always the sole owner.
14790b57cec5SDimitry Andric   D.getMutableDeclSpec().abort();
14800b57cec5SDimitry Andric 
148181ad6265SDimitry Andric   if (BodyKind != Sema::FnBodyKind::Other) {
1482*0fca6ea1SDimitry Andric     Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
148381ad6265SDimitry Andric     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
148481ad6265SDimitry Andric     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
148581ad6265SDimitry Andric     return Res;
148681ad6265SDimitry Andric   }
148781ad6265SDimitry Andric 
148855e4f9d5SDimitry Andric   // With abbreviated function templates - we need to explicitly add depth to
148955e4f9d5SDimitry Andric   // account for the implicit template parameter list induced by the template.
14905f757f3fSDimitry Andric   if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
14915f757f3fSDimitry Andric       Template && Template->isAbbreviated() &&
149255e4f9d5SDimitry Andric       Template->getTemplateParameters()->getParam(0)->isImplicit())
149355e4f9d5SDimitry Andric     // First template parameter is implicit - meaning no explicit template
149455e4f9d5SDimitry Andric     // parameter list was specified.
149555e4f9d5SDimitry Andric     CurTemplateDepthTracker.addDepth(1);
149655e4f9d5SDimitry Andric 
14970b57cec5SDimitry Andric   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
14980b57cec5SDimitry Andric       trySkippingFunctionBody()) {
14990b57cec5SDimitry Andric     BodyScope.Exit();
15000b57cec5SDimitry Andric     Actions.ActOnSkippedFunctionBody(Res);
15010b57cec5SDimitry Andric     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
15020b57cec5SDimitry Andric   }
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric   if (Tok.is(tok::kw_try))
15050b57cec5SDimitry Andric     return ParseFunctionTryBlock(Res, BodyScope);
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   // If we have a colon, then we're probably parsing a C++
15080b57cec5SDimitry Andric   // ctor-initializer.
15090b57cec5SDimitry Andric   if (Tok.is(tok::colon)) {
15100b57cec5SDimitry Andric     ParseConstructorInitializer(Res);
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric     // Recover from error.
15130b57cec5SDimitry Andric     if (!Tok.is(tok::l_brace)) {
15140b57cec5SDimitry Andric       BodyScope.Exit();
15150b57cec5SDimitry Andric       Actions.ActOnFinishFunctionBody(Res, nullptr);
15160b57cec5SDimitry Andric       return Res;
15170b57cec5SDimitry Andric     }
15180b57cec5SDimitry Andric   } else
15190b57cec5SDimitry Andric     Actions.ActOnDefaultCtorInitializers(Res);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   // Late attributes are parsed in the same scope as the function body.
15220b57cec5SDimitry Andric   if (LateParsedAttrs)
15230b57cec5SDimitry Andric     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   return ParseFunctionStatementBody(Res, BodyScope);
15260b57cec5SDimitry Andric }
15270b57cec5SDimitry Andric 
SkipFunctionBody()15280b57cec5SDimitry Andric void Parser::SkipFunctionBody() {
15290b57cec5SDimitry Andric   if (Tok.is(tok::equal)) {
15300b57cec5SDimitry Andric     SkipUntil(tok::semi);
15310b57cec5SDimitry Andric     return;
15320b57cec5SDimitry Andric   }
15330b57cec5SDimitry Andric 
15340b57cec5SDimitry Andric   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
15350b57cec5SDimitry Andric   if (IsFunctionTryBlock)
15360b57cec5SDimitry Andric     ConsumeToken();
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric   CachedTokens Skipped;
15390b57cec5SDimitry Andric   if (ConsumeAndStoreFunctionPrologue(Skipped))
15400b57cec5SDimitry Andric     SkipMalformedDecl();
15410b57cec5SDimitry Andric   else {
15420b57cec5SDimitry Andric     SkipUntil(tok::r_brace);
15430b57cec5SDimitry Andric     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
15440b57cec5SDimitry Andric       SkipUntil(tok::l_brace);
15450b57cec5SDimitry Andric       SkipUntil(tok::r_brace);
15460b57cec5SDimitry Andric     }
15470b57cec5SDimitry Andric   }
15480b57cec5SDimitry Andric }
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
15510b57cec5SDimitry Andric /// types for a function with a K&R-style identifier list for arguments.
ParseKNRParamDeclarations(Declarator & D)15520b57cec5SDimitry Andric void Parser::ParseKNRParamDeclarations(Declarator &D) {
15530b57cec5SDimitry Andric   // We know that the top-level of this declarator is a function.
15540b57cec5SDimitry Andric   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   // Enter function-declaration scope, limiting any declarators to the
15570b57cec5SDimitry Andric   // function prototype scope, including parameter declarators.
15580b57cec5SDimitry Andric   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
15590b57cec5SDimitry Andric                             Scope::FunctionDeclarationScope | Scope::DeclScope);
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric   // Read all the argument declarations.
1562bdd1243dSDimitry Andric   while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
15630b57cec5SDimitry Andric     SourceLocation DSStart = Tok.getLocation();
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric     // Parse the common declaration-specifiers piece.
15660b57cec5SDimitry Andric     DeclSpec DS(AttrFactory);
1567*0fca6ea1SDimitry Andric     ParsedTemplateInfo TemplateInfo;
1568*0fca6ea1SDimitry Andric     ParseDeclarationSpecifiers(DS, TemplateInfo);
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
15710b57cec5SDimitry Andric     // least one declarator'.
15720b57cec5SDimitry Andric     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
15730b57cec5SDimitry Andric     // the declarations though.  It's trivial to ignore them, really hard to do
15740b57cec5SDimitry Andric     // anything else with them.
15750b57cec5SDimitry Andric     if (TryConsumeToken(tok::semi)) {
15760b57cec5SDimitry Andric       Diag(DSStart, diag::err_declaration_does_not_declare_param);
15770b57cec5SDimitry Andric       continue;
15780b57cec5SDimitry Andric     }
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
15810b57cec5SDimitry Andric     // than register.
15820b57cec5SDimitry Andric     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
15830b57cec5SDimitry Andric         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
15840b57cec5SDimitry Andric       Diag(DS.getStorageClassSpecLoc(),
15850b57cec5SDimitry Andric            diag::err_invalid_storage_class_in_func_decl);
15860b57cec5SDimitry Andric       DS.ClearStorageClassSpecs();
15870b57cec5SDimitry Andric     }
15880b57cec5SDimitry Andric     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
15890b57cec5SDimitry Andric       Diag(DS.getThreadStorageClassSpecLoc(),
15900b57cec5SDimitry Andric            diag::err_invalid_storage_class_in_func_decl);
15910b57cec5SDimitry Andric       DS.ClearStorageClassSpecs();
15920b57cec5SDimitry Andric     }
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric     // Parse the first declarator attached to this declspec.
159581ad6265SDimitry Andric     Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
159681ad6265SDimitry Andric                               DeclaratorContext::KNRTypeList);
15970b57cec5SDimitry Andric     ParseDeclarator(ParmDeclarator);
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric     // Handle the full declarator list.
160004eeddc0SDimitry Andric     while (true) {
16010b57cec5SDimitry Andric       // If attributes are present, parse them.
16020b57cec5SDimitry Andric       MaybeParseGNUAttributes(ParmDeclarator);
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric       // Ask the actions module to compute the type for this declarator.
16050b57cec5SDimitry Andric       Decl *Param =
16060b57cec5SDimitry Andric         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric       if (Param &&
16090b57cec5SDimitry Andric           // A missing identifier has already been diagnosed.
16100b57cec5SDimitry Andric           ParmDeclarator.getIdentifier()) {
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric         // Scan the argument list looking for the correct param to apply this
16130b57cec5SDimitry Andric         // type.
16140b57cec5SDimitry Andric         for (unsigned i = 0; ; ++i) {
16150b57cec5SDimitry Andric           // C99 6.9.1p6: those declarators shall declare only identifiers from
16160b57cec5SDimitry Andric           // the identifier list.
16170b57cec5SDimitry Andric           if (i == FTI.NumParams) {
16180b57cec5SDimitry Andric             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
16190b57cec5SDimitry Andric               << ParmDeclarator.getIdentifier();
16200b57cec5SDimitry Andric             break;
16210b57cec5SDimitry Andric           }
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
16240b57cec5SDimitry Andric             // Reject redefinitions of parameters.
16250b57cec5SDimitry Andric             if (FTI.Params[i].Param) {
16260b57cec5SDimitry Andric               Diag(ParmDeclarator.getIdentifierLoc(),
16270b57cec5SDimitry Andric                    diag::err_param_redefinition)
16280b57cec5SDimitry Andric                  << ParmDeclarator.getIdentifier();
16290b57cec5SDimitry Andric             } else {
16300b57cec5SDimitry Andric               FTI.Params[i].Param = Param;
16310b57cec5SDimitry Andric             }
16320b57cec5SDimitry Andric             break;
16330b57cec5SDimitry Andric           }
16340b57cec5SDimitry Andric         }
16350b57cec5SDimitry Andric       }
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric       // If we don't have a comma, it is either the end of the list (a ';') or
16380b57cec5SDimitry Andric       // an error, bail out.
16390b57cec5SDimitry Andric       if (Tok.isNot(tok::comma))
16400b57cec5SDimitry Andric         break;
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric       ParmDeclarator.clear();
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric       // Consume the comma.
16450b57cec5SDimitry Andric       ParmDeclarator.setCommaLoc(ConsumeToken());
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric       // Parse the next declarator.
16480b57cec5SDimitry Andric       ParseDeclarator(ParmDeclarator);
16490b57cec5SDimitry Andric     }
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric     // Consume ';' and continue parsing.
16520b57cec5SDimitry Andric     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
16530b57cec5SDimitry Andric       continue;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric     // Otherwise recover by skipping to next semi or mandatory function body.
16560b57cec5SDimitry Andric     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
16570b57cec5SDimitry Andric       break;
16580b57cec5SDimitry Andric     TryConsumeToken(tok::semi);
16590b57cec5SDimitry Andric   }
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // The actions module must verify that all arguments were declared.
16620b57cec5SDimitry Andric   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
16630b57cec5SDimitry Andric }
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
16670b57cec5SDimitry Andric /// allowed to be a wide string, and is not subject to character translation.
1668480093f4SDimitry Andric /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1669480093f4SDimitry Andric /// asm label as opposed to an asm statement, because such a construct does not
1670480093f4SDimitry Andric /// behave well.
16710b57cec5SDimitry Andric ///
16720b57cec5SDimitry Andric /// [GNU] asm-string-literal:
16730b57cec5SDimitry Andric ///         string-literal
16740b57cec5SDimitry Andric ///
ParseAsmStringLiteral(bool ForAsmLabel)1675480093f4SDimitry Andric ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
16760b57cec5SDimitry Andric   if (!isTokenStringLiteral()) {
16770b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_string_literal)
16780b57cec5SDimitry Andric       << /*Source='in...'*/0 << "'asm'";
16790b57cec5SDimitry Andric     return ExprError();
16800b57cec5SDimitry Andric   }
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   ExprResult AsmString(ParseStringLiteralExpression());
16830b57cec5SDimitry Andric   if (!AsmString.isInvalid()) {
16840b57cec5SDimitry Andric     const auto *SL = cast<StringLiteral>(AsmString.get());
168581ad6265SDimitry Andric     if (!SL->isOrdinary()) {
16860b57cec5SDimitry Andric       Diag(Tok, diag::err_asm_operand_wide_string_literal)
16870b57cec5SDimitry Andric         << SL->isWide()
16880b57cec5SDimitry Andric         << SL->getSourceRange();
16890b57cec5SDimitry Andric       return ExprError();
16900b57cec5SDimitry Andric     }
1691480093f4SDimitry Andric     if (ForAsmLabel && SL->getString().empty()) {
1692480093f4SDimitry Andric       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1693480093f4SDimitry Andric           << 2 /* an empty */ << SL->getSourceRange();
1694480093f4SDimitry Andric       return ExprError();
1695480093f4SDimitry Andric     }
16960b57cec5SDimitry Andric   }
16970b57cec5SDimitry Andric   return AsmString;
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric /// ParseSimpleAsm
17010b57cec5SDimitry Andric ///
17020b57cec5SDimitry Andric /// [GNU] simple-asm-expr:
17030b57cec5SDimitry Andric ///         'asm' '(' asm-string-literal ')'
17040b57cec5SDimitry Andric ///
ParseSimpleAsm(bool ForAsmLabel,SourceLocation * EndLoc)1705480093f4SDimitry Andric ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
17060b57cec5SDimitry Andric   assert(Tok.is(tok::kw_asm) && "Not an asm!");
17070b57cec5SDimitry Andric   SourceLocation Loc = ConsumeToken();
17080b57cec5SDimitry Andric 
17095ffd83dbSDimitry Andric   if (isGNUAsmQualifier(Tok)) {
17105ffd83dbSDimitry Andric     // Remove from the end of 'asm' to the end of the asm qualifier.
17110b57cec5SDimitry Andric     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
17120b57cec5SDimitry Andric                              PP.getLocForEndOfToken(Tok.getLocation()));
17135ffd83dbSDimitry Andric     Diag(Tok, diag::err_global_asm_qualifier_ignored)
17145ffd83dbSDimitry Andric         << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
17150b57cec5SDimitry Andric         << FixItHint::CreateRemoval(RemovalRange);
17160b57cec5SDimitry Andric     ConsumeToken();
17170b57cec5SDimitry Andric   }
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   BalancedDelimiterTracker T(*this, tok::l_paren);
17200b57cec5SDimitry Andric   if (T.consumeOpen()) {
17210b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_lparen_after) << "asm";
17220b57cec5SDimitry Andric     return ExprError();
17230b57cec5SDimitry Andric   }
17240b57cec5SDimitry Andric 
1725480093f4SDimitry Andric   ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (!Result.isInvalid()) {
17280b57cec5SDimitry Andric     // Close the paren and get the location of the end bracket
17290b57cec5SDimitry Andric     T.consumeClose();
17300b57cec5SDimitry Andric     if (EndLoc)
17310b57cec5SDimitry Andric       *EndLoc = T.getCloseLocation();
17320b57cec5SDimitry Andric   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
17330b57cec5SDimitry Andric     if (EndLoc)
17340b57cec5SDimitry Andric       *EndLoc = Tok.getLocation();
17350b57cec5SDimitry Andric     ConsumeParen();
17360b57cec5SDimitry Andric   }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   return Result;
17390b57cec5SDimitry Andric }
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric /// Get the TemplateIdAnnotation from the token and put it in the
17420b57cec5SDimitry Andric /// cleanup pool so that it gets destroyed when parsing the current top level
17430b57cec5SDimitry Andric /// declaration is finished.
takeTemplateIdAnnotation(const Token & tok)17440b57cec5SDimitry Andric TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
17450b57cec5SDimitry Andric   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
17460b57cec5SDimitry Andric   TemplateIdAnnotation *
17470b57cec5SDimitry Andric       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
17480b57cec5SDimitry Andric   return Id;
17490b57cec5SDimitry Andric }
17500b57cec5SDimitry Andric 
AnnotateScopeToken(CXXScopeSpec & SS,bool IsNewAnnotation)17510b57cec5SDimitry Andric void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
17520b57cec5SDimitry Andric   // Push the current token back into the token stream (or revert it if it is
17530b57cec5SDimitry Andric   // cached) and use an annotation scope token for current token.
17540b57cec5SDimitry Andric   if (PP.isBacktrackEnabled())
17550b57cec5SDimitry Andric     PP.RevertCachedTokens(1);
17560b57cec5SDimitry Andric   else
17570b57cec5SDimitry Andric     PP.EnterToken(Tok, /*IsReinject=*/true);
17580b57cec5SDimitry Andric   Tok.setKind(tok::annot_cxxscope);
17590b57cec5SDimitry Andric   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
17600b57cec5SDimitry Andric   Tok.setAnnotationRange(SS.getRange());
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   // In case the tokens were cached, have Preprocessor replace them
17630b57cec5SDimitry Andric   // with the annotation token.  We don't need to do this if we've
17640b57cec5SDimitry Andric   // just reverted back to a prior state.
17650b57cec5SDimitry Andric   if (IsNewAnnotation)
17660b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
17670b57cec5SDimitry Andric }
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric /// Attempt to classify the name at the current token position. This may
17700b57cec5SDimitry Andric /// form a type, scope or primary expression annotation, or replace the token
17710b57cec5SDimitry Andric /// with a typo-corrected keyword. This is only appropriate when the current
17720b57cec5SDimitry Andric /// name must refer to an entity which has already been declared.
17730b57cec5SDimitry Andric ///
17740b57cec5SDimitry Andric /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
17750b57cec5SDimitry Andric ///        no typo correction will be performed.
1776bdd1243dSDimitry Andric /// \param AllowImplicitTypename Whether we are in a context where a dependent
1777bdd1243dSDimitry Andric ///        nested-name-specifier without typename is treated as a type (e.g.
1778bdd1243dSDimitry Andric ///        T::type).
17790b57cec5SDimitry Andric Parser::AnnotatedNameKind
TryAnnotateName(CorrectionCandidateCallback * CCC,ImplicitTypenameContext AllowImplicitTypename)1780bdd1243dSDimitry Andric Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1781bdd1243dSDimitry Andric                         ImplicitTypenameContext AllowImplicitTypename) {
17820b57cec5SDimitry Andric   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   const bool EnteringContext = false;
17850b57cec5SDimitry Andric   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   CXXScopeSpec SS;
17880b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus &&
17895ffd83dbSDimitry Andric       ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
179004eeddc0SDimitry Andric                                      /*ObjectHasErrors=*/false,
17915ffd83dbSDimitry Andric                                      EnteringContext))
17920b57cec5SDimitry Andric     return ANK_Error;
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1795bdd1243dSDimitry Andric     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1796bdd1243dSDimitry Andric                                                   AllowImplicitTypename))
17970b57cec5SDimitry Andric       return ANK_Error;
17980b57cec5SDimitry Andric     return ANK_Unresolved;
17990b57cec5SDimitry Andric   }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   IdentifierInfo *Name = Tok.getIdentifierInfo();
18020b57cec5SDimitry Andric   SourceLocation NameLoc = Tok.getLocation();
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   // FIXME: Move the tentative declaration logic into ClassifyName so we can
18050b57cec5SDimitry Andric   // typo-correct to tentatively-declared identifiers.
1806bdd1243dSDimitry Andric   if (isTentativelyDeclared(Name) && SS.isEmpty()) {
18070b57cec5SDimitry Andric     // Identifier has been tentatively declared, and thus cannot be resolved as
18080b57cec5SDimitry Andric     // an expression. Fall back to annotating it as a type.
1809bdd1243dSDimitry Andric     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1810bdd1243dSDimitry Andric                                                   AllowImplicitTypename))
18110b57cec5SDimitry Andric       return ANK_Error;
18120b57cec5SDimitry Andric     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
18130b57cec5SDimitry Andric   }
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   Token Next = NextToken();
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric   // Look up and classify the identifier. We don't perform any typo-correction
18180b57cec5SDimitry Andric   // after a scope specifier, because in general we can't recover from typos
18190b57cec5SDimitry Andric   // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
18200b57cec5SDimitry Andric   // jump back into scope specifier parsing).
1821a7dea167SDimitry Andric   Sema::NameClassification Classification = Actions.ClassifyName(
1822a7dea167SDimitry Andric       getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric   // If name lookup found nothing and we guessed that this was a template name,
18250b57cec5SDimitry Andric   // double-check before committing to that interpretation. C++20 requires that
18260b57cec5SDimitry Andric   // we interpret this as a template-id if it can be, but if it can't be, then
18270b57cec5SDimitry Andric   // this is an error recovery case.
18280b57cec5SDimitry Andric   if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
18290b57cec5SDimitry Andric       isTemplateArgumentList(1) == TPResult::False) {
18300b57cec5SDimitry Andric     // It's not a template-id; re-classify without the '<' as a hint.
18310b57cec5SDimitry Andric     Token FakeNext = Next;
18320b57cec5SDimitry Andric     FakeNext.setKind(tok::unknown);
18330b57cec5SDimitry Andric     Classification =
18340b57cec5SDimitry Andric         Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1835a7dea167SDimitry Andric                              SS.isEmpty() ? CCC : nullptr);
18360b57cec5SDimitry Andric   }
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   switch (Classification.getKind()) {
18390b57cec5SDimitry Andric   case Sema::NC_Error:
18400b57cec5SDimitry Andric     return ANK_Error;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   case Sema::NC_Keyword:
18430b57cec5SDimitry Andric     // The identifier was typo-corrected to a keyword.
18440b57cec5SDimitry Andric     Tok.setIdentifierInfo(Name);
18450b57cec5SDimitry Andric     Tok.setKind(Name->getTokenID());
18460b57cec5SDimitry Andric     PP.TypoCorrectToken(Tok);
18470b57cec5SDimitry Andric     if (SS.isNotEmpty())
18480b57cec5SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
18490b57cec5SDimitry Andric     // We've "annotated" this as a keyword.
18500b57cec5SDimitry Andric     return ANK_Success;
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric   case Sema::NC_Unknown:
18530b57cec5SDimitry Andric     // It's not something we know about. Leave it unannotated.
18540b57cec5SDimitry Andric     break;
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   case Sema::NC_Type: {
1857fe6060f1SDimitry Andric     if (TryAltiVecVectorToken())
1858fe6060f1SDimitry Andric       // vector has been found as a type id when altivec is enabled but
1859fe6060f1SDimitry Andric       // this is followed by a declaration specifier so this is really the
1860fe6060f1SDimitry Andric       // altivec vector token.  Leave it unannotated.
1861fe6060f1SDimitry Andric       break;
18620b57cec5SDimitry Andric     SourceLocation BeginLoc = NameLoc;
18630b57cec5SDimitry Andric     if (SS.isNotEmpty())
18640b57cec5SDimitry Andric       BeginLoc = SS.getBeginLoc();
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric     /// An Objective-C object type followed by '<' is a specialization of
18670b57cec5SDimitry Andric     /// a parameterized class type or a protocol-qualified type.
18680b57cec5SDimitry Andric     ParsedType Ty = Classification.getType();
18690b57cec5SDimitry Andric     if (getLangOpts().ObjC && NextToken().is(tok::less) &&
18700b57cec5SDimitry Andric         (Ty.get()->isObjCObjectType() ||
18710b57cec5SDimitry Andric          Ty.get()->isObjCObjectPointerType())) {
18720b57cec5SDimitry Andric       // Consume the name.
18730b57cec5SDimitry Andric       SourceLocation IdentifierLoc = ConsumeToken();
18740b57cec5SDimitry Andric       SourceLocation NewEndLoc;
18750b57cec5SDimitry Andric       TypeResult NewType
18760b57cec5SDimitry Andric           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
18770b57cec5SDimitry Andric                                                    /*consumeLastToken=*/false,
18780b57cec5SDimitry Andric                                                    NewEndLoc);
18790b57cec5SDimitry Andric       if (NewType.isUsable())
18800b57cec5SDimitry Andric         Ty = NewType.get();
18810b57cec5SDimitry Andric       else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
18820b57cec5SDimitry Andric         return ANK_Error;
18830b57cec5SDimitry Andric     }
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric     Tok.setKind(tok::annot_typename);
18860b57cec5SDimitry Andric     setTypeAnnotation(Tok, Ty);
18870b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(Tok.getLocation());
18880b57cec5SDimitry Andric     Tok.setLocation(BeginLoc);
18890b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
18900b57cec5SDimitry Andric     return ANK_Success;
18910b57cec5SDimitry Andric   }
18920b57cec5SDimitry Andric 
1893e8d8bef9SDimitry Andric   case Sema::NC_OverloadSet:
1894e8d8bef9SDimitry Andric     Tok.setKind(tok::annot_overload_set);
18950b57cec5SDimitry Andric     setExprAnnotation(Tok, Classification.getExpression());
18960b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
18970b57cec5SDimitry Andric     if (SS.isNotEmpty())
18980b57cec5SDimitry Andric       Tok.setLocation(SS.getBeginLoc());
18990b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
19000b57cec5SDimitry Andric     return ANK_Success;
19010b57cec5SDimitry Andric 
1902a7dea167SDimitry Andric   case Sema::NC_NonType:
1903fe6060f1SDimitry Andric     if (TryAltiVecVectorToken())
1904fe6060f1SDimitry Andric       // vector has been found as a non-type id when altivec is enabled but
1905fe6060f1SDimitry Andric       // this is followed by a declaration specifier so this is really the
1906fe6060f1SDimitry Andric       // altivec vector token.  Leave it unannotated.
1907fe6060f1SDimitry Andric       break;
1908a7dea167SDimitry Andric     Tok.setKind(tok::annot_non_type);
1909a7dea167SDimitry Andric     setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1910a7dea167SDimitry Andric     Tok.setLocation(NameLoc);
1911a7dea167SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
1912a7dea167SDimitry Andric     PP.AnnotateCachedTokens(Tok);
1913a7dea167SDimitry Andric     if (SS.isNotEmpty())
1914a7dea167SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
1915a7dea167SDimitry Andric     return ANK_Success;
1916a7dea167SDimitry Andric 
1917a7dea167SDimitry Andric   case Sema::NC_UndeclaredNonType:
1918a7dea167SDimitry Andric   case Sema::NC_DependentNonType:
1919a7dea167SDimitry Andric     Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1920a7dea167SDimitry Andric                     ? tok::annot_non_type_undeclared
1921a7dea167SDimitry Andric                     : tok::annot_non_type_dependent);
1922a7dea167SDimitry Andric     setIdentifierAnnotation(Tok, Name);
1923a7dea167SDimitry Andric     Tok.setLocation(NameLoc);
1924a7dea167SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
1925a7dea167SDimitry Andric     PP.AnnotateCachedTokens(Tok);
1926a7dea167SDimitry Andric     if (SS.isNotEmpty())
1927a7dea167SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
1928a7dea167SDimitry Andric     return ANK_Success;
1929a7dea167SDimitry Andric 
19300b57cec5SDimitry Andric   case Sema::NC_TypeTemplate:
19310b57cec5SDimitry Andric     if (Next.isNot(tok::less)) {
19320b57cec5SDimitry Andric       // This may be a type template being used as a template template argument.
19330b57cec5SDimitry Andric       if (SS.isNotEmpty())
19340b57cec5SDimitry Andric         AnnotateScopeToken(SS, !WasScopeAnnotation);
19350b57cec5SDimitry Andric       return ANK_TemplateName;
19360b57cec5SDimitry Andric     }
1937bdd1243dSDimitry Andric     [[fallthrough]];
193806c3fb27SDimitry Andric   case Sema::NC_Concept:
19390b57cec5SDimitry Andric   case Sema::NC_VarTemplate:
19400b57cec5SDimitry Andric   case Sema::NC_FunctionTemplate:
19410b57cec5SDimitry Andric   case Sema::NC_UndeclaredTemplate: {
194206c3fb27SDimitry Andric     bool IsConceptName = Classification.getKind() == Sema::NC_Concept;
194306c3fb27SDimitry Andric     // We have a template name followed by '<'. Consume the identifier token so
194455e4f9d5SDimitry Andric     // we reach the '<' and annotate it.
194506c3fb27SDimitry Andric     if (Next.is(tok::less))
194655e4f9d5SDimitry Andric       ConsumeToken();
194706c3fb27SDimitry Andric     UnqualifiedId Id;
194806c3fb27SDimitry Andric     Id.setIdentifier(Name, NameLoc);
194955e4f9d5SDimitry Andric     if (AnnotateTemplateIdToken(
195055e4f9d5SDimitry Andric             TemplateTy::make(Classification.getTemplateName()),
195155e4f9d5SDimitry Andric             Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
195206c3fb27SDimitry Andric             /*AllowTypeAnnotation=*/!IsConceptName,
195306c3fb27SDimitry Andric             /*TypeConstraint=*/IsConceptName))
195455e4f9d5SDimitry Andric       return ANK_Error;
195506c3fb27SDimitry Andric     if (SS.isNotEmpty())
195606c3fb27SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
195755e4f9d5SDimitry Andric     return ANK_Success;
195855e4f9d5SDimitry Andric   }
19590b57cec5SDimitry Andric   }
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric   // Unable to classify the name, but maybe we can annotate a scope specifier.
19620b57cec5SDimitry Andric   if (SS.isNotEmpty())
19630b57cec5SDimitry Andric     AnnotateScopeToken(SS, !WasScopeAnnotation);
19640b57cec5SDimitry Andric   return ANK_Unresolved;
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric 
TryKeywordIdentFallback(bool DisableKeyword)19670b57cec5SDimitry Andric bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
19680b57cec5SDimitry Andric   assert(Tok.isNot(tok::identifier));
19690b57cec5SDimitry Andric   Diag(Tok, diag::ext_keyword_as_ident)
19700b57cec5SDimitry Andric     << PP.getSpelling(Tok)
19710b57cec5SDimitry Andric     << DisableKeyword;
19720b57cec5SDimitry Andric   if (DisableKeyword)
19730b57cec5SDimitry Andric     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
19740b57cec5SDimitry Andric   Tok.setKind(tok::identifier);
19750b57cec5SDimitry Andric   return true;
19760b57cec5SDimitry Andric }
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric /// TryAnnotateTypeOrScopeToken - If the current token position is on a
19790b57cec5SDimitry Andric /// typename (possibly qualified in C++) or a C++ scope specifier not followed
19800b57cec5SDimitry Andric /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
19810b57cec5SDimitry Andric /// with a single annotation token representing the typename or C++ scope
19820b57cec5SDimitry Andric /// respectively.
19830b57cec5SDimitry Andric /// This simplifies handling of C++ scope specifiers and allows efficient
19840b57cec5SDimitry Andric /// backtracking without the need to re-parse and resolve nested-names and
19850b57cec5SDimitry Andric /// typenames.
19860b57cec5SDimitry Andric /// It will mainly be called when we expect to treat identifiers as typenames
19870b57cec5SDimitry Andric /// (if they are typenames). For example, in C we do not expect identifiers
19880b57cec5SDimitry Andric /// inside expressions to be treated as typenames so it will not be called
19890b57cec5SDimitry Andric /// for expressions in C.
19900b57cec5SDimitry Andric /// The benefit for C/ObjC is that a typename will be annotated and
19910b57cec5SDimitry Andric /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
19920b57cec5SDimitry Andric /// will not be called twice, once to check whether we have a declaration
19930b57cec5SDimitry Andric /// specifier, and another one to get the actual type inside
19940b57cec5SDimitry Andric /// ParseDeclarationSpecifiers).
19950b57cec5SDimitry Andric ///
19960b57cec5SDimitry Andric /// This returns true if an error occurred.
19970b57cec5SDimitry Andric ///
19980b57cec5SDimitry Andric /// Note that this routine emits an error if you call it with ::new or ::delete
19990b57cec5SDimitry Andric /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename)2000bdd1243dSDimitry Andric bool Parser::TryAnnotateTypeOrScopeToken(
2001bdd1243dSDimitry Andric     ImplicitTypenameContext AllowImplicitTypename) {
20020b57cec5SDimitry Andric   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
20030b57cec5SDimitry Andric           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
20040b57cec5SDimitry Andric           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
2005*0fca6ea1SDimitry Andric           Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
2006*0fca6ea1SDimitry Andric           Tok.is(tok::annot_pack_indexing_type)) &&
20070b57cec5SDimitry Andric          "Cannot be a type or scope token!");
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric   if (Tok.is(tok::kw_typename)) {
20100b57cec5SDimitry Andric     // MSVC lets you do stuff like:
20110b57cec5SDimitry Andric     //   typename typedef T_::D D;
20120b57cec5SDimitry Andric     //
20130b57cec5SDimitry Andric     // We will consume the typedef token here and put it back after we have
20140b57cec5SDimitry Andric     // parsed the first identifier, transforming it into something more like:
20150b57cec5SDimitry Andric     //   typename T_::D typedef D;
20160b57cec5SDimitry Andric     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
20170b57cec5SDimitry Andric       Token TypedefToken;
20180b57cec5SDimitry Andric       PP.Lex(TypedefToken);
2019bdd1243dSDimitry Andric       bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
20200b57cec5SDimitry Andric       PP.EnterToken(Tok, /*IsReinject=*/true);
20210b57cec5SDimitry Andric       Tok = TypedefToken;
20220b57cec5SDimitry Andric       if (!Result)
20230b57cec5SDimitry Andric         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
20240b57cec5SDimitry Andric       return Result;
20250b57cec5SDimitry Andric     }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric     // Parse a C++ typename-specifier, e.g., "typename T::type".
20280b57cec5SDimitry Andric     //
20290b57cec5SDimitry Andric     //   typename-specifier:
20300b57cec5SDimitry Andric     //     'typename' '::' [opt] nested-name-specifier identifier
20310b57cec5SDimitry Andric     //     'typename' '::' [opt] nested-name-specifier template [opt]
20320b57cec5SDimitry Andric     //            simple-template-id
20330b57cec5SDimitry Andric     SourceLocation TypenameLoc = ConsumeToken();
20340b57cec5SDimitry Andric     CXXScopeSpec SS;
20350b57cec5SDimitry Andric     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
203604eeddc0SDimitry Andric                                        /*ObjectHasErrors=*/false,
20370b57cec5SDimitry Andric                                        /*EnteringContext=*/false, nullptr,
20380b57cec5SDimitry Andric                                        /*IsTypename*/ true))
20390b57cec5SDimitry Andric       return true;
204055e4f9d5SDimitry Andric     if (SS.isEmpty()) {
20410b57cec5SDimitry Andric       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
20420b57cec5SDimitry Andric           Tok.is(tok::annot_decltype)) {
20430b57cec5SDimitry Andric         // Attempt to recover by skipping the invalid 'typename'
20440b57cec5SDimitry Andric         if (Tok.is(tok::annot_decltype) ||
2045bdd1243dSDimitry Andric             (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
2046bdd1243dSDimitry Andric              Tok.isAnnotation())) {
20470b57cec5SDimitry Andric           unsigned DiagID = diag::err_expected_qualified_after_typename;
20480b57cec5SDimitry Andric           // MS compatibility: MSVC permits using known types with typename.
20490b57cec5SDimitry Andric           // e.g. "typedef typename T* pointer_type"
20500b57cec5SDimitry Andric           if (getLangOpts().MicrosoftExt)
20510b57cec5SDimitry Andric             DiagID = diag::warn_expected_qualified_after_typename;
20520b57cec5SDimitry Andric           Diag(Tok.getLocation(), DiagID);
20530b57cec5SDimitry Andric           return false;
20540b57cec5SDimitry Andric         }
20550b57cec5SDimitry Andric       }
20560b57cec5SDimitry Andric       if (Tok.isEditorPlaceholder())
20570b57cec5SDimitry Andric         return true;
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
20600b57cec5SDimitry Andric       return true;
20610b57cec5SDimitry Andric     }
20620b57cec5SDimitry Andric 
2063*0fca6ea1SDimitry Andric     bool TemplateKWPresent = false;
2064*0fca6ea1SDimitry Andric     if (Tok.is(tok::kw_template)) {
2065*0fca6ea1SDimitry Andric       ConsumeToken();
2066*0fca6ea1SDimitry Andric       TemplateKWPresent = true;
2067*0fca6ea1SDimitry Andric     }
2068*0fca6ea1SDimitry Andric 
20690b57cec5SDimitry Andric     TypeResult Ty;
20700b57cec5SDimitry Andric     if (Tok.is(tok::identifier)) {
2071*0fca6ea1SDimitry Andric       if (TemplateKWPresent && NextToken().isNot(tok::less)) {
2072*0fca6ea1SDimitry Andric         Diag(Tok.getLocation(),
2073*0fca6ea1SDimitry Andric              diag::missing_template_arg_list_after_template_kw);
2074*0fca6ea1SDimitry Andric         return true;
2075*0fca6ea1SDimitry Andric       }
20760b57cec5SDimitry Andric       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
20770b57cec5SDimitry Andric                                      *Tok.getIdentifierInfo(),
20780b57cec5SDimitry Andric                                      Tok.getLocation());
20790b57cec5SDimitry Andric     } else if (Tok.is(tok::annot_template_id)) {
20800b57cec5SDimitry Andric       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
20815ffd83dbSDimitry Andric       if (!TemplateId->mightBeType()) {
20820b57cec5SDimitry Andric         Diag(Tok, diag::err_typename_refers_to_non_type_template)
20830b57cec5SDimitry Andric           << Tok.getAnnotationRange();
20840b57cec5SDimitry Andric         return true;
20850b57cec5SDimitry Andric       }
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
20880b57cec5SDimitry Andric                                          TemplateId->NumArgs);
20890b57cec5SDimitry Andric 
20905ffd83dbSDimitry Andric       Ty = TemplateId->isInvalid()
20915ffd83dbSDimitry Andric                ? TypeError()
20925ffd83dbSDimitry Andric                : Actions.ActOnTypenameType(
20935ffd83dbSDimitry Andric                      getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
20945ffd83dbSDimitry Andric                      TemplateId->Template, TemplateId->Name,
20955ffd83dbSDimitry Andric                      TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
20965ffd83dbSDimitry Andric                      TemplateArgsPtr, TemplateId->RAngleLoc);
20970b57cec5SDimitry Andric     } else {
20980b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_type_name_after_typename)
20990b57cec5SDimitry Andric         << SS.getRange();
21000b57cec5SDimitry Andric       return true;
21010b57cec5SDimitry Andric     }
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric     SourceLocation EndLoc = Tok.getLastLoc();
21040b57cec5SDimitry Andric     Tok.setKind(tok::annot_typename);
21055ffd83dbSDimitry Andric     setTypeAnnotation(Tok, Ty);
21060b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(EndLoc);
21070b57cec5SDimitry Andric     Tok.setLocation(TypenameLoc);
21080b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
21090b57cec5SDimitry Andric     return false;
21100b57cec5SDimitry Andric   }
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // Remembers whether the token was originally a scope annotation.
21130b57cec5SDimitry Andric   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric   CXXScopeSpec SS;
21160b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
21175ffd83dbSDimitry Andric     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
211804eeddc0SDimitry Andric                                        /*ObjectHasErrors=*/false,
21195ffd83dbSDimitry Andric                                        /*EnteringContext*/ false))
21200b57cec5SDimitry Andric       return true;
21210b57cec5SDimitry Andric 
2122bdd1243dSDimitry Andric   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2123bdd1243dSDimitry Andric                                                    AllowImplicitTypename);
21240b57cec5SDimitry Andric }
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric /// Try to annotate a type or scope token, having already parsed an
21270b57cec5SDimitry Andric /// optional scope specifier. \p IsNewScope should be \c true unless the scope
21280b57cec5SDimitry Andric /// specifier was extracted from an existing tok::annot_cxxscope annotation.
TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec & SS,bool IsNewScope,ImplicitTypenameContext AllowImplicitTypename)2129bdd1243dSDimitry Andric bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
2130bdd1243dSDimitry Andric     CXXScopeSpec &SS, bool IsNewScope,
2131bdd1243dSDimitry Andric     ImplicitTypenameContext AllowImplicitTypename) {
21320b57cec5SDimitry Andric   if (Tok.is(tok::identifier)) {
21330b57cec5SDimitry Andric     // Determine whether the identifier is a type name.
21340b57cec5SDimitry Andric     if (ParsedType Ty = Actions.getTypeName(
21350b57cec5SDimitry Andric             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
21360b57cec5SDimitry Andric             false, NextToken().is(tok::period), nullptr,
21370b57cec5SDimitry Andric             /*IsCtorOrDtorName=*/false,
2138bdd1243dSDimitry Andric             /*NonTrivialTypeSourceInfo=*/true,
2139bdd1243dSDimitry Andric             /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
21400b57cec5SDimitry Andric       SourceLocation BeginLoc = Tok.getLocation();
21410b57cec5SDimitry Andric       if (SS.isNotEmpty()) // it was a C++ qualified type name.
21420b57cec5SDimitry Andric         BeginLoc = SS.getBeginLoc();
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric       /// An Objective-C object type followed by '<' is a specialization of
21450b57cec5SDimitry Andric       /// a parameterized class type or a protocol-qualified type.
21460b57cec5SDimitry Andric       if (getLangOpts().ObjC && NextToken().is(tok::less) &&
21470b57cec5SDimitry Andric           (Ty.get()->isObjCObjectType() ||
21480b57cec5SDimitry Andric            Ty.get()->isObjCObjectPointerType())) {
21490b57cec5SDimitry Andric         // Consume the name.
21500b57cec5SDimitry Andric         SourceLocation IdentifierLoc = ConsumeToken();
21510b57cec5SDimitry Andric         SourceLocation NewEndLoc;
21520b57cec5SDimitry Andric         TypeResult NewType
21530b57cec5SDimitry Andric           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
21540b57cec5SDimitry Andric                                                    /*consumeLastToken=*/false,
21550b57cec5SDimitry Andric                                                    NewEndLoc);
21560b57cec5SDimitry Andric         if (NewType.isUsable())
21570b57cec5SDimitry Andric           Ty = NewType.get();
21580b57cec5SDimitry Andric         else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
21590b57cec5SDimitry Andric           return false;
21600b57cec5SDimitry Andric       }
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric       // This is a typename. Replace the current token in-place with an
21630b57cec5SDimitry Andric       // annotation type token.
21640b57cec5SDimitry Andric       Tok.setKind(tok::annot_typename);
21650b57cec5SDimitry Andric       setTypeAnnotation(Tok, Ty);
21660b57cec5SDimitry Andric       Tok.setAnnotationEndLoc(Tok.getLocation());
21670b57cec5SDimitry Andric       Tok.setLocation(BeginLoc);
21680b57cec5SDimitry Andric 
21690b57cec5SDimitry Andric       // In case the tokens were cached, have Preprocessor replace
21700b57cec5SDimitry Andric       // them with the annotation token.
21710b57cec5SDimitry Andric       PP.AnnotateCachedTokens(Tok);
21720b57cec5SDimitry Andric       return false;
21730b57cec5SDimitry Andric     }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric     if (!getLangOpts().CPlusPlus) {
21765f757f3fSDimitry Andric       // If we're in C, the only place we can have :: tokens is C23
2177bdd1243dSDimitry Andric       // attribute which is parsed elsewhere. If the identifier is not a type,
2178bdd1243dSDimitry Andric       // then it can't be scope either, just early exit.
21790b57cec5SDimitry Andric       return false;
21800b57cec5SDimitry Andric     }
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric     // If this is a template-id, annotate with a template-id or type token.
21830b57cec5SDimitry Andric     // FIXME: This appears to be dead code. We already have formed template-id
21840b57cec5SDimitry Andric     // tokens when parsing the scope specifier; this can never form a new one.
21850b57cec5SDimitry Andric     if (NextToken().is(tok::less)) {
21860b57cec5SDimitry Andric       TemplateTy Template;
21870b57cec5SDimitry Andric       UnqualifiedId TemplateName;
21880b57cec5SDimitry Andric       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
21890b57cec5SDimitry Andric       bool MemberOfUnknownSpecialization;
21900b57cec5SDimitry Andric       if (TemplateNameKind TNK = Actions.isTemplateName(
21910b57cec5SDimitry Andric               getCurScope(), SS,
21920b57cec5SDimitry Andric               /*hasTemplateKeyword=*/false, TemplateName,
21930b57cec5SDimitry Andric               /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
21940b57cec5SDimitry Andric               MemberOfUnknownSpecialization)) {
21950b57cec5SDimitry Andric         // Only annotate an undeclared template name as a template-id if the
21960b57cec5SDimitry Andric         // following tokens have the form of a template argument list.
21970b57cec5SDimitry Andric         if (TNK != TNK_Undeclared_template ||
21980b57cec5SDimitry Andric             isTemplateArgumentList(1) != TPResult::False) {
21990b57cec5SDimitry Andric           // Consume the identifier.
22000b57cec5SDimitry Andric           ConsumeToken();
22010b57cec5SDimitry Andric           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
22020b57cec5SDimitry Andric                                       TemplateName)) {
22030b57cec5SDimitry Andric             // If an unrecoverable error occurred, we need to return true here,
22040b57cec5SDimitry Andric             // because the token stream is in a damaged state.  We may not
22050b57cec5SDimitry Andric             // return a valid identifier.
22060b57cec5SDimitry Andric             return true;
22070b57cec5SDimitry Andric           }
22080b57cec5SDimitry Andric         }
22090b57cec5SDimitry Andric       }
22100b57cec5SDimitry Andric     }
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric     // The current token, which is either an identifier or a
22130b57cec5SDimitry Andric     // template-id, is not part of the annotation. Fall through to
22140b57cec5SDimitry Andric     // push that token back into the stream and complete the C++ scope
22150b57cec5SDimitry Andric     // specifier annotation.
22160b57cec5SDimitry Andric   }
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric   if (Tok.is(tok::annot_template_id)) {
22190b57cec5SDimitry Andric     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
22200b57cec5SDimitry Andric     if (TemplateId->Kind == TNK_Type_template) {
22210b57cec5SDimitry Andric       // A template-id that refers to a type was parsed into a
22220b57cec5SDimitry Andric       // template-id annotation in a context where we weren't allowed
22230b57cec5SDimitry Andric       // to produce a type annotation token. Update the template-id
22240b57cec5SDimitry Andric       // annotation token to a type annotation token now.
2225bdd1243dSDimitry Andric       AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
22260b57cec5SDimitry Andric       return false;
22270b57cec5SDimitry Andric     }
22280b57cec5SDimitry Andric   }
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric   if (SS.isEmpty())
22310b57cec5SDimitry Andric     return false;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   // A C++ scope specifier that isn't followed by a typename.
22340b57cec5SDimitry Andric   AnnotateScopeToken(SS, IsNewScope);
22350b57cec5SDimitry Andric   return false;
22360b57cec5SDimitry Andric }
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
22390b57cec5SDimitry Andric /// annotates C++ scope specifiers and template-ids.  This returns
22400b57cec5SDimitry Andric /// true if there was an error that could not be recovered from.
22410b57cec5SDimitry Andric ///
22420b57cec5SDimitry Andric /// Note that this routine emits an error if you call it with ::new or ::delete
22430b57cec5SDimitry Andric /// as the current tokens, so only call it in contexts where these are invalid.
TryAnnotateCXXScopeToken(bool EnteringContext)22440b57cec5SDimitry Andric bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
22450b57cec5SDimitry Andric   assert(getLangOpts().CPlusPlus &&
22460b57cec5SDimitry Andric          "Call sites of this function should be guarded by checking for C++");
224755e4f9d5SDimitry Andric   assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   CXXScopeSpec SS;
22505ffd83dbSDimitry Andric   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
225104eeddc0SDimitry Andric                                      /*ObjectHasErrors=*/false,
22525ffd83dbSDimitry Andric                                      EnteringContext))
22530b57cec5SDimitry Andric     return true;
22540b57cec5SDimitry Andric   if (SS.isEmpty())
22550b57cec5SDimitry Andric     return false;
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric   AnnotateScopeToken(SS, true);
22580b57cec5SDimitry Andric   return false;
22590b57cec5SDimitry Andric }
22600b57cec5SDimitry Andric 
isTokenEqualOrEqualTypo()22610b57cec5SDimitry Andric bool Parser::isTokenEqualOrEqualTypo() {
22620b57cec5SDimitry Andric   tok::TokenKind Kind = Tok.getKind();
22630b57cec5SDimitry Andric   switch (Kind) {
22640b57cec5SDimitry Andric   default:
22650b57cec5SDimitry Andric     return false;
22660b57cec5SDimitry Andric   case tok::ampequal:            // &=
22670b57cec5SDimitry Andric   case tok::starequal:           // *=
22680b57cec5SDimitry Andric   case tok::plusequal:           // +=
22690b57cec5SDimitry Andric   case tok::minusequal:          // -=
22700b57cec5SDimitry Andric   case tok::exclaimequal:        // !=
22710b57cec5SDimitry Andric   case tok::slashequal:          // /=
22720b57cec5SDimitry Andric   case tok::percentequal:        // %=
22730b57cec5SDimitry Andric   case tok::lessequal:           // <=
22740b57cec5SDimitry Andric   case tok::lesslessequal:       // <<=
22750b57cec5SDimitry Andric   case tok::greaterequal:        // >=
22760b57cec5SDimitry Andric   case tok::greatergreaterequal: // >>=
22770b57cec5SDimitry Andric   case tok::caretequal:          // ^=
22780b57cec5SDimitry Andric   case tok::pipeequal:           // |=
22790b57cec5SDimitry Andric   case tok::equalequal:          // ==
22800b57cec5SDimitry Andric     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
22810b57cec5SDimitry Andric         << Kind
22820b57cec5SDimitry Andric         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2283bdd1243dSDimitry Andric     [[fallthrough]];
22840b57cec5SDimitry Andric   case tok::equal:
22850b57cec5SDimitry Andric     return true;
22860b57cec5SDimitry Andric   }
22870b57cec5SDimitry Andric }
22880b57cec5SDimitry Andric 
handleUnexpectedCodeCompletionToken()22890b57cec5SDimitry Andric SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
22900b57cec5SDimitry Andric   assert(Tok.is(tok::code_completion));
22910b57cec5SDimitry Andric   PrevTokLocation = Tok.getLocation();
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric   for (Scope *S = getCurScope(); S; S = S->getParent()) {
229481ad6265SDimitry Andric     if (S->isFunctionScope()) {
2295fe6060f1SDimitry Andric       cutOffParsing();
2296*0fca6ea1SDimitry Andric       Actions.CodeCompletion().CodeCompleteOrdinaryName(
2297*0fca6ea1SDimitry Andric           getCurScope(), SemaCodeCompletion::PCC_RecoveryInFunction);
22980b57cec5SDimitry Andric       return PrevTokLocation;
22990b57cec5SDimitry Andric     }
23000b57cec5SDimitry Andric 
230181ad6265SDimitry Andric     if (S->isClassScope()) {
23020b57cec5SDimitry Andric       cutOffParsing();
2303*0fca6ea1SDimitry Andric       Actions.CodeCompletion().CodeCompleteOrdinaryName(
2304*0fca6ea1SDimitry Andric           getCurScope(), SemaCodeCompletion::PCC_Class);
23050b57cec5SDimitry Andric       return PrevTokLocation;
23060b57cec5SDimitry Andric     }
23070b57cec5SDimitry Andric   }
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric   cutOffParsing();
2310*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompleteOrdinaryName(
2311*0fca6ea1SDimitry Andric       getCurScope(), SemaCodeCompletion::PCC_Namespace);
23120b57cec5SDimitry Andric   return PrevTokLocation;
23130b57cec5SDimitry Andric }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric // Code-completion pass-through functions
23160b57cec5SDimitry Andric 
CodeCompleteDirective(bool InConditional)23170b57cec5SDimitry Andric void Parser::CodeCompleteDirective(bool InConditional) {
2318*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
23190b57cec5SDimitry Andric }
23200b57cec5SDimitry Andric 
CodeCompleteInConditionalExclusion()23210b57cec5SDimitry Andric void Parser::CodeCompleteInConditionalExclusion() {
2322*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2323*0fca6ea1SDimitry Andric       getCurScope());
23240b57cec5SDimitry Andric }
23250b57cec5SDimitry Andric 
CodeCompleteMacroName(bool IsDefinition)23260b57cec5SDimitry Andric void Parser::CodeCompleteMacroName(bool IsDefinition) {
2327*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
23280b57cec5SDimitry Andric }
23290b57cec5SDimitry Andric 
CodeCompletePreprocessorExpression()23300b57cec5SDimitry Andric void Parser::CodeCompletePreprocessorExpression() {
2331*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompletePreprocessorExpression();
23320b57cec5SDimitry Andric }
23330b57cec5SDimitry Andric 
CodeCompleteMacroArgument(IdentifierInfo * Macro,MacroInfo * MacroInfo,unsigned ArgumentIndex)23340b57cec5SDimitry Andric void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
23350b57cec5SDimitry Andric                                        MacroInfo *MacroInfo,
23360b57cec5SDimitry Andric                                        unsigned ArgumentIndex) {
2337*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2338*0fca6ea1SDimitry Andric       getCurScope(), Macro, MacroInfo, ArgumentIndex);
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric 
CodeCompleteIncludedFile(llvm::StringRef Dir,bool IsAngled)23410b57cec5SDimitry Andric void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2342*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric 
CodeCompleteNaturalLanguage()23450b57cec5SDimitry Andric void Parser::CodeCompleteNaturalLanguage() {
2346*0fca6ea1SDimitry Andric   Actions.CodeCompletion().CodeCompleteNaturalLanguage();
23470b57cec5SDimitry Andric }
23480b57cec5SDimitry Andric 
ParseMicrosoftIfExistsCondition(IfExistsCondition & Result)23490b57cec5SDimitry Andric bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
23500b57cec5SDimitry Andric   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
23510b57cec5SDimitry Andric          "Expected '__if_exists' or '__if_not_exists'");
23520b57cec5SDimitry Andric   Result.IsIfExists = Tok.is(tok::kw___if_exists);
23530b57cec5SDimitry Andric   Result.KeywordLoc = ConsumeToken();
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   BalancedDelimiterTracker T(*this, tok::l_paren);
23560b57cec5SDimitry Andric   if (T.consumeOpen()) {
23570b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_lparen_after)
23580b57cec5SDimitry Andric       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
23590b57cec5SDimitry Andric     return true;
23600b57cec5SDimitry Andric   }
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   // Parse nested-name-specifier.
23630b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
23645ffd83dbSDimitry Andric     ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
236504eeddc0SDimitry Andric                                    /*ObjectHasErrors=*/false,
23660b57cec5SDimitry Andric                                    /*EnteringContext=*/false);
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric   // Check nested-name specifier.
23690b57cec5SDimitry Andric   if (Result.SS.isInvalid()) {
23700b57cec5SDimitry Andric     T.skipToEnd();
23710b57cec5SDimitry Andric     return true;
23720b57cec5SDimitry Andric   }
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric   // Parse the unqualified-id.
23750b57cec5SDimitry Andric   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
23765ffd83dbSDimitry Andric   if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
23775ffd83dbSDimitry Andric                          /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
23785ffd83dbSDimitry Andric                          /*AllowDestructorName*/ true,
23795ffd83dbSDimitry Andric                          /*AllowConstructorName*/ true,
23805ffd83dbSDimitry Andric                          /*AllowDeductionGuide*/ false, &TemplateKWLoc,
23815ffd83dbSDimitry Andric                          Result.Name)) {
23820b57cec5SDimitry Andric     T.skipToEnd();
23830b57cec5SDimitry Andric     return true;
23840b57cec5SDimitry Andric   }
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   if (T.consumeClose())
23870b57cec5SDimitry Andric     return true;
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   // Check if the symbol exists.
23900b57cec5SDimitry Andric   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
23910b57cec5SDimitry Andric                                                Result.IsIfExists, Result.SS,
23920b57cec5SDimitry Andric                                                Result.Name)) {
23930b57cec5SDimitry Andric   case Sema::IER_Exists:
23940b57cec5SDimitry Andric     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
23950b57cec5SDimitry Andric     break;
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric   case Sema::IER_DoesNotExist:
23980b57cec5SDimitry Andric     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
23990b57cec5SDimitry Andric     break;
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric   case Sema::IER_Dependent:
24020b57cec5SDimitry Andric     Result.Behavior = IEB_Dependent;
24030b57cec5SDimitry Andric     break;
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   case Sema::IER_Error:
24060b57cec5SDimitry Andric     return true;
24070b57cec5SDimitry Andric   }
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   return false;
24100b57cec5SDimitry Andric }
24110b57cec5SDimitry Andric 
ParseMicrosoftIfExistsExternalDeclaration()24120b57cec5SDimitry Andric void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
24130b57cec5SDimitry Andric   IfExistsCondition Result;
24140b57cec5SDimitry Andric   if (ParseMicrosoftIfExistsCondition(Result))
24150b57cec5SDimitry Andric     return;
24160b57cec5SDimitry Andric 
24170b57cec5SDimitry Andric   BalancedDelimiterTracker Braces(*this, tok::l_brace);
24180b57cec5SDimitry Andric   if (Braces.consumeOpen()) {
24190b57cec5SDimitry Andric     Diag(Tok, diag::err_expected) << tok::l_brace;
24200b57cec5SDimitry Andric     return;
24210b57cec5SDimitry Andric   }
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   switch (Result.Behavior) {
24240b57cec5SDimitry Andric   case IEB_Parse:
24250b57cec5SDimitry Andric     // Parse declarations below.
24260b57cec5SDimitry Andric     break;
24270b57cec5SDimitry Andric 
24280b57cec5SDimitry Andric   case IEB_Dependent:
24290b57cec5SDimitry Andric     llvm_unreachable("Cannot have a dependent external declaration");
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   case IEB_Skip:
24320b57cec5SDimitry Andric     Braces.skipToEnd();
24330b57cec5SDimitry Andric     return;
24340b57cec5SDimitry Andric   }
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   // Parse the declarations.
24370b57cec5SDimitry Andric   // FIXME: Support module import within __if_exists?
24380b57cec5SDimitry Andric   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
243981ad6265SDimitry Andric     ParsedAttributes Attrs(AttrFactory);
244081ad6265SDimitry Andric     MaybeParseCXX11Attributes(Attrs);
2441bdd1243dSDimitry Andric     ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2442bdd1243dSDimitry Andric     DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
24430b57cec5SDimitry Andric     if (Result && !getCurScope()->getParent())
24440b57cec5SDimitry Andric       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
24450b57cec5SDimitry Andric   }
24460b57cec5SDimitry Andric   Braces.consumeClose();
24470b57cec5SDimitry Andric }
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric /// Parse a declaration beginning with the 'module' keyword or C++20
24500b57cec5SDimitry Andric /// context-sensitive keyword (optionally preceded by 'export').
24510b57cec5SDimitry Andric ///
245206c3fb27SDimitry Andric ///   module-declaration:   [C++20]
24530b57cec5SDimitry Andric ///     'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
24540b57cec5SDimitry Andric ///
24550b57cec5SDimitry Andric ///   global-module-fragment:  [C++2a]
24560b57cec5SDimitry Andric ///     'module' ';' top-level-declaration-seq[opt]
24570b57cec5SDimitry Andric ///   module-declaration:      [C++2a]
24580b57cec5SDimitry Andric ///     'export'[opt] 'module' module-name module-partition[opt]
24590b57cec5SDimitry Andric ///            attribute-specifier-seq[opt] ';'
24600b57cec5SDimitry Andric ///   private-module-fragment: [C++2a]
24610b57cec5SDimitry Andric ///     'module' ':' 'private' ';' top-level-declaration-seq[opt]
246281ad6265SDimitry Andric Parser::DeclGroupPtrTy
ParseModuleDecl(Sema::ModuleImportState & ImportState)246381ad6265SDimitry Andric Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
24640b57cec5SDimitry Andric   SourceLocation StartLoc = Tok.getLocation();
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
24670b57cec5SDimitry Andric                                  ? Sema::ModuleDeclKind::Interface
24680b57cec5SDimitry Andric                                  : Sema::ModuleDeclKind::Implementation;
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   assert(
24710b57cec5SDimitry Andric       (Tok.is(tok::kw_module) ||
24720b57cec5SDimitry Andric        (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
24730b57cec5SDimitry Andric       "not a module declaration");
24740b57cec5SDimitry Andric   SourceLocation ModuleLoc = ConsumeToken();
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric   // Attributes appear after the module name, not before.
24770b57cec5SDimitry Andric   // FIXME: Suggest moving the attributes later with a fixit.
24780b57cec5SDimitry Andric   DiagnoseAndSkipCXX11Attributes();
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric   // Parse a global-module-fragment, if present.
24810b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
24820b57cec5SDimitry Andric     SourceLocation SemiLoc = ConsumeToken();
248381ad6265SDimitry Andric     if (ImportState != Sema::ModuleImportState::FirstDecl) {
24840b57cec5SDimitry Andric       Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
24850b57cec5SDimitry Andric         << SourceRange(StartLoc, SemiLoc);
24860b57cec5SDimitry Andric       return nullptr;
24870b57cec5SDimitry Andric     }
24880b57cec5SDimitry Andric     if (MDK == Sema::ModuleDeclKind::Interface) {
24890b57cec5SDimitry Andric       Diag(StartLoc, diag::err_module_fragment_exported)
24900b57cec5SDimitry Andric         << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
24910b57cec5SDimitry Andric     }
249281ad6265SDimitry Andric     ImportState = Sema::ModuleImportState::GlobalFragment;
24930b57cec5SDimitry Andric     return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
24940b57cec5SDimitry Andric   }
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric   // Parse a private-module-fragment, if present.
24970b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
24980b57cec5SDimitry Andric       NextToken().is(tok::kw_private)) {
24990b57cec5SDimitry Andric     if (MDK == Sema::ModuleDeclKind::Interface) {
25000b57cec5SDimitry Andric       Diag(StartLoc, diag::err_module_fragment_exported)
25010b57cec5SDimitry Andric         << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
25020b57cec5SDimitry Andric     }
25030b57cec5SDimitry Andric     ConsumeToken();
25040b57cec5SDimitry Andric     SourceLocation PrivateLoc = ConsumeToken();
25050b57cec5SDimitry Andric     DiagnoseAndSkipCXX11Attributes();
25060b57cec5SDimitry Andric     ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2507bdd1243dSDimitry Andric     ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2508bdd1243dSDimitry Andric                       ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2509bdd1243dSDimitry Andric                       : Sema::ModuleImportState::PrivateFragmentImportFinished;
25100b57cec5SDimitry Andric     return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
25110b57cec5SDimitry Andric   }
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
25140b57cec5SDimitry Andric   if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
25150b57cec5SDimitry Andric     return nullptr;
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   // Parse the optional module-partition.
251881ad6265SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
25190b57cec5SDimitry Andric   if (Tok.is(tok::colon)) {
25200b57cec5SDimitry Andric     SourceLocation ColonLoc = ConsumeToken();
252181ad6265SDimitry Andric     if (!getLangOpts().CPlusPlusModules)
25220b57cec5SDimitry Andric       Diag(ColonLoc, diag::err_unsupported_module_partition)
25230b57cec5SDimitry Andric           << SourceRange(ColonLoc, Partition.back().second);
252481ad6265SDimitry Andric     // Recover by ignoring the partition name.
252581ad6265SDimitry Andric     else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
252681ad6265SDimitry Andric       return nullptr;
25270b57cec5SDimitry Andric   }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric   // We don't support any module attributes yet; just parse them and diagnose.
253081ad6265SDimitry Andric   ParsedAttributes Attrs(AttrFactory);
25310b57cec5SDimitry Andric   MaybeParseCXX11Attributes(Attrs);
253281ad6265SDimitry Andric   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
253306c3fb27SDimitry Andric                           diag::err_keyword_not_module_attr,
253481ad6265SDimitry Andric                           /*DiagnoseEmptyAttrs=*/false,
253581ad6265SDimitry Andric                           /*WarnOnUnknownAttrs=*/true);
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   ExpectAndConsumeSemi(diag::err_module_expected_semi);
25380b57cec5SDimitry Andric 
253981ad6265SDimitry Andric   return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
254081ad6265SDimitry Andric                                  ImportState);
25410b57cec5SDimitry Andric }
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric /// Parse a module import declaration. This is essentially the same for
254481ad6265SDimitry Andric /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
254581ad6265SDimitry Andric /// trailing optional attributes (in C++).
25460b57cec5SDimitry Andric ///
25470b57cec5SDimitry Andric /// [ObjC]  @import declaration:
25480b57cec5SDimitry Andric ///           '@' 'import' module-name ';'
25490b57cec5SDimitry Andric /// [ModTS] module-import-declaration:
25500b57cec5SDimitry Andric ///           'import' module-name attribute-specifier-seq[opt] ';'
255181ad6265SDimitry Andric /// [C++20] module-import-declaration:
25520b57cec5SDimitry Andric ///           'export'[opt] 'import' module-name
25530b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
25540b57cec5SDimitry Andric ///           'export'[opt] 'import' module-partition
25550b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
25560b57cec5SDimitry Andric ///           'export'[opt] 'import' header-name
25570b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
ParseModuleImport(SourceLocation AtLoc,Sema::ModuleImportState & ImportState)255881ad6265SDimitry Andric Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
255981ad6265SDimitry Andric                                 Sema::ModuleImportState &ImportState) {
25600b57cec5SDimitry Andric   SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric   SourceLocation ExportLoc;
25630b57cec5SDimitry Andric   TryConsumeToken(tok::kw_export, ExportLoc);
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric   assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
25660b57cec5SDimitry Andric                             : Tok.isObjCAtKeyword(tok::objc_import)) &&
25670b57cec5SDimitry Andric          "Improper start to module import");
25680b57cec5SDimitry Andric   bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
25690b57cec5SDimitry Andric   SourceLocation ImportLoc = ConsumeToken();
25700b57cec5SDimitry Andric 
257181ad6265SDimitry Andric   // For C++20 modules, we can have "name" or ":Partition name" as valid input.
25720b57cec5SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
257381ad6265SDimitry Andric   bool IsPartition = false;
25740b57cec5SDimitry Andric   Module *HeaderUnit = nullptr;
25750b57cec5SDimitry Andric   if (Tok.is(tok::header_name)) {
25760b57cec5SDimitry Andric     // This is a header import that the preprocessor decided we should skip
25770b57cec5SDimitry Andric     // because it was malformed in some way. Parse and ignore it; it's already
25780b57cec5SDimitry Andric     // been diagnosed.
25790b57cec5SDimitry Andric     ConsumeToken();
25800b57cec5SDimitry Andric   } else if (Tok.is(tok::annot_header_unit)) {
25810b57cec5SDimitry Andric     // This is a header import that the preprocessor mapped to a module import.
25820b57cec5SDimitry Andric     HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
25830b57cec5SDimitry Andric     ConsumeAnnotationToken();
258481ad6265SDimitry Andric   } else if (Tok.is(tok::colon)) {
25850b57cec5SDimitry Andric     SourceLocation ColonLoc = ConsumeToken();
258681ad6265SDimitry Andric     if (!getLangOpts().CPlusPlusModules)
25870b57cec5SDimitry Andric       Diag(ColonLoc, diag::err_unsupported_module_partition)
25880b57cec5SDimitry Andric           << SourceRange(ColonLoc, Path.back().second);
258981ad6265SDimitry Andric     // Recover by leaving partition empty.
259081ad6265SDimitry Andric     else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
25910b57cec5SDimitry Andric       return nullptr;
259281ad6265SDimitry Andric     else
259381ad6265SDimitry Andric       IsPartition = true;
25940b57cec5SDimitry Andric   } else {
25950b57cec5SDimitry Andric     if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
25960b57cec5SDimitry Andric       return nullptr;
25970b57cec5SDimitry Andric   }
25980b57cec5SDimitry Andric 
259981ad6265SDimitry Andric   ParsedAttributes Attrs(AttrFactory);
26000b57cec5SDimitry Andric   MaybeParseCXX11Attributes(Attrs);
26010b57cec5SDimitry Andric   // We don't support any module import attributes yet.
260281ad6265SDimitry Andric   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
260306c3fb27SDimitry Andric                           diag::err_keyword_not_import_attr,
260481ad6265SDimitry Andric                           /*DiagnoseEmptyAttrs=*/false,
260581ad6265SDimitry Andric                           /*WarnOnUnknownAttrs=*/true);
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric   if (PP.hadModuleLoaderFatalFailure()) {
26080b57cec5SDimitry Andric     // With a fatal failure in the module loader, we abort parsing.
26090b57cec5SDimitry Andric     cutOffParsing();
26100b57cec5SDimitry Andric     return nullptr;
26110b57cec5SDimitry Andric   }
26120b57cec5SDimitry Andric 
261381ad6265SDimitry Andric   // Diagnose mis-imports.
261481ad6265SDimitry Andric   bool SeenError = true;
261581ad6265SDimitry Andric   switch (ImportState) {
261681ad6265SDimitry Andric   case Sema::ModuleImportState::ImportAllowed:
261781ad6265SDimitry Andric     SeenError = false;
261881ad6265SDimitry Andric     break;
261981ad6265SDimitry Andric   case Sema::ModuleImportState::FirstDecl:
26205f757f3fSDimitry Andric     // If we found an import decl as the first declaration, we must be not in
26215f757f3fSDimitry Andric     // a C++20 module unit or we are in an invalid state.
26225f757f3fSDimitry Andric     ImportState = Sema::ModuleImportState::NotACXX20Module;
26235f757f3fSDimitry Andric     [[fallthrough]];
262481ad6265SDimitry Andric   case Sema::ModuleImportState::NotACXX20Module:
262581ad6265SDimitry Andric     // We can only import a partition within a module purview.
262681ad6265SDimitry Andric     if (IsPartition)
262781ad6265SDimitry Andric       Diag(ImportLoc, diag::err_partition_import_outside_module);
262881ad6265SDimitry Andric     else
262981ad6265SDimitry Andric       SeenError = false;
263081ad6265SDimitry Andric     break;
263181ad6265SDimitry Andric   case Sema::ModuleImportState::GlobalFragment:
2632bdd1243dSDimitry Andric   case Sema::ModuleImportState::PrivateFragmentImportAllowed:
2633bdd1243dSDimitry Andric     // We can only have pre-processor directives in the global module fragment
2634bdd1243dSDimitry Andric     // which allows pp-import, but not of a partition (since the global module
2635bdd1243dSDimitry Andric     // does not have partitions).
2636bdd1243dSDimitry Andric     // We cannot import a partition into a private module fragment, since
2637bdd1243dSDimitry Andric     // [module.private.frag]/1 disallows private module fragments in a multi-
2638bdd1243dSDimitry Andric     // TU module.
2639bdd1243dSDimitry Andric     if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2640bdd1243dSDimitry Andric                                           Module::ModuleKind::ModuleHeaderUnit))
2641bdd1243dSDimitry Andric       Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2642bdd1243dSDimitry Andric           << IsPartition
2643bdd1243dSDimitry Andric           << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
264481ad6265SDimitry Andric     else
264581ad6265SDimitry Andric       SeenError = false;
264681ad6265SDimitry Andric     break;
264781ad6265SDimitry Andric   case Sema::ModuleImportState::ImportFinished:
2648bdd1243dSDimitry Andric   case Sema::ModuleImportState::PrivateFragmentImportFinished:
264981ad6265SDimitry Andric     if (getLangOpts().CPlusPlusModules)
265081ad6265SDimitry Andric       Diag(ImportLoc, diag::err_import_not_allowed_here);
265181ad6265SDimitry Andric     else
265281ad6265SDimitry Andric       SeenError = false;
265381ad6265SDimitry Andric     break;
265481ad6265SDimitry Andric   }
265581ad6265SDimitry Andric   if (SeenError) {
265681ad6265SDimitry Andric     ExpectAndConsumeSemi(diag::err_module_expected_semi);
265781ad6265SDimitry Andric     return nullptr;
265881ad6265SDimitry Andric   }
265981ad6265SDimitry Andric 
26600b57cec5SDimitry Andric   DeclResult Import;
26610b57cec5SDimitry Andric   if (HeaderUnit)
26620b57cec5SDimitry Andric     Import =
26630b57cec5SDimitry Andric         Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
26640b57cec5SDimitry Andric   else if (!Path.empty())
266581ad6265SDimitry Andric     Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
266681ad6265SDimitry Andric                                        IsPartition);
26670b57cec5SDimitry Andric   ExpectAndConsumeSemi(diag::err_module_expected_semi);
26680b57cec5SDimitry Andric   if (Import.isInvalid())
26690b57cec5SDimitry Andric     return nullptr;
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   // Using '@import' in framework headers requires modules to be enabled so that
26720b57cec5SDimitry Andric   // the header is parseable. Emit a warning to make the user aware.
26730b57cec5SDimitry Andric   if (IsObjCAtImport && AtLoc.isValid()) {
26740b57cec5SDimitry Andric     auto &SrcMgr = PP.getSourceManager();
267581ad6265SDimitry Andric     auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
267681ad6265SDimitry Andric     if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
26775f757f3fSDimitry Andric                   .ends_with(".framework"))
26780b57cec5SDimitry Andric       Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
26790b57cec5SDimitry Andric   }
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   return Import.get();
26820b57cec5SDimitry Andric }
26830b57cec5SDimitry Andric 
268406c3fb27SDimitry Andric /// Parse a C++ / Objective-C module name (both forms use the same
26850b57cec5SDimitry Andric /// grammar).
26860b57cec5SDimitry Andric ///
26870b57cec5SDimitry Andric ///         module-name:
26880b57cec5SDimitry Andric ///           module-name-qualifier[opt] identifier
26890b57cec5SDimitry Andric ///         module-name-qualifier:
26900b57cec5SDimitry Andric ///           module-name-qualifier[opt] identifier '.'
ParseModuleName(SourceLocation UseLoc,SmallVectorImpl<std::pair<IdentifierInfo *,SourceLocation>> & Path,bool IsImport)26910b57cec5SDimitry Andric bool Parser::ParseModuleName(
26920b57cec5SDimitry Andric     SourceLocation UseLoc,
26930b57cec5SDimitry Andric     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
26940b57cec5SDimitry Andric     bool IsImport) {
26950b57cec5SDimitry Andric   // Parse the module path.
26960b57cec5SDimitry Andric   while (true) {
26970b57cec5SDimitry Andric     if (!Tok.is(tok::identifier)) {
26980b57cec5SDimitry Andric       if (Tok.is(tok::code_completion)) {
26990b57cec5SDimitry Andric         cutOffParsing();
2700*0fca6ea1SDimitry Andric         Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);
27010b57cec5SDimitry Andric         return true;
27020b57cec5SDimitry Andric       }
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric       Diag(Tok, diag::err_module_expected_ident) << IsImport;
27050b57cec5SDimitry Andric       SkipUntil(tok::semi);
27060b57cec5SDimitry Andric       return true;
27070b57cec5SDimitry Andric     }
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric     // Record this part of the module path.
27100b57cec5SDimitry Andric     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
27110b57cec5SDimitry Andric     ConsumeToken();
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric     if (Tok.isNot(tok::period))
27140b57cec5SDimitry Andric       return false;
27150b57cec5SDimitry Andric 
27160b57cec5SDimitry Andric     ConsumeToken();
27170b57cec5SDimitry Andric   }
27180b57cec5SDimitry Andric }
27190b57cec5SDimitry Andric 
27200b57cec5SDimitry Andric /// Try recover parser when module annotation appears where it must not
27210b57cec5SDimitry Andric /// be found.
27220b57cec5SDimitry Andric /// \returns false if the recover was successful and parsing may be continued, or
27230b57cec5SDimitry Andric /// true if parser must bail out to top level and handle the token there.
parseMisplacedModuleImport()27240b57cec5SDimitry Andric bool Parser::parseMisplacedModuleImport() {
27250b57cec5SDimitry Andric   while (true) {
27260b57cec5SDimitry Andric     switch (Tok.getKind()) {
27270b57cec5SDimitry Andric     case tok::annot_module_end:
27280b57cec5SDimitry Andric       // If we recovered from a misplaced module begin, we expect to hit a
27290b57cec5SDimitry Andric       // misplaced module end too. Stay in the current context when this
27300b57cec5SDimitry Andric       // happens.
27310b57cec5SDimitry Andric       if (MisplacedModuleBeginCount) {
27320b57cec5SDimitry Andric         --MisplacedModuleBeginCount;
2733*0fca6ea1SDimitry Andric         Actions.ActOnAnnotModuleEnd(
2734*0fca6ea1SDimitry Andric             Tok.getLocation(),
2735*0fca6ea1SDimitry Andric             reinterpret_cast<Module *>(Tok.getAnnotationValue()));
27360b57cec5SDimitry Andric         ConsumeAnnotationToken();
27370b57cec5SDimitry Andric         continue;
27380b57cec5SDimitry Andric       }
27390b57cec5SDimitry Andric       // Inform caller that recovery failed, the error must be handled at upper
27400b57cec5SDimitry Andric       // level. This will generate the desired "missing '}' at end of module"
27410b57cec5SDimitry Andric       // diagnostics on the way out.
27420b57cec5SDimitry Andric       return true;
27430b57cec5SDimitry Andric     case tok::annot_module_begin:
27440b57cec5SDimitry Andric       // Recover by entering the module (Sema will diagnose).
2745*0fca6ea1SDimitry Andric       Actions.ActOnAnnotModuleBegin(
2746*0fca6ea1SDimitry Andric           Tok.getLocation(),
2747*0fca6ea1SDimitry Andric           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
27480b57cec5SDimitry Andric       ConsumeAnnotationToken();
27490b57cec5SDimitry Andric       ++MisplacedModuleBeginCount;
27500b57cec5SDimitry Andric       continue;
27510b57cec5SDimitry Andric     case tok::annot_module_include:
27520b57cec5SDimitry Andric       // Module import found where it should not be, for instance, inside a
27530b57cec5SDimitry Andric       // namespace. Recover by importing the module.
2754*0fca6ea1SDimitry Andric       Actions.ActOnAnnotModuleInclude(
2755*0fca6ea1SDimitry Andric           Tok.getLocation(),
2756*0fca6ea1SDimitry Andric           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
27570b57cec5SDimitry Andric       ConsumeAnnotationToken();
27580b57cec5SDimitry Andric       // If there is another module import, process it.
27590b57cec5SDimitry Andric       continue;
27600b57cec5SDimitry Andric     default:
27610b57cec5SDimitry Andric       return false;
27620b57cec5SDimitry Andric     }
27630b57cec5SDimitry Andric   }
27640b57cec5SDimitry Andric   return false;
27650b57cec5SDimitry Andric }
27660b57cec5SDimitry Andric 
diagnoseUseOfC11Keyword(const Token & Tok)2767*0fca6ea1SDimitry Andric void Parser::diagnoseUseOfC11Keyword(const Token &Tok) {
2768*0fca6ea1SDimitry Andric   // Warn that this is a C11 extension if in an older mode or if in C++.
2769*0fca6ea1SDimitry Andric   // Otherwise, warn that it is incompatible with standards before C11 if in
2770*0fca6ea1SDimitry Andric   // C11 or later.
2771*0fca6ea1SDimitry Andric   Diag(Tok, getLangOpts().C11 ? diag::warn_c11_compat_keyword
2772*0fca6ea1SDimitry Andric                               : diag::ext_c11_feature)
2773*0fca6ea1SDimitry Andric       << Tok.getName();
2774*0fca6ea1SDimitry Andric }
2775*0fca6ea1SDimitry Andric 
diagnoseOverflow()27760b57cec5SDimitry Andric bool BalancedDelimiterTracker::diagnoseOverflow() {
27770b57cec5SDimitry Andric   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
27780b57cec5SDimitry Andric     << P.getLangOpts().BracketDepth;
27790b57cec5SDimitry Andric   P.Diag(P.Tok, diag::note_bracket_depth);
27800b57cec5SDimitry Andric   P.cutOffParsing();
27810b57cec5SDimitry Andric   return true;
27820b57cec5SDimitry Andric }
27830b57cec5SDimitry Andric 
expectAndConsume(unsigned DiagID,const char * Msg,tok::TokenKind SkipToTok)27840b57cec5SDimitry Andric bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
27850b57cec5SDimitry Andric                                                 const char *Msg,
27860b57cec5SDimitry Andric                                                 tok::TokenKind SkipToTok) {
27870b57cec5SDimitry Andric   LOpen = P.Tok.getLocation();
27880b57cec5SDimitry Andric   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
27890b57cec5SDimitry Andric     if (SkipToTok != tok::unknown)
27900b57cec5SDimitry Andric       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
27910b57cec5SDimitry Andric     return true;
27920b57cec5SDimitry Andric   }
27930b57cec5SDimitry Andric 
27940b57cec5SDimitry Andric   if (getDepth() < P.getLangOpts().BracketDepth)
27950b57cec5SDimitry Andric     return false;
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric   return diagnoseOverflow();
27980b57cec5SDimitry Andric }
27990b57cec5SDimitry Andric 
diagnoseMissingClose()28000b57cec5SDimitry Andric bool BalancedDelimiterTracker::diagnoseMissingClose() {
28010b57cec5SDimitry Andric   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
28020b57cec5SDimitry Andric 
28030b57cec5SDimitry Andric   if (P.Tok.is(tok::annot_module_end))
28040b57cec5SDimitry Andric     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
28050b57cec5SDimitry Andric   else
28060b57cec5SDimitry Andric     P.Diag(P.Tok, diag::err_expected) << Close;
28070b57cec5SDimitry Andric   P.Diag(LOpen, diag::note_matching) << Kind;
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   // If we're not already at some kind of closing bracket, skip to our closing
28100b57cec5SDimitry Andric   // token.
28110b57cec5SDimitry Andric   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
28120b57cec5SDimitry Andric       P.Tok.isNot(tok::r_square) &&
28130b57cec5SDimitry Andric       P.SkipUntil(Close, FinalToken,
28140b57cec5SDimitry Andric                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
28150b57cec5SDimitry Andric       P.Tok.is(Close))
28160b57cec5SDimitry Andric     LClose = P.ConsumeAnyToken();
28170b57cec5SDimitry Andric   return true;
28180b57cec5SDimitry Andric }
28190b57cec5SDimitry Andric 
skipToEnd()28200b57cec5SDimitry Andric void BalancedDelimiterTracker::skipToEnd() {
28210b57cec5SDimitry Andric   P.SkipUntil(Close, Parser::StopBeforeMatch);
28220b57cec5SDimitry Andric   consumeClose();
28230b57cec5SDimitry Andric }
2824