xref: /freebsd/contrib/llvm-project/clang/lib/Parse/Parser.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
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"
160b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
175ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
180b57cec5SDimitry Andric #include "clang/Parse/ParseDiagnostic.h"
190b57cec5SDimitry Andric #include "clang/Parse/RAIIObjectsForParser.h"
200b57cec5SDimitry Andric #include "clang/Sema/DeclSpec.h"
210b57cec5SDimitry Andric #include "clang/Sema/ParsedTemplate.h"
220b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
230b57cec5SDimitry Andric #include "llvm/Support/Path.h"
240b57cec5SDimitry Andric using namespace clang;
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric namespace {
280b57cec5SDimitry Andric /// A comment handler that passes comments found by the preprocessor
290b57cec5SDimitry Andric /// to the parser action.
300b57cec5SDimitry Andric class ActionCommentHandler : public CommentHandler {
310b57cec5SDimitry Andric   Sema &S;
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric public:
340b57cec5SDimitry Andric   explicit ActionCommentHandler(Sema &S) : S(S) { }
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric   bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
370b57cec5SDimitry Andric     S.ActOnComment(Comment);
380b57cec5SDimitry Andric     return false;
390b57cec5SDimitry Andric   }
400b57cec5SDimitry Andric };
410b57cec5SDimitry Andric } // end anonymous namespace
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric IdentifierInfo *Parser::getSEHExceptKeyword() {
440b57cec5SDimitry Andric   // __except is accepted as a (contextual) keyword
450b57cec5SDimitry Andric   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
460b57cec5SDimitry Andric     Ident__except = PP.getIdentifierInfo("__except");
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   return Ident__except;
490b57cec5SDimitry Andric }
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52fe6060f1SDimitry Andric     : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
53fe6060f1SDimitry Andric       Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
54fe6060f1SDimitry Andric       ColonIsSacred(false), InMessageExpression(false),
55fe6060f1SDimitry Andric       TemplateParameterDepth(0), ParsingInObjCContainer(false) {
560b57cec5SDimitry Andric   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
570b57cec5SDimitry Andric   Tok.startToken();
580b57cec5SDimitry Andric   Tok.setKind(tok::eof);
590b57cec5SDimitry Andric   Actions.CurScope = nullptr;
600b57cec5SDimitry Andric   NumCachedScopes = 0;
610b57cec5SDimitry Andric   CurParsedObjCImpl = nullptr;
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric   // Add #pragma handlers. These are removed and destroyed in the
640b57cec5SDimitry Andric   // destructor.
650b57cec5SDimitry Andric   initializePragmaHandlers();
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric   CommentSemaHandler.reset(new ActionCommentHandler(actions));
680b57cec5SDimitry Andric   PP.addCommentHandler(CommentSemaHandler.get());
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric   PP.setCodeCompletionHandler(*this);
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
740b57cec5SDimitry Andric   return Diags.Report(Loc, DiagID);
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
780b57cec5SDimitry Andric   return Diag(Tok.getLocation(), DiagID);
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric /// Emits a diagnostic suggesting parentheses surrounding a
820b57cec5SDimitry Andric /// given range.
830b57cec5SDimitry Andric ///
840b57cec5SDimitry Andric /// \param Loc The location where we'll emit the diagnostic.
850b57cec5SDimitry Andric /// \param DK The kind of diagnostic to emit.
860b57cec5SDimitry Andric /// \param ParenRange Source range enclosing code that should be parenthesized.
870b57cec5SDimitry Andric void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
880b57cec5SDimitry Andric                                 SourceRange ParenRange) {
890b57cec5SDimitry Andric   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
900b57cec5SDimitry Andric   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
910b57cec5SDimitry Andric     // We can't display the parentheses, so just dig the
920b57cec5SDimitry Andric     // warning/error and return.
930b57cec5SDimitry Andric     Diag(Loc, DK);
940b57cec5SDimitry Andric     return;
950b57cec5SDimitry Andric   }
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric   Diag(Loc, DK)
980b57cec5SDimitry Andric     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
990b57cec5SDimitry Andric     << FixItHint::CreateInsertion(EndLoc, ")");
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
1030b57cec5SDimitry Andric   switch (ExpectedTok) {
1040b57cec5SDimitry Andric   case tok::semi:
1050b57cec5SDimitry Andric     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
1060b57cec5SDimitry Andric   default: return false;
1070b57cec5SDimitry Andric   }
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
1110b57cec5SDimitry Andric                               StringRef Msg) {
1120b57cec5SDimitry Andric   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
1130b57cec5SDimitry Andric     ConsumeAnyToken();
1140b57cec5SDimitry Andric     return false;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   // Detect common single-character typos and resume.
1180b57cec5SDimitry Andric   if (IsCommonTypo(ExpectedTok, Tok)) {
1190b57cec5SDimitry Andric     SourceLocation Loc = Tok.getLocation();
1200b57cec5SDimitry Andric     {
1210b57cec5SDimitry Andric       DiagnosticBuilder DB = Diag(Loc, DiagID);
1220b57cec5SDimitry Andric       DB << FixItHint::CreateReplacement(
1230b57cec5SDimitry Andric                 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
1240b57cec5SDimitry Andric       if (DiagID == diag::err_expected)
1250b57cec5SDimitry Andric         DB << ExpectedTok;
1260b57cec5SDimitry Andric       else if (DiagID == diag::err_expected_after)
1270b57cec5SDimitry Andric         DB << Msg << ExpectedTok;
1280b57cec5SDimitry Andric       else
1290b57cec5SDimitry Andric         DB << Msg;
1300b57cec5SDimitry Andric     }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric     // Pretend there wasn't a problem.
1330b57cec5SDimitry Andric     ConsumeAnyToken();
1340b57cec5SDimitry Andric     return false;
1350b57cec5SDimitry Andric   }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1380b57cec5SDimitry Andric   const char *Spelling = nullptr;
1390b57cec5SDimitry Andric   if (EndLoc.isValid())
1400b57cec5SDimitry Andric     Spelling = tok::getPunctuatorSpelling(ExpectedTok);
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   DiagnosticBuilder DB =
1430b57cec5SDimitry Andric       Spelling
1440b57cec5SDimitry Andric           ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
1450b57cec5SDimitry Andric           : Diag(Tok, DiagID);
1460b57cec5SDimitry Andric   if (DiagID == diag::err_expected)
1470b57cec5SDimitry Andric     DB << ExpectedTok;
1480b57cec5SDimitry Andric   else if (DiagID == diag::err_expected_after)
1490b57cec5SDimitry Andric     DB << Msg << ExpectedTok;
1500b57cec5SDimitry Andric   else
1510b57cec5SDimitry Andric     DB << Msg;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   return true;
1540b57cec5SDimitry Andric }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
1570b57cec5SDimitry Andric   if (TryConsumeToken(tok::semi))
1580b57cec5SDimitry Andric     return false;
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   if (Tok.is(tok::code_completion)) {
1610b57cec5SDimitry Andric     handleUnexpectedCodeCompletionToken();
1620b57cec5SDimitry Andric     return false;
1630b57cec5SDimitry Andric   }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
1660b57cec5SDimitry Andric       NextToken().is(tok::semi)) {
1670b57cec5SDimitry Andric     Diag(Tok, diag::err_extraneous_token_before_semi)
1680b57cec5SDimitry Andric       << PP.getSpelling(Tok)
1690b57cec5SDimitry Andric       << FixItHint::CreateRemoval(Tok.getLocation());
1700b57cec5SDimitry Andric     ConsumeAnyToken(); // The ')' or ']'.
1710b57cec5SDimitry Andric     ConsumeToken(); // The ';'.
1720b57cec5SDimitry Andric     return false;
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   return ExpectAndConsume(tok::semi, DiagID);
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
178a7dea167SDimitry Andric void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
1790b57cec5SDimitry Andric   if (!Tok.is(tok::semi)) return;
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   bool HadMultipleSemis = false;
1820b57cec5SDimitry Andric   SourceLocation StartLoc = Tok.getLocation();
1830b57cec5SDimitry Andric   SourceLocation EndLoc = Tok.getLocation();
1840b57cec5SDimitry Andric   ConsumeToken();
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
1870b57cec5SDimitry Andric     HadMultipleSemis = true;
1880b57cec5SDimitry Andric     EndLoc = Tok.getLocation();
1890b57cec5SDimitry Andric     ConsumeToken();
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // C++11 allows extra semicolons at namespace scope, but not in any of the
1930b57cec5SDimitry Andric   // other contexts.
1940b57cec5SDimitry Andric   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
1950b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus11)
1960b57cec5SDimitry Andric       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
1970b57cec5SDimitry Andric           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
1980b57cec5SDimitry Andric     else
1990b57cec5SDimitry Andric       Diag(StartLoc, diag::ext_extra_semi_cxx11)
2000b57cec5SDimitry Andric           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2010b57cec5SDimitry Andric     return;
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
2050b57cec5SDimitry Andric     Diag(StartLoc, diag::ext_extra_semi)
206a7dea167SDimitry Andric         << Kind << DeclSpec::getSpecifierName(TST,
2070b57cec5SDimitry Andric                                     Actions.getASTContext().getPrintingPolicy())
2080b57cec5SDimitry Andric         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2090b57cec5SDimitry Andric   else
2100b57cec5SDimitry Andric     // A single semicolon is valid after a member function definition.
2110b57cec5SDimitry Andric     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
2120b57cec5SDimitry Andric       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric bool Parser::expectIdentifier() {
2160b57cec5SDimitry Andric   if (Tok.is(tok::identifier))
2170b57cec5SDimitry Andric     return false;
2180b57cec5SDimitry Andric   if (const auto *II = Tok.getIdentifierInfo()) {
2190b57cec5SDimitry Andric     if (II->isCPlusPlusKeyword(getLangOpts())) {
2200b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
2210b57cec5SDimitry Andric           << tok::identifier << Tok.getIdentifierInfo();
2220b57cec5SDimitry Andric       // Objective-C++: Recover by treating this keyword as a valid identifier.
2230b57cec5SDimitry Andric       return false;
2240b57cec5SDimitry Andric     }
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric   Diag(Tok, diag::err_expected) << tok::identifier;
2270b57cec5SDimitry Andric   return true;
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric 
230e8d8bef9SDimitry Andric void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
231e8d8bef9SDimitry Andric                                 tok::TokenKind FirstTokKind, CompoundToken Op) {
232e8d8bef9SDimitry Andric   if (FirstTokLoc.isInvalid())
233e8d8bef9SDimitry Andric     return;
234e8d8bef9SDimitry Andric   SourceLocation SecondTokLoc = Tok.getLocation();
235e8d8bef9SDimitry Andric 
236e8d8bef9SDimitry Andric   // If either token is in a macro, we expect both tokens to come from the same
237e8d8bef9SDimitry Andric   // macro expansion.
238e8d8bef9SDimitry Andric   if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
239e8d8bef9SDimitry Andric       PP.getSourceManager().getFileID(FirstTokLoc) !=
240e8d8bef9SDimitry Andric           PP.getSourceManager().getFileID(SecondTokLoc)) {
241e8d8bef9SDimitry Andric     Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
242e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
243e8d8bef9SDimitry Andric         << static_cast<int>(Op) << SourceRange(FirstTokLoc);
244e8d8bef9SDimitry Andric     Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
245e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << Tok.getKind()
246e8d8bef9SDimitry Andric         << SourceRange(SecondTokLoc);
247e8d8bef9SDimitry Andric     return;
248e8d8bef9SDimitry Andric   }
249e8d8bef9SDimitry Andric 
250e8d8bef9SDimitry Andric   // We expect the tokens to abut.
251e8d8bef9SDimitry Andric   if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
252e8d8bef9SDimitry Andric     SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
253e8d8bef9SDimitry Andric     if (SpaceLoc.isInvalid())
254e8d8bef9SDimitry Andric       SpaceLoc = FirstTokLoc;
255e8d8bef9SDimitry Andric     Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
256e8d8bef9SDimitry Andric         << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
257e8d8bef9SDimitry Andric         << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
258e8d8bef9SDimitry Andric     return;
259e8d8bef9SDimitry Andric   }
260e8d8bef9SDimitry Andric }
261e8d8bef9SDimitry Andric 
2620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2630b57cec5SDimitry Andric // Error recovery.
2640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
2670b57cec5SDimitry Andric   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric /// SkipUntil - Read tokens until we get to the specified token, then consume
2710b57cec5SDimitry Andric /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
2720b57cec5SDimitry Andric /// token will ever occur, this skips to the next token, or to some likely
2730b57cec5SDimitry Andric /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
2740b57cec5SDimitry Andric /// character.
2750b57cec5SDimitry Andric ///
2760b57cec5SDimitry Andric /// If SkipUntil finds the specified token, it returns true, otherwise it
2770b57cec5SDimitry Andric /// returns false.
2780b57cec5SDimitry Andric bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
2790b57cec5SDimitry Andric   // We always want this function to skip at least one token if the first token
2800b57cec5SDimitry Andric   // isn't T and if not at EOF.
2810b57cec5SDimitry Andric   bool isFirstTokenSkipped = true;
2820b57cec5SDimitry Andric   while (1) {
2830b57cec5SDimitry Andric     // If we found one of the tokens, stop and return true.
2840b57cec5SDimitry Andric     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
2850b57cec5SDimitry Andric       if (Tok.is(Toks[i])) {
2860b57cec5SDimitry Andric         if (HasFlagsSet(Flags, StopBeforeMatch)) {
2870b57cec5SDimitry Andric           // Noop, don't consume the token.
2880b57cec5SDimitry Andric         } else {
2890b57cec5SDimitry Andric           ConsumeAnyToken();
2900b57cec5SDimitry Andric         }
2910b57cec5SDimitry Andric         return true;
2920b57cec5SDimitry Andric       }
2930b57cec5SDimitry Andric     }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric     // Important special case: The caller has given up and just wants us to
2960b57cec5SDimitry Andric     // skip the rest of the file. Do this without recursing, since we can
2970b57cec5SDimitry Andric     // get here precisely because the caller detected too much recursion.
2980b57cec5SDimitry Andric     if (Toks.size() == 1 && Toks[0] == tok::eof &&
2990b57cec5SDimitry Andric         !HasFlagsSet(Flags, StopAtSemi) &&
3000b57cec5SDimitry Andric         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
3010b57cec5SDimitry Andric       while (Tok.isNot(tok::eof))
3020b57cec5SDimitry Andric         ConsumeAnyToken();
3030b57cec5SDimitry Andric       return true;
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric     switch (Tok.getKind()) {
3070b57cec5SDimitry Andric     case tok::eof:
3080b57cec5SDimitry Andric       // Ran out of tokens.
3090b57cec5SDimitry Andric       return false;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric     case tok::annot_pragma_openmp:
312fe6060f1SDimitry Andric     case tok::annot_attr_openmp:
3130b57cec5SDimitry Andric     case tok::annot_pragma_openmp_end:
3140b57cec5SDimitry Andric       // Stop before an OpenMP pragma boundary.
315480093f4SDimitry Andric       if (OpenMPDirectiveParsing)
316480093f4SDimitry Andric         return false;
317480093f4SDimitry Andric       ConsumeAnnotationToken();
318480093f4SDimitry Andric       break;
3190b57cec5SDimitry Andric     case tok::annot_module_begin:
3200b57cec5SDimitry Andric     case tok::annot_module_end:
3210b57cec5SDimitry Andric     case tok::annot_module_include:
3220b57cec5SDimitry Andric       // Stop before we change submodules. They generally indicate a "good"
3230b57cec5SDimitry Andric       // place to pick up parsing again (except in the special case where
3240b57cec5SDimitry Andric       // we're trying to skip to EOF).
3250b57cec5SDimitry Andric       return false;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric     case tok::code_completion:
3280b57cec5SDimitry Andric       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
3290b57cec5SDimitry Andric         handleUnexpectedCodeCompletionToken();
3300b57cec5SDimitry Andric       return false;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric     case tok::l_paren:
3330b57cec5SDimitry Andric       // Recursively skip properly-nested parens.
3340b57cec5SDimitry Andric       ConsumeParen();
3350b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3360b57cec5SDimitry Andric         SkipUntil(tok::r_paren, StopAtCodeCompletion);
3370b57cec5SDimitry Andric       else
3380b57cec5SDimitry Andric         SkipUntil(tok::r_paren);
3390b57cec5SDimitry Andric       break;
3400b57cec5SDimitry Andric     case tok::l_square:
3410b57cec5SDimitry Andric       // Recursively skip properly-nested square brackets.
3420b57cec5SDimitry Andric       ConsumeBracket();
3430b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3440b57cec5SDimitry Andric         SkipUntil(tok::r_square, StopAtCodeCompletion);
3450b57cec5SDimitry Andric       else
3460b57cec5SDimitry Andric         SkipUntil(tok::r_square);
3470b57cec5SDimitry Andric       break;
3480b57cec5SDimitry Andric     case tok::l_brace:
3490b57cec5SDimitry Andric       // Recursively skip properly-nested braces.
3500b57cec5SDimitry Andric       ConsumeBrace();
3510b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtCodeCompletion))
3520b57cec5SDimitry Andric         SkipUntil(tok::r_brace, StopAtCodeCompletion);
3530b57cec5SDimitry Andric       else
3540b57cec5SDimitry Andric         SkipUntil(tok::r_brace);
3550b57cec5SDimitry Andric       break;
3560b57cec5SDimitry Andric     case tok::question:
3570b57cec5SDimitry Andric       // Recursively skip ? ... : pairs; these function as brackets. But
3580b57cec5SDimitry Andric       // still stop at a semicolon if requested.
3590b57cec5SDimitry Andric       ConsumeToken();
3600b57cec5SDimitry Andric       SkipUntil(tok::colon,
3610b57cec5SDimitry Andric                 SkipUntilFlags(unsigned(Flags) &
3620b57cec5SDimitry Andric                                unsigned(StopAtCodeCompletion | StopAtSemi)));
3630b57cec5SDimitry Andric       break;
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
3660b57cec5SDimitry Andric     // Since the user wasn't looking for this token (if they were, it would
3670b57cec5SDimitry Andric     // already be handled), this isn't balanced.  If there is a LHS token at a
3680b57cec5SDimitry Andric     // higher level, we will assume that this matches the unbalanced token
3690b57cec5SDimitry Andric     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
3700b57cec5SDimitry Andric     case tok::r_paren:
3710b57cec5SDimitry Andric       if (ParenCount && !isFirstTokenSkipped)
3720b57cec5SDimitry Andric         return false;  // Matches something.
3730b57cec5SDimitry Andric       ConsumeParen();
3740b57cec5SDimitry Andric       break;
3750b57cec5SDimitry Andric     case tok::r_square:
3760b57cec5SDimitry Andric       if (BracketCount && !isFirstTokenSkipped)
3770b57cec5SDimitry Andric         return false;  // Matches something.
3780b57cec5SDimitry Andric       ConsumeBracket();
3790b57cec5SDimitry Andric       break;
3800b57cec5SDimitry Andric     case tok::r_brace:
3810b57cec5SDimitry Andric       if (BraceCount && !isFirstTokenSkipped)
3820b57cec5SDimitry Andric         return false;  // Matches something.
3830b57cec5SDimitry Andric       ConsumeBrace();
3840b57cec5SDimitry Andric       break;
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     case tok::semi:
3870b57cec5SDimitry Andric       if (HasFlagsSet(Flags, StopAtSemi))
3880b57cec5SDimitry Andric         return false;
3890b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
3900b57cec5SDimitry Andric     default:
3910b57cec5SDimitry Andric       // Skip this token.
3920b57cec5SDimitry Andric       ConsumeAnyToken();
3930b57cec5SDimitry Andric       break;
3940b57cec5SDimitry Andric     }
3950b57cec5SDimitry Andric     isFirstTokenSkipped = false;
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4000b57cec5SDimitry Andric // Scope manipulation
4010b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric /// EnterScope - Start a new scope.
4040b57cec5SDimitry Andric void Parser::EnterScope(unsigned ScopeFlags) {
4050b57cec5SDimitry Andric   if (NumCachedScopes) {
4060b57cec5SDimitry Andric     Scope *N = ScopeCache[--NumCachedScopes];
4070b57cec5SDimitry Andric     N->Init(getCurScope(), ScopeFlags);
4080b57cec5SDimitry Andric     Actions.CurScope = N;
4090b57cec5SDimitry Andric   } else {
4100b57cec5SDimitry Andric     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric /// ExitScope - Pop a scope off the scope stack.
4150b57cec5SDimitry Andric void Parser::ExitScope() {
4160b57cec5SDimitry Andric   assert(getCurScope() && "Scope imbalance!");
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   // Inform the actions module that this scope is going away if there are any
4190b57cec5SDimitry Andric   // decls in it.
4200b57cec5SDimitry Andric   Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   Scope *OldScope = getCurScope();
4230b57cec5SDimitry Andric   Actions.CurScope = OldScope->getParent();
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   if (NumCachedScopes == ScopeCacheSize)
4260b57cec5SDimitry Andric     delete OldScope;
4270b57cec5SDimitry Andric   else
4280b57cec5SDimitry Andric     ScopeCache[NumCachedScopes++] = OldScope;
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
4320b57cec5SDimitry Andric /// this object does nothing.
4330b57cec5SDimitry Andric Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
4340b57cec5SDimitry Andric                                  bool ManageFlags)
4350b57cec5SDimitry Andric   : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
4360b57cec5SDimitry Andric   if (CurScope) {
4370b57cec5SDimitry Andric     OldFlags = CurScope->getFlags();
4380b57cec5SDimitry Andric     CurScope->setFlags(ScopeFlags);
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric /// Restore the flags for the current scope to what they were before this
4430b57cec5SDimitry Andric /// object overrode them.
4440b57cec5SDimitry Andric Parser::ParseScopeFlags::~ParseScopeFlags() {
4450b57cec5SDimitry Andric   if (CurScope)
4460b57cec5SDimitry Andric     CurScope->setFlags(OldFlags);
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4510b57cec5SDimitry Andric // C99 6.9: External Definitions.
4520b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric Parser::~Parser() {
4550b57cec5SDimitry Andric   // If we still have scopes active, delete the scope tree.
4560b57cec5SDimitry Andric   delete getCurScope();
4570b57cec5SDimitry Andric   Actions.CurScope = nullptr;
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // Free the scope cache.
4600b57cec5SDimitry Andric   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
4610b57cec5SDimitry Andric     delete ScopeCache[i];
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   resetPragmaHandlers();
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   PP.removeCommentHandler(CommentSemaHandler.get());
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   PP.clearCodeCompletionHandler();
4680b57cec5SDimitry Andric 
4695ffd83dbSDimitry Andric   DestroyTemplateIds();
4700b57cec5SDimitry Andric }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric /// Initialize - Warm up the parser.
4730b57cec5SDimitry Andric ///
4740b57cec5SDimitry Andric void Parser::Initialize() {
4750b57cec5SDimitry Andric   // Create the translation unit scope.  Install it as the current scope.
4760b57cec5SDimitry Andric   assert(getCurScope() == nullptr && "A scope is already active?");
4770b57cec5SDimitry Andric   EnterScope(Scope::DeclScope);
4780b57cec5SDimitry Andric   Actions.ActOnTranslationUnitScope(getCurScope());
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // Initialization for Objective-C context sensitive keywords recognition.
4810b57cec5SDimitry Andric   // Referenced in Parser::ParseObjCTypeQualifierList.
4820b57cec5SDimitry Andric   if (getLangOpts().ObjC) {
4830b57cec5SDimitry Andric     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
4840b57cec5SDimitry Andric     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
4850b57cec5SDimitry Andric     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
4860b57cec5SDimitry Andric     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
4870b57cec5SDimitry Andric     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
4880b57cec5SDimitry Andric     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
4890b57cec5SDimitry Andric     ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
4900b57cec5SDimitry Andric     ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
4910b57cec5SDimitry Andric     ObjCTypeQuals[objc_null_unspecified]
4920b57cec5SDimitry Andric       = &PP.getIdentifierTable().get("null_unspecified");
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   Ident_instancetype = nullptr;
4960b57cec5SDimitry Andric   Ident_final = nullptr;
4970b57cec5SDimitry Andric   Ident_sealed = nullptr;
498fe6060f1SDimitry Andric   Ident_abstract = nullptr;
4990b57cec5SDimitry Andric   Ident_override = nullptr;
5000b57cec5SDimitry Andric   Ident_GNU_final = nullptr;
5010b57cec5SDimitry Andric   Ident_import = nullptr;
5020b57cec5SDimitry Andric   Ident_module = nullptr;
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   Ident_super = &PP.getIdentifierTable().get("super");
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   Ident_vector = nullptr;
5070b57cec5SDimitry Andric   Ident_bool = nullptr;
508fe6060f1SDimitry Andric   Ident_Bool = nullptr;
5090b57cec5SDimitry Andric   Ident_pixel = nullptr;
5100b57cec5SDimitry Andric   if (getLangOpts().AltiVec || getLangOpts().ZVector) {
5110b57cec5SDimitry Andric     Ident_vector = &PP.getIdentifierTable().get("vector");
5120b57cec5SDimitry Andric     Ident_bool = &PP.getIdentifierTable().get("bool");
513fe6060f1SDimitry Andric     Ident_Bool = &PP.getIdentifierTable().get("_Bool");
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric   if (getLangOpts().AltiVec)
5160b57cec5SDimitry Andric     Ident_pixel = &PP.getIdentifierTable().get("pixel");
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   Ident_introduced = nullptr;
5190b57cec5SDimitry Andric   Ident_deprecated = nullptr;
5200b57cec5SDimitry Andric   Ident_obsoleted = nullptr;
5210b57cec5SDimitry Andric   Ident_unavailable = nullptr;
5220b57cec5SDimitry Andric   Ident_strict = nullptr;
5230b57cec5SDimitry Andric   Ident_replacement = nullptr;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   Ident__except = nullptr;
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   Ident__exception_code = Ident__exception_info = nullptr;
5300b57cec5SDimitry Andric   Ident__abnormal_termination = Ident___exception_code = nullptr;
5310b57cec5SDimitry Andric   Ident___exception_info = Ident___abnormal_termination = nullptr;
5320b57cec5SDimitry Andric   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
5330b57cec5SDimitry Andric   Ident_AbnormalTermination = nullptr;
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   if(getLangOpts().Borland) {
5360b57cec5SDimitry Andric     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
5370b57cec5SDimitry Andric     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
5380b57cec5SDimitry Andric     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
5390b57cec5SDimitry Andric     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
5400b57cec5SDimitry Andric     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
5410b57cec5SDimitry Andric     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
5420b57cec5SDimitry Andric     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
5430b57cec5SDimitry Andric     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
5440b57cec5SDimitry Andric     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
5470b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
5480b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
5490b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
5500b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
5510b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
5520b57cec5SDimitry Andric     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
5530b57cec5SDimitry Andric     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
5540b57cec5SDimitry Andric     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
5550b57cec5SDimitry Andric   }
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules) {
5580b57cec5SDimitry Andric     Ident_import = PP.getIdentifierInfo("import");
5590b57cec5SDimitry Andric     Ident_module = PP.getIdentifierInfo("module");
5600b57cec5SDimitry Andric   }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   Actions.Initialize();
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   // Prime the lexer look-ahead.
5650b57cec5SDimitry Andric   ConsumeToken();
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric 
5685ffd83dbSDimitry Andric void Parser::DestroyTemplateIds() {
5695ffd83dbSDimitry Andric   for (TemplateIdAnnotation *Id : TemplateIds)
5705ffd83dbSDimitry Andric     Id->Destroy();
5715ffd83dbSDimitry Andric   TemplateIds.clear();
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric /// Parse the first top-level declaration in a translation unit.
5750b57cec5SDimitry Andric ///
5760b57cec5SDimitry Andric ///   translation-unit:
5770b57cec5SDimitry Andric /// [C]     external-declaration
5780b57cec5SDimitry Andric /// [C]     translation-unit external-declaration
5790b57cec5SDimitry Andric /// [C++]   top-level-declaration-seq[opt]
5800b57cec5SDimitry Andric /// [C++20] global-module-fragment[opt] module-declaration
5810b57cec5SDimitry Andric ///                 top-level-declaration-seq[opt] private-module-fragment[opt]
5820b57cec5SDimitry Andric ///
5830b57cec5SDimitry Andric /// Note that in C, it is an error if there is no first declaration.
5840b57cec5SDimitry Andric bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result) {
5850b57cec5SDimitry Andric   Actions.ActOnStartOfTranslationUnit();
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   // C11 6.9p1 says translation units must have at least one top-level
5880b57cec5SDimitry Andric   // declaration. C++ doesn't have this restriction. We also don't want to
5890b57cec5SDimitry Andric   // complain if we have a precompiled header, although technically if the PCH
5900b57cec5SDimitry Andric   // is empty we should still emit the (pedantic) diagnostic.
591e8d8bef9SDimitry Andric   // If the main file is a header, we're only pretending it's a TU; don't warn.
5920b57cec5SDimitry Andric   bool NoTopLevelDecls = ParseTopLevelDecl(Result, true);
5930b57cec5SDimitry Andric   if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
594e8d8bef9SDimitry Andric       !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
5950b57cec5SDimitry Andric     Diag(diag::ext_empty_translation_unit);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   return NoTopLevelDecls;
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
6010b57cec5SDimitry Andric /// action tells us to.  This returns true if the EOF was encountered.
6020b57cec5SDimitry Andric ///
6030b57cec5SDimitry Andric ///   top-level-declaration:
6040b57cec5SDimitry Andric ///           declaration
6050b57cec5SDimitry Andric /// [C++20]   module-import-declaration
6060b57cec5SDimitry Andric bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl) {
6075ffd83dbSDimitry Andric   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   // Skip over the EOF token, flagging end of previous input for incremental
6100b57cec5SDimitry Andric   // processing
6110b57cec5SDimitry Andric   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
6120b57cec5SDimitry Andric     ConsumeToken();
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   Result = nullptr;
6150b57cec5SDimitry Andric   switch (Tok.getKind()) {
6160b57cec5SDimitry Andric   case tok::annot_pragma_unused:
6170b57cec5SDimitry Andric     HandlePragmaUnused();
6180b57cec5SDimitry Andric     return false;
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   case tok::kw_export:
6210b57cec5SDimitry Andric     switch (NextToken().getKind()) {
6220b57cec5SDimitry Andric     case tok::kw_module:
6230b57cec5SDimitry Andric       goto module_decl;
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric     // Note: no need to handle kw_import here. We only form kw_import under
6260b57cec5SDimitry Andric     // the Modules TS, and in that case 'export import' is parsed as an
6270b57cec5SDimitry Andric     // export-declaration containing an import-declaration.
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric     // Recognize context-sensitive C++20 'export module' and 'export import'
6300b57cec5SDimitry Andric     // declarations.
6310b57cec5SDimitry Andric     case tok::identifier: {
6320b57cec5SDimitry Andric       IdentifierInfo *II = NextToken().getIdentifierInfo();
6330b57cec5SDimitry Andric       if ((II == Ident_module || II == Ident_import) &&
6340b57cec5SDimitry Andric           GetLookAheadToken(2).isNot(tok::coloncolon)) {
6350b57cec5SDimitry Andric         if (II == Ident_module)
6360b57cec5SDimitry Andric           goto module_decl;
6370b57cec5SDimitry Andric         else
6380b57cec5SDimitry Andric           goto import_decl;
6390b57cec5SDimitry Andric       }
6400b57cec5SDimitry Andric       break;
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric     default:
6440b57cec5SDimitry Andric       break;
6450b57cec5SDimitry Andric     }
6460b57cec5SDimitry Andric     break;
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   case tok::kw_module:
6490b57cec5SDimitry Andric   module_decl:
6500b57cec5SDimitry Andric     Result = ParseModuleDecl(IsFirstDecl);
6510b57cec5SDimitry Andric     return false;
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric   // tok::kw_import is handled by ParseExternalDeclaration. (Under the Modules
6540b57cec5SDimitry Andric   // TS, an import can occur within an export block.)
6550b57cec5SDimitry Andric   import_decl: {
6560b57cec5SDimitry Andric     Decl *ImportDecl = ParseModuleImport(SourceLocation());
6570b57cec5SDimitry Andric     Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
6580b57cec5SDimitry Andric     return false;
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   case tok::annot_module_include:
6620b57cec5SDimitry Andric     Actions.ActOnModuleInclude(Tok.getLocation(),
6630b57cec5SDimitry Andric                                reinterpret_cast<Module *>(
6640b57cec5SDimitry Andric                                    Tok.getAnnotationValue()));
6650b57cec5SDimitry Andric     ConsumeAnnotationToken();
6660b57cec5SDimitry Andric     return false;
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   case tok::annot_module_begin:
6690b57cec5SDimitry Andric     Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
6700b57cec5SDimitry Andric                                                     Tok.getAnnotationValue()));
6710b57cec5SDimitry Andric     ConsumeAnnotationToken();
6720b57cec5SDimitry Andric     return false;
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   case tok::annot_module_end:
6750b57cec5SDimitry Andric     Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
6760b57cec5SDimitry Andric                                                   Tok.getAnnotationValue()));
6770b57cec5SDimitry Andric     ConsumeAnnotationToken();
6780b57cec5SDimitry Andric     return false;
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   case tok::eof:
6815ffd83dbSDimitry Andric     // Check whether -fmax-tokens= was reached.
6825ffd83dbSDimitry Andric     if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
6835ffd83dbSDimitry Andric       PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
6845ffd83dbSDimitry Andric           << PP.getTokenCount() << PP.getMaxTokens();
6855ffd83dbSDimitry Andric       SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
6865ffd83dbSDimitry Andric       if (OverrideLoc.isValid()) {
6875ffd83dbSDimitry Andric         PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
6885ffd83dbSDimitry Andric       }
6895ffd83dbSDimitry Andric     }
6905ffd83dbSDimitry Andric 
6910b57cec5SDimitry Andric     // Late template parsing can begin.
6925ffd83dbSDimitry Andric     Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
6930b57cec5SDimitry Andric     if (!PP.isIncrementalProcessingEnabled())
6940b57cec5SDimitry Andric       Actions.ActOnEndOfTranslationUnit();
6950b57cec5SDimitry Andric     //else don't tell Sema that we ended parsing: more input might come.
6960b57cec5SDimitry Andric     return true;
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   case tok::identifier:
6990b57cec5SDimitry Andric     // C++2a [basic.link]p3:
7000b57cec5SDimitry Andric     //   A token sequence beginning with 'export[opt] module' or
7010b57cec5SDimitry Andric     //   'export[opt] import' and not immediately followed by '::'
7020b57cec5SDimitry Andric     //   is never interpreted as the declaration of a top-level-declaration.
7030b57cec5SDimitry Andric     if ((Tok.getIdentifierInfo() == Ident_module ||
7040b57cec5SDimitry Andric          Tok.getIdentifierInfo() == Ident_import) &&
7050b57cec5SDimitry Andric         NextToken().isNot(tok::coloncolon)) {
7060b57cec5SDimitry Andric       if (Tok.getIdentifierInfo() == Ident_module)
7070b57cec5SDimitry Andric         goto module_decl;
7080b57cec5SDimitry Andric       else
7090b57cec5SDimitry Andric         goto import_decl;
7100b57cec5SDimitry Andric     }
7110b57cec5SDimitry Andric     break;
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   default:
7140b57cec5SDimitry Andric     break;
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   ParsedAttributesWithRange attrs(AttrFactory);
7180b57cec5SDimitry Andric   MaybeParseCXX11Attributes(attrs);
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   Result = ParseExternalDeclaration(attrs);
7210b57cec5SDimitry Andric   return false;
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric /// ParseExternalDeclaration:
7250b57cec5SDimitry Andric ///
7260b57cec5SDimitry Andric ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
7270b57cec5SDimitry Andric ///         function-definition
7280b57cec5SDimitry Andric ///         declaration
7290b57cec5SDimitry Andric /// [GNU]   asm-definition
7300b57cec5SDimitry Andric /// [GNU]   __extension__ external-declaration
7310b57cec5SDimitry Andric /// [OBJC]  objc-class-definition
7320b57cec5SDimitry Andric /// [OBJC]  objc-class-declaration
7330b57cec5SDimitry Andric /// [OBJC]  objc-alias-declaration
7340b57cec5SDimitry Andric /// [OBJC]  objc-protocol-definition
7350b57cec5SDimitry Andric /// [OBJC]  objc-method-definition
7360b57cec5SDimitry Andric /// [OBJC]  @end
7370b57cec5SDimitry Andric /// [C++]   linkage-specification
7380b57cec5SDimitry Andric /// [GNU] asm-definition:
7390b57cec5SDimitry Andric ///         simple-asm-expr ';'
7400b57cec5SDimitry Andric /// [C++11] empty-declaration
7410b57cec5SDimitry Andric /// [C++11] attribute-declaration
7420b57cec5SDimitry Andric ///
7430b57cec5SDimitry Andric /// [C++11] empty-declaration:
7440b57cec5SDimitry Andric ///           ';'
7450b57cec5SDimitry Andric ///
7460b57cec5SDimitry Andric /// [C++0x/GNU] 'extern' 'template' declaration
7470b57cec5SDimitry Andric ///
7480b57cec5SDimitry Andric /// [Modules-TS] module-import-declaration
7490b57cec5SDimitry Andric ///
7500b57cec5SDimitry Andric Parser::DeclGroupPtrTy
7510b57cec5SDimitry Andric Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
7520b57cec5SDimitry Andric                                  ParsingDeclSpec *DS) {
7535ffd83dbSDimitry Andric   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
7540b57cec5SDimitry Andric   ParenBraceBracketBalancer BalancerRAIIObj(*this);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   if (PP.isCodeCompletionReached()) {
7570b57cec5SDimitry Andric     cutOffParsing();
7580b57cec5SDimitry Andric     return nullptr;
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   Decl *SingleDecl = nullptr;
7620b57cec5SDimitry Andric   switch (Tok.getKind()) {
7630b57cec5SDimitry Andric   case tok::annot_pragma_vis:
7640b57cec5SDimitry Andric     HandlePragmaVisibility();
7650b57cec5SDimitry Andric     return nullptr;
7660b57cec5SDimitry Andric   case tok::annot_pragma_pack:
7670b57cec5SDimitry Andric     HandlePragmaPack();
7680b57cec5SDimitry Andric     return nullptr;
7690b57cec5SDimitry Andric   case tok::annot_pragma_msstruct:
7700b57cec5SDimitry Andric     HandlePragmaMSStruct();
7710b57cec5SDimitry Andric     return nullptr;
7720b57cec5SDimitry Andric   case tok::annot_pragma_align:
7730b57cec5SDimitry Andric     HandlePragmaAlign();
7740b57cec5SDimitry Andric     return nullptr;
7750b57cec5SDimitry Andric   case tok::annot_pragma_weak:
7760b57cec5SDimitry Andric     HandlePragmaWeak();
7770b57cec5SDimitry Andric     return nullptr;
7780b57cec5SDimitry Andric   case tok::annot_pragma_weakalias:
7790b57cec5SDimitry Andric     HandlePragmaWeakAlias();
7800b57cec5SDimitry Andric     return nullptr;
7810b57cec5SDimitry Andric   case tok::annot_pragma_redefine_extname:
7820b57cec5SDimitry Andric     HandlePragmaRedefineExtname();
7830b57cec5SDimitry Andric     return nullptr;
7840b57cec5SDimitry Andric   case tok::annot_pragma_fp_contract:
7850b57cec5SDimitry Andric     HandlePragmaFPContract();
7860b57cec5SDimitry Andric     return nullptr;
7870b57cec5SDimitry Andric   case tok::annot_pragma_fenv_access:
788*349cc55cSDimitry Andric   case tok::annot_pragma_fenv_access_ms:
7890b57cec5SDimitry Andric     HandlePragmaFEnvAccess();
7900b57cec5SDimitry Andric     return nullptr;
791e8d8bef9SDimitry Andric   case tok::annot_pragma_fenv_round:
792e8d8bef9SDimitry Andric     HandlePragmaFEnvRound();
793e8d8bef9SDimitry Andric     return nullptr;
7945ffd83dbSDimitry Andric   case tok::annot_pragma_float_control:
7955ffd83dbSDimitry Andric     HandlePragmaFloatControl();
7965ffd83dbSDimitry Andric     return nullptr;
7970b57cec5SDimitry Andric   case tok::annot_pragma_fp:
7980b57cec5SDimitry Andric     HandlePragmaFP();
7990b57cec5SDimitry Andric     break;
8000b57cec5SDimitry Andric   case tok::annot_pragma_opencl_extension:
8010b57cec5SDimitry Andric     HandlePragmaOpenCLExtension();
8020b57cec5SDimitry Andric     return nullptr;
803fe6060f1SDimitry Andric   case tok::annot_attr_openmp:
8040b57cec5SDimitry Andric   case tok::annot_pragma_openmp: {
8050b57cec5SDimitry Andric     AccessSpecifier AS = AS_none;
8060b57cec5SDimitry Andric     return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric   case tok::annot_pragma_ms_pointers_to_members:
8090b57cec5SDimitry Andric     HandlePragmaMSPointersToMembers();
8100b57cec5SDimitry Andric     return nullptr;
8110b57cec5SDimitry Andric   case tok::annot_pragma_ms_vtordisp:
8120b57cec5SDimitry Andric     HandlePragmaMSVtorDisp();
8130b57cec5SDimitry Andric     return nullptr;
8140b57cec5SDimitry Andric   case tok::annot_pragma_ms_pragma:
8150b57cec5SDimitry Andric     HandlePragmaMSPragma();
8160b57cec5SDimitry Andric     return nullptr;
8170b57cec5SDimitry Andric   case tok::annot_pragma_dump:
8180b57cec5SDimitry Andric     HandlePragmaDump();
8190b57cec5SDimitry Andric     return nullptr;
8200b57cec5SDimitry Andric   case tok::annot_pragma_attribute:
8210b57cec5SDimitry Andric     HandlePragmaAttribute();
8220b57cec5SDimitry Andric     return nullptr;
8230b57cec5SDimitry Andric   case tok::semi:
8240b57cec5SDimitry Andric     // Either a C++11 empty-declaration or attribute-declaration.
8250b57cec5SDimitry Andric     SingleDecl =
8260b57cec5SDimitry Andric         Actions.ActOnEmptyDeclaration(getCurScope(), attrs, Tok.getLocation());
8270b57cec5SDimitry Andric     ConsumeExtraSemi(OutsideFunction);
8280b57cec5SDimitry Andric     break;
8290b57cec5SDimitry Andric   case tok::r_brace:
8300b57cec5SDimitry Andric     Diag(Tok, diag::err_extraneous_closing_brace);
8310b57cec5SDimitry Andric     ConsumeBrace();
8320b57cec5SDimitry Andric     return nullptr;
8330b57cec5SDimitry Andric   case tok::eof:
8340b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_external_declaration);
8350b57cec5SDimitry Andric     return nullptr;
8360b57cec5SDimitry Andric   case tok::kw___extension__: {
8370b57cec5SDimitry Andric     // __extension__ silences extension warnings in the subexpression.
8380b57cec5SDimitry Andric     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
8390b57cec5SDimitry Andric     ConsumeToken();
8400b57cec5SDimitry Andric     return ParseExternalDeclaration(attrs);
8410b57cec5SDimitry Andric   }
8420b57cec5SDimitry Andric   case tok::kw_asm: {
8430b57cec5SDimitry Andric     ProhibitAttributes(attrs);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric     SourceLocation StartLoc = Tok.getLocation();
8460b57cec5SDimitry Andric     SourceLocation EndLoc;
8470b57cec5SDimitry Andric 
848480093f4SDimitry Andric     ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric     // Check if GNU-style InlineAsm is disabled.
8510b57cec5SDimitry Andric     // Empty asm string is allowed because it will not introduce
8520b57cec5SDimitry Andric     // any assembly code.
8530b57cec5SDimitry Andric     if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
8540b57cec5SDimitry Andric       const auto *SL = cast<StringLiteral>(Result.get());
8550b57cec5SDimitry Andric       if (!SL->getString().trim().empty())
8560b57cec5SDimitry Andric         Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
8570b57cec5SDimitry Andric     }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     ExpectAndConsume(tok::semi, diag::err_expected_after,
8600b57cec5SDimitry Andric                      "top-level asm block");
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric     if (Result.isInvalid())
8630b57cec5SDimitry Andric       return nullptr;
8640b57cec5SDimitry Andric     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
8650b57cec5SDimitry Andric     break;
8660b57cec5SDimitry Andric   }
8670b57cec5SDimitry Andric   case tok::at:
8680b57cec5SDimitry Andric     return ParseObjCAtDirectives(attrs);
8690b57cec5SDimitry Andric   case tok::minus:
8700b57cec5SDimitry Andric   case tok::plus:
8710b57cec5SDimitry Andric     if (!getLangOpts().ObjC) {
8720b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_external_declaration);
8730b57cec5SDimitry Andric       ConsumeToken();
8740b57cec5SDimitry Andric       return nullptr;
8750b57cec5SDimitry Andric     }
8760b57cec5SDimitry Andric     SingleDecl = ParseObjCMethodDefinition();
8770b57cec5SDimitry Andric     break;
8780b57cec5SDimitry Andric   case tok::code_completion:
879fe6060f1SDimitry Andric     cutOffParsing();
8800b57cec5SDimitry Andric     if (CurParsedObjCImpl) {
8810b57cec5SDimitry Andric       // Code-complete Objective-C methods even without leading '-'/'+' prefix.
8820b57cec5SDimitry Andric       Actions.CodeCompleteObjCMethodDecl(getCurScope(),
8830b57cec5SDimitry Andric                                          /*IsInstanceMethod=*/None,
8840b57cec5SDimitry Andric                                          /*ReturnType=*/nullptr);
8850b57cec5SDimitry Andric     }
8860b57cec5SDimitry Andric     Actions.CodeCompleteOrdinaryName(
8870b57cec5SDimitry Andric         getCurScope(),
8880b57cec5SDimitry Andric         CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
8890b57cec5SDimitry Andric     return nullptr;
8900b57cec5SDimitry Andric   case tok::kw_import:
8910b57cec5SDimitry Andric     SingleDecl = ParseModuleImport(SourceLocation());
8920b57cec5SDimitry Andric     break;
8930b57cec5SDimitry Andric   case tok::kw_export:
8940b57cec5SDimitry Andric     if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
8950b57cec5SDimitry Andric       SingleDecl = ParseExportDeclaration();
8960b57cec5SDimitry Andric       break;
8970b57cec5SDimitry Andric     }
8980b57cec5SDimitry Andric     // This must be 'export template'. Parse it so we can diagnose our lack
8990b57cec5SDimitry Andric     // of support.
9000b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
9010b57cec5SDimitry Andric   case tok::kw_using:
9020b57cec5SDimitry Andric   case tok::kw_namespace:
9030b57cec5SDimitry Andric   case tok::kw_typedef:
9040b57cec5SDimitry Andric   case tok::kw_template:
9050b57cec5SDimitry Andric   case tok::kw_static_assert:
9060b57cec5SDimitry Andric   case tok::kw__Static_assert:
9070b57cec5SDimitry Andric     // A function definition cannot start with any of these keywords.
9080b57cec5SDimitry Andric     {
9090b57cec5SDimitry Andric       SourceLocation DeclEnd;
910e8d8bef9SDimitry Andric       return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
9110b57cec5SDimitry Andric     }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric   case tok::kw_static:
9140b57cec5SDimitry Andric     // Parse (then ignore) 'static' prior to a template instantiation. This is
9150b57cec5SDimitry Andric     // a GCC extension that we intentionally do not support.
9160b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
9170b57cec5SDimitry Andric       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
9180b57cec5SDimitry Andric         << 0;
9190b57cec5SDimitry Andric       SourceLocation DeclEnd;
920e8d8bef9SDimitry Andric       return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
9210b57cec5SDimitry Andric     }
9220b57cec5SDimitry Andric     goto dont_know;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   case tok::kw_inline:
9250b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus) {
9260b57cec5SDimitry Andric       tok::TokenKind NextKind = NextToken().getKind();
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric       // Inline namespaces. Allowed as an extension even in C++03.
9290b57cec5SDimitry Andric       if (NextKind == tok::kw_namespace) {
9300b57cec5SDimitry Andric         SourceLocation DeclEnd;
931e8d8bef9SDimitry Andric         return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
9320b57cec5SDimitry Andric       }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric       // Parse (then ignore) 'inline' prior to a template instantiation. This is
9350b57cec5SDimitry Andric       // a GCC extension that we intentionally do not support.
9360b57cec5SDimitry Andric       if (NextKind == tok::kw_template) {
9370b57cec5SDimitry Andric         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
9380b57cec5SDimitry Andric           << 1;
9390b57cec5SDimitry Andric         SourceLocation DeclEnd;
940e8d8bef9SDimitry Andric         return ParseDeclaration(DeclaratorContext::File, DeclEnd, attrs);
9410b57cec5SDimitry Andric       }
9420b57cec5SDimitry Andric     }
9430b57cec5SDimitry Andric     goto dont_know;
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   case tok::kw_extern:
9460b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
9470b57cec5SDimitry Andric       // Extern templates
9480b57cec5SDimitry Andric       SourceLocation ExternLoc = ConsumeToken();
9490b57cec5SDimitry Andric       SourceLocation TemplateLoc = ConsumeToken();
9500b57cec5SDimitry Andric       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
9510b57cec5SDimitry Andric              diag::warn_cxx98_compat_extern_template :
9520b57cec5SDimitry Andric              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
9530b57cec5SDimitry Andric       SourceLocation DeclEnd;
954e8d8bef9SDimitry Andric       return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
955e8d8bef9SDimitry Andric           DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, attrs));
9560b57cec5SDimitry Andric     }
9570b57cec5SDimitry Andric     goto dont_know;
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric   case tok::kw___if_exists:
9600b57cec5SDimitry Andric   case tok::kw___if_not_exists:
9610b57cec5SDimitry Andric     ParseMicrosoftIfExistsExternalDeclaration();
9620b57cec5SDimitry Andric     return nullptr;
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   case tok::kw_module:
9650b57cec5SDimitry Andric     Diag(Tok, diag::err_unexpected_module_decl);
9660b57cec5SDimitry Andric     SkipUntil(tok::semi);
9670b57cec5SDimitry Andric     return nullptr;
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   default:
9700b57cec5SDimitry Andric   dont_know:
9710b57cec5SDimitry Andric     if (Tok.isEditorPlaceholder()) {
9720b57cec5SDimitry Andric       ConsumeToken();
9730b57cec5SDimitry Andric       return nullptr;
9740b57cec5SDimitry Andric     }
9750b57cec5SDimitry Andric     // We can't tell whether this is a function-definition or declaration yet.
9760b57cec5SDimitry Andric     return ParseDeclarationOrFunctionDefinition(attrs, DS);
9770b57cec5SDimitry Andric   }
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   // This routine returns a DeclGroup, if the thing we parsed only contains a
9800b57cec5SDimitry Andric   // single decl, convert it now.
9810b57cec5SDimitry Andric   return Actions.ConvertDeclToDeclGroup(SingleDecl);
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric /// Determine whether the current token, if it occurs after a
9850b57cec5SDimitry Andric /// declarator, continues a declaration or declaration list.
9860b57cec5SDimitry Andric bool Parser::isDeclarationAfterDeclarator() {
9870b57cec5SDimitry Andric   // Check for '= delete' or '= default'
9880b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
9890b57cec5SDimitry Andric     const Token &KW = NextToken();
9900b57cec5SDimitry Andric     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
9910b57cec5SDimitry Andric       return false;
9920b57cec5SDimitry Andric   }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
9950b57cec5SDimitry Andric     Tok.is(tok::comma) ||           // int X(),  -> not a function def
9960b57cec5SDimitry Andric     Tok.is(tok::semi)  ||           // int X();  -> not a function def
9970b57cec5SDimitry Andric     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
9980b57cec5SDimitry Andric     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
9990b57cec5SDimitry Andric     (getLangOpts().CPlusPlus &&
10000b57cec5SDimitry Andric      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
10010b57cec5SDimitry Andric }
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric /// Determine whether the current token, if it occurs after a
10040b57cec5SDimitry Andric /// declarator, indicates the start of a function definition.
10050b57cec5SDimitry Andric bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
10060b57cec5SDimitry Andric   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
10070b57cec5SDimitry Andric   if (Tok.is(tok::l_brace))   // int X() {}
10080b57cec5SDimitry Andric     return true;
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   // Handle K&R C argument lists: int X(f) int f; {}
10110b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus &&
10120b57cec5SDimitry Andric       Declarator.getFunctionTypeInfo().isKNRPrototype())
10130b57cec5SDimitry Andric     return isDeclarationSpecifier();
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
10160b57cec5SDimitry Andric     const Token &KW = NextToken();
10170b57cec5SDimitry Andric     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
10180b57cec5SDimitry Andric   }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
10210b57cec5SDimitry Andric          Tok.is(tok::kw_try);          // X() try { ... }
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric /// Parse either a function-definition or a declaration.  We can't tell which
10250b57cec5SDimitry Andric /// we have until we read up to the compound-statement in function-definition.
10260b57cec5SDimitry Andric /// TemplateParams, if non-NULL, provides the template parameters when we're
10270b57cec5SDimitry Andric /// parsing a C++ template-declaration.
10280b57cec5SDimitry Andric ///
10290b57cec5SDimitry Andric ///       function-definition: [C99 6.9.1]
10300b57cec5SDimitry Andric ///         decl-specs      declarator declaration-list[opt] compound-statement
10310b57cec5SDimitry Andric /// [C90] function-definition: [C99 6.7.1] - implicit int result
10320b57cec5SDimitry Andric /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
10330b57cec5SDimitry Andric ///
10340b57cec5SDimitry Andric ///       declaration: [C99 6.7]
10350b57cec5SDimitry Andric ///         declaration-specifiers init-declarator-list[opt] ';'
10360b57cec5SDimitry Andric /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
10370b57cec5SDimitry Andric /// [OMP]   threadprivate-directive
10380b57cec5SDimitry Andric /// [OMP]   allocate-directive                         [TODO]
10390b57cec5SDimitry Andric ///
10400b57cec5SDimitry Andric Parser::DeclGroupPtrTy
10410b57cec5SDimitry Andric Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
10420b57cec5SDimitry Andric                                        ParsingDeclSpec &DS,
10430b57cec5SDimitry Andric                                        AccessSpecifier AS) {
10440b57cec5SDimitry Andric   MaybeParseMicrosoftAttributes(DS.getAttributes());
10450b57cec5SDimitry Andric   // Parse the common declaration-specifiers piece.
10460b57cec5SDimitry Andric   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
10470b57cec5SDimitry Andric                              DeclSpecContext::DSC_top_level);
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   // If we had a free-standing type definition with a missing semicolon, we
10500b57cec5SDimitry Andric   // may get this far before the problem becomes obvious.
10510b57cec5SDimitry Andric   if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
10520b57cec5SDimitry Andric                                    DS, AS, DeclSpecContext::DSC_top_level))
10530b57cec5SDimitry Andric     return nullptr;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
10560b57cec5SDimitry Andric   // declaration-specifiers init-declarator-list[opt] ';'
10570b57cec5SDimitry Andric   if (Tok.is(tok::semi)) {
10580b57cec5SDimitry Andric     auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
10590b57cec5SDimitry Andric       assert(DeclSpec::isDeclRep(TKind));
10600b57cec5SDimitry Andric       switch(TKind) {
10610b57cec5SDimitry Andric       case DeclSpec::TST_class:
10620b57cec5SDimitry Andric         return 5;
10630b57cec5SDimitry Andric       case DeclSpec::TST_struct:
10640b57cec5SDimitry Andric         return 6;
10650b57cec5SDimitry Andric       case DeclSpec::TST_union:
10660b57cec5SDimitry Andric         return 5;
10670b57cec5SDimitry Andric       case DeclSpec::TST_enum:
10680b57cec5SDimitry Andric         return 4;
10690b57cec5SDimitry Andric       case DeclSpec::TST_interface:
10700b57cec5SDimitry Andric         return 9;
10710b57cec5SDimitry Andric       default:
10720b57cec5SDimitry Andric         llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
10730b57cec5SDimitry Andric       }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric     };
10760b57cec5SDimitry Andric     // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
10770b57cec5SDimitry Andric     SourceLocation CorrectLocationForAttributes =
10780b57cec5SDimitry Andric         DeclSpec::isDeclRep(DS.getTypeSpecType())
10790b57cec5SDimitry Andric             ? DS.getTypeSpecTypeLoc().getLocWithOffset(
10800b57cec5SDimitry Andric                   LengthOfTSTToken(DS.getTypeSpecType()))
10810b57cec5SDimitry Andric             : SourceLocation();
10820b57cec5SDimitry Andric     ProhibitAttributes(attrs, CorrectLocationForAttributes);
10830b57cec5SDimitry Andric     ConsumeToken();
10840b57cec5SDimitry Andric     RecordDecl *AnonRecord = nullptr;
10850b57cec5SDimitry Andric     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
10860b57cec5SDimitry Andric                                                        DS, AnonRecord);
10870b57cec5SDimitry Andric     DS.complete(TheDecl);
10880b57cec5SDimitry Andric     if (AnonRecord) {
10890b57cec5SDimitry Andric       Decl* decls[] = {AnonRecord, TheDecl};
10900b57cec5SDimitry Andric       return Actions.BuildDeclaratorGroup(decls);
10910b57cec5SDimitry Andric     }
10920b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(TheDecl);
10930b57cec5SDimitry Andric   }
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric   DS.takeAttributesFrom(attrs);
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric   // ObjC2 allows prefix attributes on class interfaces and protocols.
10980b57cec5SDimitry Andric   // FIXME: This still needs better diagnostics. We should only accept
10990b57cec5SDimitry Andric   // attributes here, no types, etc.
11000b57cec5SDimitry Andric   if (getLangOpts().ObjC && Tok.is(tok::at)) {
11010b57cec5SDimitry Andric     SourceLocation AtLoc = ConsumeToken(); // the "@"
11020b57cec5SDimitry Andric     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
11030b57cec5SDimitry Andric         !Tok.isObjCAtKeyword(tok::objc_protocol) &&
11040b57cec5SDimitry Andric         !Tok.isObjCAtKeyword(tok::objc_implementation)) {
11050b57cec5SDimitry Andric       Diag(Tok, diag::err_objc_unexpected_attr);
11060b57cec5SDimitry Andric       SkipUntil(tok::semi);
11070b57cec5SDimitry Andric       return nullptr;
11080b57cec5SDimitry Andric     }
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric     DS.abort();
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric     const char *PrevSpec = nullptr;
11130b57cec5SDimitry Andric     unsigned DiagID;
11140b57cec5SDimitry Andric     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
11150b57cec5SDimitry Andric                            Actions.getASTContext().getPrintingPolicy()))
11160b57cec5SDimitry Andric       Diag(AtLoc, DiagID) << PrevSpec;
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric     if (Tok.isObjCAtKeyword(tok::objc_protocol))
11190b57cec5SDimitry Andric       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric     if (Tok.isObjCAtKeyword(tok::objc_implementation))
11220b57cec5SDimitry Andric       return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(
11250b57cec5SDimitry Andric             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
11260b57cec5SDimitry Andric   }
11270b57cec5SDimitry Andric 
11280b57cec5SDimitry Andric   // If the declspec consisted only of 'extern' and we have a string
11290b57cec5SDimitry Andric   // literal following it, this must be a C++ linkage specifier like
11300b57cec5SDimitry Andric   // 'extern "C"'.
11310b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
11320b57cec5SDimitry Andric       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
11330b57cec5SDimitry Andric       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1134e8d8bef9SDimitry Andric     Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
11350b57cec5SDimitry Andric     return Actions.ConvertDeclToDeclGroup(TheDecl);
11360b57cec5SDimitry Andric   }
11370b57cec5SDimitry Andric 
1138e8d8bef9SDimitry Andric   return ParseDeclGroup(DS, DeclaratorContext::File);
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric Parser::DeclGroupPtrTy
11420b57cec5SDimitry Andric Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
11430b57cec5SDimitry Andric                                              ParsingDeclSpec *DS,
11440b57cec5SDimitry Andric                                              AccessSpecifier AS) {
11450b57cec5SDimitry Andric   if (DS) {
11460b57cec5SDimitry Andric     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
11470b57cec5SDimitry Andric   } else {
11480b57cec5SDimitry Andric     ParsingDeclSpec PDS(*this);
11490b57cec5SDimitry Andric     // Must temporarily exit the objective-c container scope for
11500b57cec5SDimitry Andric     // parsing c constructs and re-enter objc container scope
11510b57cec5SDimitry Andric     // afterwards.
11520b57cec5SDimitry Andric     ObjCDeclContextSwitch ObjCDC(*this);
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
11550b57cec5SDimitry Andric   }
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric /// ParseFunctionDefinition - We parsed and verified that the specified
11590b57cec5SDimitry Andric /// Declarator is well formed.  If this is a K&R-style function, read the
11600b57cec5SDimitry Andric /// parameters declaration-list, then start the compound-statement.
11610b57cec5SDimitry Andric ///
11620b57cec5SDimitry Andric ///       function-definition: [C99 6.9.1]
11630b57cec5SDimitry Andric ///         decl-specs      declarator declaration-list[opt] compound-statement
11640b57cec5SDimitry Andric /// [C90] function-definition: [C99 6.7.1] - implicit int result
11650b57cec5SDimitry Andric /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
11660b57cec5SDimitry Andric /// [C++] function-definition: [C++ 8.4]
11670b57cec5SDimitry Andric ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
11680b57cec5SDimitry Andric ///         function-body
11690b57cec5SDimitry Andric /// [C++] function-definition: [C++ 8.4]
11700b57cec5SDimitry Andric ///         decl-specifier-seq[opt] declarator function-try-block
11710b57cec5SDimitry Andric ///
11720b57cec5SDimitry Andric Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
11730b57cec5SDimitry Andric                                       const ParsedTemplateInfo &TemplateInfo,
11740b57cec5SDimitry Andric                                       LateParsedAttrList *LateParsedAttrs) {
11750b57cec5SDimitry Andric   // Poison SEH identifiers so they are flagged as illegal in function bodies.
11760b57cec5SDimitry Andric   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
11770b57cec5SDimitry Andric   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
117855e4f9d5SDimitry Andric   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   // If this is C90 and the declspecs were completely missing, fudge in an
11810b57cec5SDimitry Andric   // implicit int.  We do this here because this is the only place where
11820b57cec5SDimitry Andric   // declaration-specifiers are completely optional in the grammar.
11830b57cec5SDimitry Andric   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
11840b57cec5SDimitry Andric     const char *PrevSpec;
11850b57cec5SDimitry Andric     unsigned DiagID;
11860b57cec5SDimitry Andric     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
11870b57cec5SDimitry Andric     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
11880b57cec5SDimitry Andric                                            D.getIdentifierLoc(),
11890b57cec5SDimitry Andric                                            PrevSpec, DiagID,
11900b57cec5SDimitry Andric                                            Policy);
11910b57cec5SDimitry Andric     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
11920b57cec5SDimitry Andric   }
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   // If this declaration was formed with a K&R-style identifier list for the
11950b57cec5SDimitry Andric   // arguments, parse declarations for all of the args next.
11960b57cec5SDimitry Andric   // int foo(a,b) int a; float b; {}
11970b57cec5SDimitry Andric   if (FTI.isKNRPrototype())
11980b57cec5SDimitry Andric     ParseKNRParamDeclarations(D);
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   // We should have either an opening brace or, in a C++ constructor,
12010b57cec5SDimitry Andric   // we may have a colon.
12020b57cec5SDimitry Andric   if (Tok.isNot(tok::l_brace) &&
12030b57cec5SDimitry Andric       (!getLangOpts().CPlusPlus ||
12040b57cec5SDimitry Andric        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
12050b57cec5SDimitry Andric         Tok.isNot(tok::equal)))) {
12060b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_fn_body);
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
12090b57cec5SDimitry Andric     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric     // If we didn't find the '{', bail out.
12120b57cec5SDimitry Andric     if (Tok.isNot(tok::l_brace))
12130b57cec5SDimitry Andric       return nullptr;
12140b57cec5SDimitry Andric   }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric   // Check to make sure that any normal attributes are allowed to be on
12170b57cec5SDimitry Andric   // a definition.  Late parsed attributes are checked at the end.
12180b57cec5SDimitry Andric   if (Tok.isNot(tok::equal)) {
12190b57cec5SDimitry Andric     for (const ParsedAttr &AL : D.getAttributes())
1220fe6060f1SDimitry Andric       if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1221a7dea167SDimitry Andric         Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
12220b57cec5SDimitry Andric   }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   // In delayed template parsing mode, for function template we consume the
12250b57cec5SDimitry Andric   // tokens and store them for late parsing at the end of the translation unit.
12260b57cec5SDimitry Andric   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
12270b57cec5SDimitry Andric       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
12280b57cec5SDimitry Andric       Actions.canDelayFunctionBody(D)) {
12290b57cec5SDimitry Andric     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
12320b57cec5SDimitry Andric                                    Scope::CompoundStmtScope);
12330b57cec5SDimitry Andric     Scope *ParentScope = getCurScope()->getParent();
12340b57cec5SDimitry Andric 
1235e8d8bef9SDimitry Andric     D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
12360b57cec5SDimitry Andric     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
12370b57cec5SDimitry Andric                                         TemplateParameterLists);
12380b57cec5SDimitry Andric     D.complete(DP);
12390b57cec5SDimitry Andric     D.getMutableDeclSpec().abort();
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric     if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
12420b57cec5SDimitry Andric         trySkippingFunctionBody()) {
12430b57cec5SDimitry Andric       BodyScope.Exit();
12440b57cec5SDimitry Andric       return Actions.ActOnSkippedFunctionBody(DP);
12450b57cec5SDimitry Andric     }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric     CachedTokens Toks;
12480b57cec5SDimitry Andric     LexTemplateFunctionForLateParsing(Toks);
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric     if (DP) {
12510b57cec5SDimitry Andric       FunctionDecl *FnD = DP->getAsFunction();
12520b57cec5SDimitry Andric       Actions.CheckForFunctionRedefinition(FnD);
12530b57cec5SDimitry Andric       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
12540b57cec5SDimitry Andric     }
12550b57cec5SDimitry Andric     return DP;
12560b57cec5SDimitry Andric   }
12570b57cec5SDimitry Andric   else if (CurParsedObjCImpl &&
12580b57cec5SDimitry Andric            !TemplateInfo.TemplateParams &&
12590b57cec5SDimitry Andric            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
12600b57cec5SDimitry Andric             Tok.is(tok::colon)) &&
12610b57cec5SDimitry Andric       Actions.CurContext->isTranslationUnit()) {
12620b57cec5SDimitry Andric     ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
12630b57cec5SDimitry Andric                                    Scope::CompoundStmtScope);
12640b57cec5SDimitry Andric     Scope *ParentScope = getCurScope()->getParent();
12650b57cec5SDimitry Andric 
1266e8d8bef9SDimitry Andric     D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
12670b57cec5SDimitry Andric     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
12680b57cec5SDimitry Andric                                               MultiTemplateParamsArg());
12690b57cec5SDimitry Andric     D.complete(FuncDecl);
12700b57cec5SDimitry Andric     D.getMutableDeclSpec().abort();
12710b57cec5SDimitry Andric     if (FuncDecl) {
12720b57cec5SDimitry Andric       // Consume the tokens and store them for later parsing.
12730b57cec5SDimitry Andric       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
12740b57cec5SDimitry Andric       CurParsedObjCImpl->HasCFunction = true;
12750b57cec5SDimitry Andric       return FuncDecl;
12760b57cec5SDimitry Andric     }
12770b57cec5SDimitry Andric     // FIXME: Should we really fall through here?
12780b57cec5SDimitry Andric   }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   // Enter a scope for the function body.
12810b57cec5SDimitry Andric   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
12820b57cec5SDimitry Andric                                  Scope::CompoundStmtScope);
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // Tell the actions module that we have entered a function definition with the
12850b57cec5SDimitry Andric   // specified Declarator for the function.
12860b57cec5SDimitry Andric   Sema::SkipBodyInfo SkipBody;
12870b57cec5SDimitry Andric   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
12880b57cec5SDimitry Andric                                               TemplateInfo.TemplateParams
12890b57cec5SDimitry Andric                                                   ? *TemplateInfo.TemplateParams
12900b57cec5SDimitry Andric                                                   : MultiTemplateParamsArg(),
12910b57cec5SDimitry Andric                                               &SkipBody);
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric   if (SkipBody.ShouldSkip) {
12940b57cec5SDimitry Andric     SkipFunctionBody();
12950b57cec5SDimitry Andric     return Res;
12960b57cec5SDimitry Andric   }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   // Break out of the ParsingDeclarator context before we parse the body.
12990b57cec5SDimitry Andric   D.complete(Res);
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   // Break out of the ParsingDeclSpec context, too.  This const_cast is
13020b57cec5SDimitry Andric   // safe because we're always the sole owner.
13030b57cec5SDimitry Andric   D.getMutableDeclSpec().abort();
13040b57cec5SDimitry Andric 
130555e4f9d5SDimitry Andric   // With abbreviated function templates - we need to explicitly add depth to
130655e4f9d5SDimitry Andric   // account for the implicit template parameter list induced by the template.
130755e4f9d5SDimitry Andric   if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
130855e4f9d5SDimitry Andric     if (Template->isAbbreviated() &&
130955e4f9d5SDimitry Andric         Template->getTemplateParameters()->getParam(0)->isImplicit())
131055e4f9d5SDimitry Andric       // First template parameter is implicit - meaning no explicit template
131155e4f9d5SDimitry Andric       // parameter list was specified.
131255e4f9d5SDimitry Andric       CurTemplateDepthTracker.addDepth(1);
131355e4f9d5SDimitry Andric 
13140b57cec5SDimitry Andric   if (TryConsumeToken(tok::equal)) {
13150b57cec5SDimitry Andric     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric     bool Delete = false;
13180b57cec5SDimitry Andric     SourceLocation KWLoc;
13190b57cec5SDimitry Andric     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
13200b57cec5SDimitry Andric       Diag(KWLoc, getLangOpts().CPlusPlus11
13210b57cec5SDimitry Andric                       ? diag::warn_cxx98_compat_defaulted_deleted_function
13220b57cec5SDimitry Andric                       : diag::ext_defaulted_deleted_function)
13230b57cec5SDimitry Andric         << 1 /* deleted */;
13240b57cec5SDimitry Andric       Actions.SetDeclDeleted(Res, KWLoc);
13250b57cec5SDimitry Andric       Delete = true;
13260b57cec5SDimitry Andric     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
13270b57cec5SDimitry Andric       Diag(KWLoc, getLangOpts().CPlusPlus11
13280b57cec5SDimitry Andric                       ? diag::warn_cxx98_compat_defaulted_deleted_function
13290b57cec5SDimitry Andric                       : diag::ext_defaulted_deleted_function)
13300b57cec5SDimitry Andric         << 0 /* defaulted */;
13310b57cec5SDimitry Andric       Actions.SetDeclDefaulted(Res, KWLoc);
13320b57cec5SDimitry Andric     } else {
13330b57cec5SDimitry Andric       llvm_unreachable("function definition after = not 'delete' or 'default'");
13340b57cec5SDimitry Andric     }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric     if (Tok.is(tok::comma)) {
13370b57cec5SDimitry Andric       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
13380b57cec5SDimitry Andric         << Delete;
13390b57cec5SDimitry Andric       SkipUntil(tok::semi);
13400b57cec5SDimitry Andric     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
13410b57cec5SDimitry Andric                                 Delete ? "delete" : "default")) {
13420b57cec5SDimitry Andric       SkipUntil(tok::semi);
13430b57cec5SDimitry Andric     }
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
13460b57cec5SDimitry Andric     Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
13470b57cec5SDimitry Andric     return Res;
13480b57cec5SDimitry Andric   }
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
13510b57cec5SDimitry Andric       trySkippingFunctionBody()) {
13520b57cec5SDimitry Andric     BodyScope.Exit();
13530b57cec5SDimitry Andric     Actions.ActOnSkippedFunctionBody(Res);
13540b57cec5SDimitry Andric     return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
13550b57cec5SDimitry Andric   }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric   if (Tok.is(tok::kw_try))
13580b57cec5SDimitry Andric     return ParseFunctionTryBlock(Res, BodyScope);
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric   // If we have a colon, then we're probably parsing a C++
13610b57cec5SDimitry Andric   // ctor-initializer.
13620b57cec5SDimitry Andric   if (Tok.is(tok::colon)) {
13630b57cec5SDimitry Andric     ParseConstructorInitializer(Res);
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric     // Recover from error.
13660b57cec5SDimitry Andric     if (!Tok.is(tok::l_brace)) {
13670b57cec5SDimitry Andric       BodyScope.Exit();
13680b57cec5SDimitry Andric       Actions.ActOnFinishFunctionBody(Res, nullptr);
13690b57cec5SDimitry Andric       return Res;
13700b57cec5SDimitry Andric     }
13710b57cec5SDimitry Andric   } else
13720b57cec5SDimitry Andric     Actions.ActOnDefaultCtorInitializers(Res);
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric   // Late attributes are parsed in the same scope as the function body.
13750b57cec5SDimitry Andric   if (LateParsedAttrs)
13760b57cec5SDimitry Andric     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   return ParseFunctionStatementBody(Res, BodyScope);
13790b57cec5SDimitry Andric }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric void Parser::SkipFunctionBody() {
13820b57cec5SDimitry Andric   if (Tok.is(tok::equal)) {
13830b57cec5SDimitry Andric     SkipUntil(tok::semi);
13840b57cec5SDimitry Andric     return;
13850b57cec5SDimitry Andric   }
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric   bool IsFunctionTryBlock = Tok.is(tok::kw_try);
13880b57cec5SDimitry Andric   if (IsFunctionTryBlock)
13890b57cec5SDimitry Andric     ConsumeToken();
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric   CachedTokens Skipped;
13920b57cec5SDimitry Andric   if (ConsumeAndStoreFunctionPrologue(Skipped))
13930b57cec5SDimitry Andric     SkipMalformedDecl();
13940b57cec5SDimitry Andric   else {
13950b57cec5SDimitry Andric     SkipUntil(tok::r_brace);
13960b57cec5SDimitry Andric     while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
13970b57cec5SDimitry Andric       SkipUntil(tok::l_brace);
13980b57cec5SDimitry Andric       SkipUntil(tok::r_brace);
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric   }
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
14040b57cec5SDimitry Andric /// types for a function with a K&R-style identifier list for arguments.
14050b57cec5SDimitry Andric void Parser::ParseKNRParamDeclarations(Declarator &D) {
14060b57cec5SDimitry Andric   // We know that the top-level of this declarator is a function.
14070b57cec5SDimitry Andric   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   // Enter function-declaration scope, limiting any declarators to the
14100b57cec5SDimitry Andric   // function prototype scope, including parameter declarators.
14110b57cec5SDimitry Andric   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
14120b57cec5SDimitry Andric                             Scope::FunctionDeclarationScope | Scope::DeclScope);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   // Read all the argument declarations.
14150b57cec5SDimitry Andric   while (isDeclarationSpecifier()) {
14160b57cec5SDimitry Andric     SourceLocation DSStart = Tok.getLocation();
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric     // Parse the common declaration-specifiers piece.
14190b57cec5SDimitry Andric     DeclSpec DS(AttrFactory);
14200b57cec5SDimitry Andric     ParseDeclarationSpecifiers(DS);
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
14230b57cec5SDimitry Andric     // least one declarator'.
14240b57cec5SDimitry Andric     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
14250b57cec5SDimitry Andric     // the declarations though.  It's trivial to ignore them, really hard to do
14260b57cec5SDimitry Andric     // anything else with them.
14270b57cec5SDimitry Andric     if (TryConsumeToken(tok::semi)) {
14280b57cec5SDimitry Andric       Diag(DSStart, diag::err_declaration_does_not_declare_param);
14290b57cec5SDimitry Andric       continue;
14300b57cec5SDimitry Andric     }
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
14330b57cec5SDimitry Andric     // than register.
14340b57cec5SDimitry Andric     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
14350b57cec5SDimitry Andric         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
14360b57cec5SDimitry Andric       Diag(DS.getStorageClassSpecLoc(),
14370b57cec5SDimitry Andric            diag::err_invalid_storage_class_in_func_decl);
14380b57cec5SDimitry Andric       DS.ClearStorageClassSpecs();
14390b57cec5SDimitry Andric     }
14400b57cec5SDimitry Andric     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
14410b57cec5SDimitry Andric       Diag(DS.getThreadStorageClassSpecLoc(),
14420b57cec5SDimitry Andric            diag::err_invalid_storage_class_in_func_decl);
14430b57cec5SDimitry Andric       DS.ClearStorageClassSpecs();
14440b57cec5SDimitry Andric     }
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric     // Parse the first declarator attached to this declspec.
1447e8d8bef9SDimitry Andric     Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeList);
14480b57cec5SDimitry Andric     ParseDeclarator(ParmDeclarator);
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric     // Handle the full declarator list.
14510b57cec5SDimitry Andric     while (1) {
14520b57cec5SDimitry Andric       // If attributes are present, parse them.
14530b57cec5SDimitry Andric       MaybeParseGNUAttributes(ParmDeclarator);
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric       // Ask the actions module to compute the type for this declarator.
14560b57cec5SDimitry Andric       Decl *Param =
14570b57cec5SDimitry Andric         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric       if (Param &&
14600b57cec5SDimitry Andric           // A missing identifier has already been diagnosed.
14610b57cec5SDimitry Andric           ParmDeclarator.getIdentifier()) {
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric         // Scan the argument list looking for the correct param to apply this
14640b57cec5SDimitry Andric         // type.
14650b57cec5SDimitry Andric         for (unsigned i = 0; ; ++i) {
14660b57cec5SDimitry Andric           // C99 6.9.1p6: those declarators shall declare only identifiers from
14670b57cec5SDimitry Andric           // the identifier list.
14680b57cec5SDimitry Andric           if (i == FTI.NumParams) {
14690b57cec5SDimitry Andric             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
14700b57cec5SDimitry Andric               << ParmDeclarator.getIdentifier();
14710b57cec5SDimitry Andric             break;
14720b57cec5SDimitry Andric           }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
14750b57cec5SDimitry Andric             // Reject redefinitions of parameters.
14760b57cec5SDimitry Andric             if (FTI.Params[i].Param) {
14770b57cec5SDimitry Andric               Diag(ParmDeclarator.getIdentifierLoc(),
14780b57cec5SDimitry Andric                    diag::err_param_redefinition)
14790b57cec5SDimitry Andric                  << ParmDeclarator.getIdentifier();
14800b57cec5SDimitry Andric             } else {
14810b57cec5SDimitry Andric               FTI.Params[i].Param = Param;
14820b57cec5SDimitry Andric             }
14830b57cec5SDimitry Andric             break;
14840b57cec5SDimitry Andric           }
14850b57cec5SDimitry Andric         }
14860b57cec5SDimitry Andric       }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric       // If we don't have a comma, it is either the end of the list (a ';') or
14890b57cec5SDimitry Andric       // an error, bail out.
14900b57cec5SDimitry Andric       if (Tok.isNot(tok::comma))
14910b57cec5SDimitry Andric         break;
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric       ParmDeclarator.clear();
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric       // Consume the comma.
14960b57cec5SDimitry Andric       ParmDeclarator.setCommaLoc(ConsumeToken());
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric       // Parse the next declarator.
14990b57cec5SDimitry Andric       ParseDeclarator(ParmDeclarator);
15000b57cec5SDimitry Andric     }
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric     // Consume ';' and continue parsing.
15030b57cec5SDimitry Andric     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
15040b57cec5SDimitry Andric       continue;
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric     // Otherwise recover by skipping to next semi or mandatory function body.
15070b57cec5SDimitry Andric     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
15080b57cec5SDimitry Andric       break;
15090b57cec5SDimitry Andric     TryConsumeToken(tok::semi);
15100b57cec5SDimitry Andric   }
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   // The actions module must verify that all arguments were declared.
15130b57cec5SDimitry Andric   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
15180b57cec5SDimitry Andric /// allowed to be a wide string, and is not subject to character translation.
1519480093f4SDimitry Andric /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1520480093f4SDimitry Andric /// asm label as opposed to an asm statement, because such a construct does not
1521480093f4SDimitry Andric /// behave well.
15220b57cec5SDimitry Andric ///
15230b57cec5SDimitry Andric /// [GNU] asm-string-literal:
15240b57cec5SDimitry Andric ///         string-literal
15250b57cec5SDimitry Andric ///
1526480093f4SDimitry Andric ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
15270b57cec5SDimitry Andric   if (!isTokenStringLiteral()) {
15280b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_string_literal)
15290b57cec5SDimitry Andric       << /*Source='in...'*/0 << "'asm'";
15300b57cec5SDimitry Andric     return ExprError();
15310b57cec5SDimitry Andric   }
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric   ExprResult AsmString(ParseStringLiteralExpression());
15340b57cec5SDimitry Andric   if (!AsmString.isInvalid()) {
15350b57cec5SDimitry Andric     const auto *SL = cast<StringLiteral>(AsmString.get());
15360b57cec5SDimitry Andric     if (!SL->isAscii()) {
15370b57cec5SDimitry Andric       Diag(Tok, diag::err_asm_operand_wide_string_literal)
15380b57cec5SDimitry Andric         << SL->isWide()
15390b57cec5SDimitry Andric         << SL->getSourceRange();
15400b57cec5SDimitry Andric       return ExprError();
15410b57cec5SDimitry Andric     }
1542480093f4SDimitry Andric     if (ForAsmLabel && SL->getString().empty()) {
1543480093f4SDimitry Andric       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1544480093f4SDimitry Andric           << 2 /* an empty */ << SL->getSourceRange();
1545480093f4SDimitry Andric       return ExprError();
1546480093f4SDimitry Andric     }
15470b57cec5SDimitry Andric   }
15480b57cec5SDimitry Andric   return AsmString;
15490b57cec5SDimitry Andric }
15500b57cec5SDimitry Andric 
15510b57cec5SDimitry Andric /// ParseSimpleAsm
15520b57cec5SDimitry Andric ///
15530b57cec5SDimitry Andric /// [GNU] simple-asm-expr:
15540b57cec5SDimitry Andric ///         'asm' '(' asm-string-literal ')'
15550b57cec5SDimitry Andric ///
1556480093f4SDimitry Andric ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
15570b57cec5SDimitry Andric   assert(Tok.is(tok::kw_asm) && "Not an asm!");
15580b57cec5SDimitry Andric   SourceLocation Loc = ConsumeToken();
15590b57cec5SDimitry Andric 
15605ffd83dbSDimitry Andric   if (isGNUAsmQualifier(Tok)) {
15615ffd83dbSDimitry Andric     // Remove from the end of 'asm' to the end of the asm qualifier.
15620b57cec5SDimitry Andric     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
15630b57cec5SDimitry Andric                              PP.getLocForEndOfToken(Tok.getLocation()));
15645ffd83dbSDimitry Andric     Diag(Tok, diag::err_global_asm_qualifier_ignored)
15655ffd83dbSDimitry Andric         << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
15660b57cec5SDimitry Andric         << FixItHint::CreateRemoval(RemovalRange);
15670b57cec5SDimitry Andric     ConsumeToken();
15680b57cec5SDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   BalancedDelimiterTracker T(*this, tok::l_paren);
15710b57cec5SDimitry Andric   if (T.consumeOpen()) {
15720b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_lparen_after) << "asm";
15730b57cec5SDimitry Andric     return ExprError();
15740b57cec5SDimitry Andric   }
15750b57cec5SDimitry Andric 
1576480093f4SDimitry Andric   ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   if (!Result.isInvalid()) {
15790b57cec5SDimitry Andric     // Close the paren and get the location of the end bracket
15800b57cec5SDimitry Andric     T.consumeClose();
15810b57cec5SDimitry Andric     if (EndLoc)
15820b57cec5SDimitry Andric       *EndLoc = T.getCloseLocation();
15830b57cec5SDimitry Andric   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
15840b57cec5SDimitry Andric     if (EndLoc)
15850b57cec5SDimitry Andric       *EndLoc = Tok.getLocation();
15860b57cec5SDimitry Andric     ConsumeParen();
15870b57cec5SDimitry Andric   }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric   return Result;
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric /// Get the TemplateIdAnnotation from the token and put it in the
15930b57cec5SDimitry Andric /// cleanup pool so that it gets destroyed when parsing the current top level
15940b57cec5SDimitry Andric /// declaration is finished.
15950b57cec5SDimitry Andric TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
15960b57cec5SDimitry Andric   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
15970b57cec5SDimitry Andric   TemplateIdAnnotation *
15980b57cec5SDimitry Andric       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
15990b57cec5SDimitry Andric   return Id;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
16030b57cec5SDimitry Andric   // Push the current token back into the token stream (or revert it if it is
16040b57cec5SDimitry Andric   // cached) and use an annotation scope token for current token.
16050b57cec5SDimitry Andric   if (PP.isBacktrackEnabled())
16060b57cec5SDimitry Andric     PP.RevertCachedTokens(1);
16070b57cec5SDimitry Andric   else
16080b57cec5SDimitry Andric     PP.EnterToken(Tok, /*IsReinject=*/true);
16090b57cec5SDimitry Andric   Tok.setKind(tok::annot_cxxscope);
16100b57cec5SDimitry Andric   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
16110b57cec5SDimitry Andric   Tok.setAnnotationRange(SS.getRange());
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   // In case the tokens were cached, have Preprocessor replace them
16140b57cec5SDimitry Andric   // with the annotation token.  We don't need to do this if we've
16150b57cec5SDimitry Andric   // just reverted back to a prior state.
16160b57cec5SDimitry Andric   if (IsNewAnnotation)
16170b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
16180b57cec5SDimitry Andric }
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric /// Attempt to classify the name at the current token position. This may
16210b57cec5SDimitry Andric /// form a type, scope or primary expression annotation, or replace the token
16220b57cec5SDimitry Andric /// with a typo-corrected keyword. This is only appropriate when the current
16230b57cec5SDimitry Andric /// name must refer to an entity which has already been declared.
16240b57cec5SDimitry Andric ///
16250b57cec5SDimitry Andric /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
16260b57cec5SDimitry Andric ///        no typo correction will be performed.
16270b57cec5SDimitry Andric Parser::AnnotatedNameKind
1628a7dea167SDimitry Andric Parser::TryAnnotateName(CorrectionCandidateCallback *CCC) {
16290b57cec5SDimitry Andric   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   const bool EnteringContext = false;
16320b57cec5SDimitry Andric   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric   CXXScopeSpec SS;
16350b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus &&
16365ffd83dbSDimitry Andric       ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
16375ffd83dbSDimitry Andric                                      /*ObjectHadErrors=*/false,
16385ffd83dbSDimitry Andric                                      EnteringContext))
16390b57cec5SDimitry Andric     return ANK_Error;
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
16420b57cec5SDimitry Andric     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
16430b57cec5SDimitry Andric       return ANK_Error;
16440b57cec5SDimitry Andric     return ANK_Unresolved;
16450b57cec5SDimitry Andric   }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   IdentifierInfo *Name = Tok.getIdentifierInfo();
16480b57cec5SDimitry Andric   SourceLocation NameLoc = Tok.getLocation();
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   // FIXME: Move the tentative declaration logic into ClassifyName so we can
16510b57cec5SDimitry Andric   // typo-correct to tentatively-declared identifiers.
16520b57cec5SDimitry Andric   if (isTentativelyDeclared(Name)) {
16530b57cec5SDimitry Andric     // Identifier has been tentatively declared, and thus cannot be resolved as
16540b57cec5SDimitry Andric     // an expression. Fall back to annotating it as a type.
16550b57cec5SDimitry Andric     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
16560b57cec5SDimitry Andric       return ANK_Error;
16570b57cec5SDimitry Andric     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
16580b57cec5SDimitry Andric   }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric   Token Next = NextToken();
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric   // Look up and classify the identifier. We don't perform any typo-correction
16630b57cec5SDimitry Andric   // after a scope specifier, because in general we can't recover from typos
16640b57cec5SDimitry Andric   // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
16650b57cec5SDimitry Andric   // jump back into scope specifier parsing).
1666a7dea167SDimitry Andric   Sema::NameClassification Classification = Actions.ClassifyName(
1667a7dea167SDimitry Andric       getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   // If name lookup found nothing and we guessed that this was a template name,
16700b57cec5SDimitry Andric   // double-check before committing to that interpretation. C++20 requires that
16710b57cec5SDimitry Andric   // we interpret this as a template-id if it can be, but if it can't be, then
16720b57cec5SDimitry Andric   // this is an error recovery case.
16730b57cec5SDimitry Andric   if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
16740b57cec5SDimitry Andric       isTemplateArgumentList(1) == TPResult::False) {
16750b57cec5SDimitry Andric     // It's not a template-id; re-classify without the '<' as a hint.
16760b57cec5SDimitry Andric     Token FakeNext = Next;
16770b57cec5SDimitry Andric     FakeNext.setKind(tok::unknown);
16780b57cec5SDimitry Andric     Classification =
16790b57cec5SDimitry Andric         Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1680a7dea167SDimitry Andric                              SS.isEmpty() ? CCC : nullptr);
16810b57cec5SDimitry Andric   }
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   switch (Classification.getKind()) {
16840b57cec5SDimitry Andric   case Sema::NC_Error:
16850b57cec5SDimitry Andric     return ANK_Error;
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric   case Sema::NC_Keyword:
16880b57cec5SDimitry Andric     // The identifier was typo-corrected to a keyword.
16890b57cec5SDimitry Andric     Tok.setIdentifierInfo(Name);
16900b57cec5SDimitry Andric     Tok.setKind(Name->getTokenID());
16910b57cec5SDimitry Andric     PP.TypoCorrectToken(Tok);
16920b57cec5SDimitry Andric     if (SS.isNotEmpty())
16930b57cec5SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
16940b57cec5SDimitry Andric     // We've "annotated" this as a keyword.
16950b57cec5SDimitry Andric     return ANK_Success;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   case Sema::NC_Unknown:
16980b57cec5SDimitry Andric     // It's not something we know about. Leave it unannotated.
16990b57cec5SDimitry Andric     break;
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   case Sema::NC_Type: {
1702fe6060f1SDimitry Andric     if (TryAltiVecVectorToken())
1703fe6060f1SDimitry Andric       // vector has been found as a type id when altivec is enabled but
1704fe6060f1SDimitry Andric       // this is followed by a declaration specifier so this is really the
1705fe6060f1SDimitry Andric       // altivec vector token.  Leave it unannotated.
1706fe6060f1SDimitry Andric       break;
17070b57cec5SDimitry Andric     SourceLocation BeginLoc = NameLoc;
17080b57cec5SDimitry Andric     if (SS.isNotEmpty())
17090b57cec5SDimitry Andric       BeginLoc = SS.getBeginLoc();
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric     /// An Objective-C object type followed by '<' is a specialization of
17120b57cec5SDimitry Andric     /// a parameterized class type or a protocol-qualified type.
17130b57cec5SDimitry Andric     ParsedType Ty = Classification.getType();
17140b57cec5SDimitry Andric     if (getLangOpts().ObjC && NextToken().is(tok::less) &&
17150b57cec5SDimitry Andric         (Ty.get()->isObjCObjectType() ||
17160b57cec5SDimitry Andric          Ty.get()->isObjCObjectPointerType())) {
17170b57cec5SDimitry Andric       // Consume the name.
17180b57cec5SDimitry Andric       SourceLocation IdentifierLoc = ConsumeToken();
17190b57cec5SDimitry Andric       SourceLocation NewEndLoc;
17200b57cec5SDimitry Andric       TypeResult NewType
17210b57cec5SDimitry Andric           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
17220b57cec5SDimitry Andric                                                    /*consumeLastToken=*/false,
17230b57cec5SDimitry Andric                                                    NewEndLoc);
17240b57cec5SDimitry Andric       if (NewType.isUsable())
17250b57cec5SDimitry Andric         Ty = NewType.get();
17260b57cec5SDimitry Andric       else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
17270b57cec5SDimitry Andric         return ANK_Error;
17280b57cec5SDimitry Andric     }
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric     Tok.setKind(tok::annot_typename);
17310b57cec5SDimitry Andric     setTypeAnnotation(Tok, Ty);
17320b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(Tok.getLocation());
17330b57cec5SDimitry Andric     Tok.setLocation(BeginLoc);
17340b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
17350b57cec5SDimitry Andric     return ANK_Success;
17360b57cec5SDimitry Andric   }
17370b57cec5SDimitry Andric 
1738e8d8bef9SDimitry Andric   case Sema::NC_OverloadSet:
1739e8d8bef9SDimitry Andric     Tok.setKind(tok::annot_overload_set);
17400b57cec5SDimitry Andric     setExprAnnotation(Tok, Classification.getExpression());
17410b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
17420b57cec5SDimitry Andric     if (SS.isNotEmpty())
17430b57cec5SDimitry Andric       Tok.setLocation(SS.getBeginLoc());
17440b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
17450b57cec5SDimitry Andric     return ANK_Success;
17460b57cec5SDimitry Andric 
1747a7dea167SDimitry Andric   case Sema::NC_NonType:
1748fe6060f1SDimitry Andric     if (TryAltiVecVectorToken())
1749fe6060f1SDimitry Andric       // vector has been found as a non-type id when altivec is enabled but
1750fe6060f1SDimitry Andric       // this is followed by a declaration specifier so this is really the
1751fe6060f1SDimitry Andric       // altivec vector token.  Leave it unannotated.
1752fe6060f1SDimitry Andric       break;
1753a7dea167SDimitry Andric     Tok.setKind(tok::annot_non_type);
1754a7dea167SDimitry Andric     setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1755a7dea167SDimitry Andric     Tok.setLocation(NameLoc);
1756a7dea167SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
1757a7dea167SDimitry Andric     PP.AnnotateCachedTokens(Tok);
1758a7dea167SDimitry Andric     if (SS.isNotEmpty())
1759a7dea167SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
1760a7dea167SDimitry Andric     return ANK_Success;
1761a7dea167SDimitry Andric 
1762a7dea167SDimitry Andric   case Sema::NC_UndeclaredNonType:
1763a7dea167SDimitry Andric   case Sema::NC_DependentNonType:
1764a7dea167SDimitry Andric     Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1765a7dea167SDimitry Andric                     ? tok::annot_non_type_undeclared
1766a7dea167SDimitry Andric                     : tok::annot_non_type_dependent);
1767a7dea167SDimitry Andric     setIdentifierAnnotation(Tok, Name);
1768a7dea167SDimitry Andric     Tok.setLocation(NameLoc);
1769a7dea167SDimitry Andric     Tok.setAnnotationEndLoc(NameLoc);
1770a7dea167SDimitry Andric     PP.AnnotateCachedTokens(Tok);
1771a7dea167SDimitry Andric     if (SS.isNotEmpty())
1772a7dea167SDimitry Andric       AnnotateScopeToken(SS, !WasScopeAnnotation);
1773a7dea167SDimitry Andric     return ANK_Success;
1774a7dea167SDimitry Andric 
17750b57cec5SDimitry Andric   case Sema::NC_TypeTemplate:
17760b57cec5SDimitry Andric     if (Next.isNot(tok::less)) {
17770b57cec5SDimitry Andric       // This may be a type template being used as a template template argument.
17780b57cec5SDimitry Andric       if (SS.isNotEmpty())
17790b57cec5SDimitry Andric         AnnotateScopeToken(SS, !WasScopeAnnotation);
17800b57cec5SDimitry Andric       return ANK_TemplateName;
17810b57cec5SDimitry Andric     }
17820b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
17830b57cec5SDimitry Andric   case Sema::NC_VarTemplate:
17840b57cec5SDimitry Andric   case Sema::NC_FunctionTemplate:
17850b57cec5SDimitry Andric   case Sema::NC_UndeclaredTemplate: {
17860b57cec5SDimitry Andric     // We have a type, variable or function template followed by '<'.
17870b57cec5SDimitry Andric     ConsumeToken();
17880b57cec5SDimitry Andric     UnqualifiedId Id;
17890b57cec5SDimitry Andric     Id.setIdentifier(Name, NameLoc);
17900b57cec5SDimitry Andric     if (AnnotateTemplateIdToken(
17910b57cec5SDimitry Andric             TemplateTy::make(Classification.getTemplateName()),
17920b57cec5SDimitry Andric             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
17930b57cec5SDimitry Andric       return ANK_Error;
17940b57cec5SDimitry Andric     return ANK_Success;
17950b57cec5SDimitry Andric   }
179655e4f9d5SDimitry Andric   case Sema::NC_Concept: {
179755e4f9d5SDimitry Andric     UnqualifiedId Id;
179855e4f9d5SDimitry Andric     Id.setIdentifier(Name, NameLoc);
179955e4f9d5SDimitry Andric     if (Next.is(tok::less))
180055e4f9d5SDimitry Andric       // We have a concept name followed by '<'. Consume the identifier token so
180155e4f9d5SDimitry Andric       // we reach the '<' and annotate it.
180255e4f9d5SDimitry Andric       ConsumeToken();
180355e4f9d5SDimitry Andric     if (AnnotateTemplateIdToken(
180455e4f9d5SDimitry Andric             TemplateTy::make(Classification.getTemplateName()),
180555e4f9d5SDimitry Andric             Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
180655e4f9d5SDimitry Andric             /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true))
180755e4f9d5SDimitry Andric       return ANK_Error;
180855e4f9d5SDimitry Andric     return ANK_Success;
180955e4f9d5SDimitry Andric   }
18100b57cec5SDimitry Andric   }
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   // Unable to classify the name, but maybe we can annotate a scope specifier.
18130b57cec5SDimitry Andric   if (SS.isNotEmpty())
18140b57cec5SDimitry Andric     AnnotateScopeToken(SS, !WasScopeAnnotation);
18150b57cec5SDimitry Andric   return ANK_Unresolved;
18160b57cec5SDimitry Andric }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
18190b57cec5SDimitry Andric   assert(Tok.isNot(tok::identifier));
18200b57cec5SDimitry Andric   Diag(Tok, diag::ext_keyword_as_ident)
18210b57cec5SDimitry Andric     << PP.getSpelling(Tok)
18220b57cec5SDimitry Andric     << DisableKeyword;
18230b57cec5SDimitry Andric   if (DisableKeyword)
18240b57cec5SDimitry Andric     Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
18250b57cec5SDimitry Andric   Tok.setKind(tok::identifier);
18260b57cec5SDimitry Andric   return true;
18270b57cec5SDimitry Andric }
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric /// TryAnnotateTypeOrScopeToken - If the current token position is on a
18300b57cec5SDimitry Andric /// typename (possibly qualified in C++) or a C++ scope specifier not followed
18310b57cec5SDimitry Andric /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
18320b57cec5SDimitry Andric /// with a single annotation token representing the typename or C++ scope
18330b57cec5SDimitry Andric /// respectively.
18340b57cec5SDimitry Andric /// This simplifies handling of C++ scope specifiers and allows efficient
18350b57cec5SDimitry Andric /// backtracking without the need to re-parse and resolve nested-names and
18360b57cec5SDimitry Andric /// typenames.
18370b57cec5SDimitry Andric /// It will mainly be called when we expect to treat identifiers as typenames
18380b57cec5SDimitry Andric /// (if they are typenames). For example, in C we do not expect identifiers
18390b57cec5SDimitry Andric /// inside expressions to be treated as typenames so it will not be called
18400b57cec5SDimitry Andric /// for expressions in C.
18410b57cec5SDimitry Andric /// The benefit for C/ObjC is that a typename will be annotated and
18420b57cec5SDimitry Andric /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
18430b57cec5SDimitry Andric /// will not be called twice, once to check whether we have a declaration
18440b57cec5SDimitry Andric /// specifier, and another one to get the actual type inside
18450b57cec5SDimitry Andric /// ParseDeclarationSpecifiers).
18460b57cec5SDimitry Andric ///
18470b57cec5SDimitry Andric /// This returns true if an error occurred.
18480b57cec5SDimitry Andric ///
18490b57cec5SDimitry Andric /// Note that this routine emits an error if you call it with ::new or ::delete
18500b57cec5SDimitry Andric /// as the current tokens, so only call it in contexts where these are invalid.
18510b57cec5SDimitry Andric bool Parser::TryAnnotateTypeOrScopeToken() {
18520b57cec5SDimitry Andric   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
18530b57cec5SDimitry Andric           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
18540b57cec5SDimitry Andric           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
18550b57cec5SDimitry Andric           Tok.is(tok::kw___super)) &&
18560b57cec5SDimitry Andric          "Cannot be a type or scope token!");
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric   if (Tok.is(tok::kw_typename)) {
18590b57cec5SDimitry Andric     // MSVC lets you do stuff like:
18600b57cec5SDimitry Andric     //   typename typedef T_::D D;
18610b57cec5SDimitry Andric     //
18620b57cec5SDimitry Andric     // We will consume the typedef token here and put it back after we have
18630b57cec5SDimitry Andric     // parsed the first identifier, transforming it into something more like:
18640b57cec5SDimitry Andric     //   typename T_::D typedef D;
18650b57cec5SDimitry Andric     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
18660b57cec5SDimitry Andric       Token TypedefToken;
18670b57cec5SDimitry Andric       PP.Lex(TypedefToken);
18680b57cec5SDimitry Andric       bool Result = TryAnnotateTypeOrScopeToken();
18690b57cec5SDimitry Andric       PP.EnterToken(Tok, /*IsReinject=*/true);
18700b57cec5SDimitry Andric       Tok = TypedefToken;
18710b57cec5SDimitry Andric       if (!Result)
18720b57cec5SDimitry Andric         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
18730b57cec5SDimitry Andric       return Result;
18740b57cec5SDimitry Andric     }
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric     // Parse a C++ typename-specifier, e.g., "typename T::type".
18770b57cec5SDimitry Andric     //
18780b57cec5SDimitry Andric     //   typename-specifier:
18790b57cec5SDimitry Andric     //     'typename' '::' [opt] nested-name-specifier identifier
18800b57cec5SDimitry Andric     //     'typename' '::' [opt] nested-name-specifier template [opt]
18810b57cec5SDimitry Andric     //            simple-template-id
18820b57cec5SDimitry Andric     SourceLocation TypenameLoc = ConsumeToken();
18830b57cec5SDimitry Andric     CXXScopeSpec SS;
18840b57cec5SDimitry Andric     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
18855ffd83dbSDimitry Andric                                        /*ObjectHadErrors=*/false,
18860b57cec5SDimitry Andric                                        /*EnteringContext=*/false, nullptr,
18870b57cec5SDimitry Andric                                        /*IsTypename*/ true))
18880b57cec5SDimitry Andric       return true;
188955e4f9d5SDimitry Andric     if (SS.isEmpty()) {
18900b57cec5SDimitry Andric       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
18910b57cec5SDimitry Andric           Tok.is(tok::annot_decltype)) {
18920b57cec5SDimitry Andric         // Attempt to recover by skipping the invalid 'typename'
18930b57cec5SDimitry Andric         if (Tok.is(tok::annot_decltype) ||
18940b57cec5SDimitry Andric             (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
18950b57cec5SDimitry Andric           unsigned DiagID = diag::err_expected_qualified_after_typename;
18960b57cec5SDimitry Andric           // MS compatibility: MSVC permits using known types with typename.
18970b57cec5SDimitry Andric           // e.g. "typedef typename T* pointer_type"
18980b57cec5SDimitry Andric           if (getLangOpts().MicrosoftExt)
18990b57cec5SDimitry Andric             DiagID = diag::warn_expected_qualified_after_typename;
19000b57cec5SDimitry Andric           Diag(Tok.getLocation(), DiagID);
19010b57cec5SDimitry Andric           return false;
19020b57cec5SDimitry Andric         }
19030b57cec5SDimitry Andric       }
19040b57cec5SDimitry Andric       if (Tok.isEditorPlaceholder())
19050b57cec5SDimitry Andric         return true;
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
19080b57cec5SDimitry Andric       return true;
19090b57cec5SDimitry Andric     }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric     TypeResult Ty;
19120b57cec5SDimitry Andric     if (Tok.is(tok::identifier)) {
19130b57cec5SDimitry Andric       // FIXME: check whether the next token is '<', first!
19140b57cec5SDimitry Andric       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
19150b57cec5SDimitry Andric                                      *Tok.getIdentifierInfo(),
19160b57cec5SDimitry Andric                                      Tok.getLocation());
19170b57cec5SDimitry Andric     } else if (Tok.is(tok::annot_template_id)) {
19180b57cec5SDimitry Andric       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
19195ffd83dbSDimitry Andric       if (!TemplateId->mightBeType()) {
19200b57cec5SDimitry Andric         Diag(Tok, diag::err_typename_refers_to_non_type_template)
19210b57cec5SDimitry Andric           << Tok.getAnnotationRange();
19220b57cec5SDimitry Andric         return true;
19230b57cec5SDimitry Andric       }
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
19260b57cec5SDimitry Andric                                          TemplateId->NumArgs);
19270b57cec5SDimitry Andric 
19285ffd83dbSDimitry Andric       Ty = TemplateId->isInvalid()
19295ffd83dbSDimitry Andric                ? TypeError()
19305ffd83dbSDimitry Andric                : Actions.ActOnTypenameType(
19315ffd83dbSDimitry Andric                      getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
19325ffd83dbSDimitry Andric                      TemplateId->Template, TemplateId->Name,
19335ffd83dbSDimitry Andric                      TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
19345ffd83dbSDimitry Andric                      TemplateArgsPtr, TemplateId->RAngleLoc);
19350b57cec5SDimitry Andric     } else {
19360b57cec5SDimitry Andric       Diag(Tok, diag::err_expected_type_name_after_typename)
19370b57cec5SDimitry Andric         << SS.getRange();
19380b57cec5SDimitry Andric       return true;
19390b57cec5SDimitry Andric     }
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric     SourceLocation EndLoc = Tok.getLastLoc();
19420b57cec5SDimitry Andric     Tok.setKind(tok::annot_typename);
19435ffd83dbSDimitry Andric     setTypeAnnotation(Tok, Ty);
19440b57cec5SDimitry Andric     Tok.setAnnotationEndLoc(EndLoc);
19450b57cec5SDimitry Andric     Tok.setLocation(TypenameLoc);
19460b57cec5SDimitry Andric     PP.AnnotateCachedTokens(Tok);
19470b57cec5SDimitry Andric     return false;
19480b57cec5SDimitry Andric   }
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric   // Remembers whether the token was originally a scope annotation.
19510b57cec5SDimitry Andric   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric   CXXScopeSpec SS;
19540b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
19555ffd83dbSDimitry Andric     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
19565ffd83dbSDimitry Andric                                        /*ObjectHadErrors=*/false,
19575ffd83dbSDimitry Andric                                        /*EnteringContext*/ false))
19580b57cec5SDimitry Andric       return true;
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
19610b57cec5SDimitry Andric }
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric /// Try to annotate a type or scope token, having already parsed an
19640b57cec5SDimitry Andric /// optional scope specifier. \p IsNewScope should be \c true unless the scope
19650b57cec5SDimitry Andric /// specifier was extracted from an existing tok::annot_cxxscope annotation.
19660b57cec5SDimitry Andric bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
19670b57cec5SDimitry Andric                                                        bool IsNewScope) {
19680b57cec5SDimitry Andric   if (Tok.is(tok::identifier)) {
19690b57cec5SDimitry Andric     // Determine whether the identifier is a type name.
19700b57cec5SDimitry Andric     if (ParsedType Ty = Actions.getTypeName(
19710b57cec5SDimitry Andric             *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
19720b57cec5SDimitry Andric             false, NextToken().is(tok::period), nullptr,
19730b57cec5SDimitry Andric             /*IsCtorOrDtorName=*/false,
19740b57cec5SDimitry Andric             /*NonTrivialTypeSourceInfo*/true,
19750b57cec5SDimitry Andric             /*IsClassTemplateDeductionContext*/true)) {
19760b57cec5SDimitry Andric       SourceLocation BeginLoc = Tok.getLocation();
19770b57cec5SDimitry Andric       if (SS.isNotEmpty()) // it was a C++ qualified type name.
19780b57cec5SDimitry Andric         BeginLoc = SS.getBeginLoc();
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric       /// An Objective-C object type followed by '<' is a specialization of
19810b57cec5SDimitry Andric       /// a parameterized class type or a protocol-qualified type.
19820b57cec5SDimitry Andric       if (getLangOpts().ObjC && NextToken().is(tok::less) &&
19830b57cec5SDimitry Andric           (Ty.get()->isObjCObjectType() ||
19840b57cec5SDimitry Andric            Ty.get()->isObjCObjectPointerType())) {
19850b57cec5SDimitry Andric         // Consume the name.
19860b57cec5SDimitry Andric         SourceLocation IdentifierLoc = ConsumeToken();
19870b57cec5SDimitry Andric         SourceLocation NewEndLoc;
19880b57cec5SDimitry Andric         TypeResult NewType
19890b57cec5SDimitry Andric           = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
19900b57cec5SDimitry Andric                                                    /*consumeLastToken=*/false,
19910b57cec5SDimitry Andric                                                    NewEndLoc);
19920b57cec5SDimitry Andric         if (NewType.isUsable())
19930b57cec5SDimitry Andric           Ty = NewType.get();
19940b57cec5SDimitry Andric         else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
19950b57cec5SDimitry Andric           return false;
19960b57cec5SDimitry Andric       }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric       // This is a typename. Replace the current token in-place with an
19990b57cec5SDimitry Andric       // annotation type token.
20000b57cec5SDimitry Andric       Tok.setKind(tok::annot_typename);
20010b57cec5SDimitry Andric       setTypeAnnotation(Tok, Ty);
20020b57cec5SDimitry Andric       Tok.setAnnotationEndLoc(Tok.getLocation());
20030b57cec5SDimitry Andric       Tok.setLocation(BeginLoc);
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric       // In case the tokens were cached, have Preprocessor replace
20060b57cec5SDimitry Andric       // them with the annotation token.
20070b57cec5SDimitry Andric       PP.AnnotateCachedTokens(Tok);
20080b57cec5SDimitry Andric       return false;
20090b57cec5SDimitry Andric     }
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric     if (!getLangOpts().CPlusPlus) {
20120b57cec5SDimitry Andric       // If we're in C, we can't have :: tokens at all (the lexer won't return
20130b57cec5SDimitry Andric       // them).  If the identifier is not a type, then it can't be scope either,
20140b57cec5SDimitry Andric       // just early exit.
20150b57cec5SDimitry Andric       return false;
20160b57cec5SDimitry Andric     }
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric     // If this is a template-id, annotate with a template-id or type token.
20190b57cec5SDimitry Andric     // FIXME: This appears to be dead code. We already have formed template-id
20200b57cec5SDimitry Andric     // tokens when parsing the scope specifier; this can never form a new one.
20210b57cec5SDimitry Andric     if (NextToken().is(tok::less)) {
20220b57cec5SDimitry Andric       TemplateTy Template;
20230b57cec5SDimitry Andric       UnqualifiedId TemplateName;
20240b57cec5SDimitry Andric       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
20250b57cec5SDimitry Andric       bool MemberOfUnknownSpecialization;
20260b57cec5SDimitry Andric       if (TemplateNameKind TNK = Actions.isTemplateName(
20270b57cec5SDimitry Andric               getCurScope(), SS,
20280b57cec5SDimitry Andric               /*hasTemplateKeyword=*/false, TemplateName,
20290b57cec5SDimitry Andric               /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
20300b57cec5SDimitry Andric               MemberOfUnknownSpecialization)) {
20310b57cec5SDimitry Andric         // Only annotate an undeclared template name as a template-id if the
20320b57cec5SDimitry Andric         // following tokens have the form of a template argument list.
20330b57cec5SDimitry Andric         if (TNK != TNK_Undeclared_template ||
20340b57cec5SDimitry Andric             isTemplateArgumentList(1) != TPResult::False) {
20350b57cec5SDimitry Andric           // Consume the identifier.
20360b57cec5SDimitry Andric           ConsumeToken();
20370b57cec5SDimitry Andric           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
20380b57cec5SDimitry Andric                                       TemplateName)) {
20390b57cec5SDimitry Andric             // If an unrecoverable error occurred, we need to return true here,
20400b57cec5SDimitry Andric             // because the token stream is in a damaged state.  We may not
20410b57cec5SDimitry Andric             // return a valid identifier.
20420b57cec5SDimitry Andric             return true;
20430b57cec5SDimitry Andric           }
20440b57cec5SDimitry Andric         }
20450b57cec5SDimitry Andric       }
20460b57cec5SDimitry Andric     }
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric     // The current token, which is either an identifier or a
20490b57cec5SDimitry Andric     // template-id, is not part of the annotation. Fall through to
20500b57cec5SDimitry Andric     // push that token back into the stream and complete the C++ scope
20510b57cec5SDimitry Andric     // specifier annotation.
20520b57cec5SDimitry Andric   }
20530b57cec5SDimitry Andric 
20540b57cec5SDimitry Andric   if (Tok.is(tok::annot_template_id)) {
20550b57cec5SDimitry Andric     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
20560b57cec5SDimitry Andric     if (TemplateId->Kind == TNK_Type_template) {
20570b57cec5SDimitry Andric       // A template-id that refers to a type was parsed into a
20580b57cec5SDimitry Andric       // template-id annotation in a context where we weren't allowed
20590b57cec5SDimitry Andric       // to produce a type annotation token. Update the template-id
20600b57cec5SDimitry Andric       // annotation token to a type annotation token now.
206155e4f9d5SDimitry Andric       AnnotateTemplateIdTokenAsType(SS);
20620b57cec5SDimitry Andric       return false;
20630b57cec5SDimitry Andric     }
20640b57cec5SDimitry Andric   }
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   if (SS.isEmpty())
20670b57cec5SDimitry Andric     return false;
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric   // A C++ scope specifier that isn't followed by a typename.
20700b57cec5SDimitry Andric   AnnotateScopeToken(SS, IsNewScope);
20710b57cec5SDimitry Andric   return false;
20720b57cec5SDimitry Andric }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
20750b57cec5SDimitry Andric /// annotates C++ scope specifiers and template-ids.  This returns
20760b57cec5SDimitry Andric /// true if there was an error that could not be recovered from.
20770b57cec5SDimitry Andric ///
20780b57cec5SDimitry Andric /// Note that this routine emits an error if you call it with ::new or ::delete
20790b57cec5SDimitry Andric /// as the current tokens, so only call it in contexts where these are invalid.
20800b57cec5SDimitry Andric bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
20810b57cec5SDimitry Andric   assert(getLangOpts().CPlusPlus &&
20820b57cec5SDimitry Andric          "Call sites of this function should be guarded by checking for C++");
208355e4f9d5SDimitry Andric   assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   CXXScopeSpec SS;
20865ffd83dbSDimitry Andric   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
20875ffd83dbSDimitry Andric                                      /*ObjectHadErrors=*/false,
20885ffd83dbSDimitry Andric                                      EnteringContext))
20890b57cec5SDimitry Andric     return true;
20900b57cec5SDimitry Andric   if (SS.isEmpty())
20910b57cec5SDimitry Andric     return false;
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric   AnnotateScopeToken(SS, true);
20940b57cec5SDimitry Andric   return false;
20950b57cec5SDimitry Andric }
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric bool Parser::isTokenEqualOrEqualTypo() {
20980b57cec5SDimitry Andric   tok::TokenKind Kind = Tok.getKind();
20990b57cec5SDimitry Andric   switch (Kind) {
21000b57cec5SDimitry Andric   default:
21010b57cec5SDimitry Andric     return false;
21020b57cec5SDimitry Andric   case tok::ampequal:            // &=
21030b57cec5SDimitry Andric   case tok::starequal:           // *=
21040b57cec5SDimitry Andric   case tok::plusequal:           // +=
21050b57cec5SDimitry Andric   case tok::minusequal:          // -=
21060b57cec5SDimitry Andric   case tok::exclaimequal:        // !=
21070b57cec5SDimitry Andric   case tok::slashequal:          // /=
21080b57cec5SDimitry Andric   case tok::percentequal:        // %=
21090b57cec5SDimitry Andric   case tok::lessequal:           // <=
21100b57cec5SDimitry Andric   case tok::lesslessequal:       // <<=
21110b57cec5SDimitry Andric   case tok::greaterequal:        // >=
21120b57cec5SDimitry Andric   case tok::greatergreaterequal: // >>=
21130b57cec5SDimitry Andric   case tok::caretequal:          // ^=
21140b57cec5SDimitry Andric   case tok::pipeequal:           // |=
21150b57cec5SDimitry Andric   case tok::equalequal:          // ==
21160b57cec5SDimitry Andric     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
21170b57cec5SDimitry Andric         << Kind
21180b57cec5SDimitry Andric         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
21190b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
21200b57cec5SDimitry Andric   case tok::equal:
21210b57cec5SDimitry Andric     return true;
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
21260b57cec5SDimitry Andric   assert(Tok.is(tok::code_completion));
21270b57cec5SDimitry Andric   PrevTokLocation = Tok.getLocation();
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric   for (Scope *S = getCurScope(); S; S = S->getParent()) {
21300b57cec5SDimitry Andric     if (S->getFlags() & Scope::FnScope) {
2131fe6060f1SDimitry Andric       cutOffParsing();
21320b57cec5SDimitry Andric       Actions.CodeCompleteOrdinaryName(getCurScope(),
21330b57cec5SDimitry Andric                                        Sema::PCC_RecoveryInFunction);
21340b57cec5SDimitry Andric       return PrevTokLocation;
21350b57cec5SDimitry Andric     }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     if (S->getFlags() & Scope::ClassScope) {
21380b57cec5SDimitry Andric       cutOffParsing();
2139fe6060f1SDimitry Andric       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
21400b57cec5SDimitry Andric       return PrevTokLocation;
21410b57cec5SDimitry Andric     }
21420b57cec5SDimitry Andric   }
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric   cutOffParsing();
2145fe6060f1SDimitry Andric   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
21460b57cec5SDimitry Andric   return PrevTokLocation;
21470b57cec5SDimitry Andric }
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric // Code-completion pass-through functions
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric void Parser::CodeCompleteDirective(bool InConditional) {
21520b57cec5SDimitry Andric   Actions.CodeCompletePreprocessorDirective(InConditional);
21530b57cec5SDimitry Andric }
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric void Parser::CodeCompleteInConditionalExclusion() {
21560b57cec5SDimitry Andric   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric void Parser::CodeCompleteMacroName(bool IsDefinition) {
21600b57cec5SDimitry Andric   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
21610b57cec5SDimitry Andric }
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric void Parser::CodeCompletePreprocessorExpression() {
21640b57cec5SDimitry Andric   Actions.CodeCompletePreprocessorExpression();
21650b57cec5SDimitry Andric }
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
21680b57cec5SDimitry Andric                                        MacroInfo *MacroInfo,
21690b57cec5SDimitry Andric                                        unsigned ArgumentIndex) {
21700b57cec5SDimitry Andric   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
21710b57cec5SDimitry Andric                                                 ArgumentIndex);
21720b57cec5SDimitry Andric }
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
21750b57cec5SDimitry Andric   Actions.CodeCompleteIncludedFile(Dir, IsAngled);
21760b57cec5SDimitry Andric }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric void Parser::CodeCompleteNaturalLanguage() {
21790b57cec5SDimitry Andric   Actions.CodeCompleteNaturalLanguage();
21800b57cec5SDimitry Andric }
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
21830b57cec5SDimitry Andric   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
21840b57cec5SDimitry Andric          "Expected '__if_exists' or '__if_not_exists'");
21850b57cec5SDimitry Andric   Result.IsIfExists = Tok.is(tok::kw___if_exists);
21860b57cec5SDimitry Andric   Result.KeywordLoc = ConsumeToken();
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   BalancedDelimiterTracker T(*this, tok::l_paren);
21890b57cec5SDimitry Andric   if (T.consumeOpen()) {
21900b57cec5SDimitry Andric     Diag(Tok, diag::err_expected_lparen_after)
21910b57cec5SDimitry Andric       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
21920b57cec5SDimitry Andric     return true;
21930b57cec5SDimitry Andric   }
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric   // Parse nested-name-specifier.
21960b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
21975ffd83dbSDimitry Andric     ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
21985ffd83dbSDimitry Andric                                    /*ObjectHadErrors=*/false,
21990b57cec5SDimitry Andric                                    /*EnteringContext=*/false);
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   // Check nested-name specifier.
22020b57cec5SDimitry Andric   if (Result.SS.isInvalid()) {
22030b57cec5SDimitry Andric     T.skipToEnd();
22040b57cec5SDimitry Andric     return true;
22050b57cec5SDimitry Andric   }
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // Parse the unqualified-id.
22080b57cec5SDimitry Andric   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
22095ffd83dbSDimitry Andric   if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
22105ffd83dbSDimitry Andric                          /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
22115ffd83dbSDimitry Andric                          /*AllowDestructorName*/ true,
22125ffd83dbSDimitry Andric                          /*AllowConstructorName*/ true,
22135ffd83dbSDimitry Andric                          /*AllowDeductionGuide*/ false, &TemplateKWLoc,
22145ffd83dbSDimitry Andric                          Result.Name)) {
22150b57cec5SDimitry Andric     T.skipToEnd();
22160b57cec5SDimitry Andric     return true;
22170b57cec5SDimitry Andric   }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric   if (T.consumeClose())
22200b57cec5SDimitry Andric     return true;
22210b57cec5SDimitry Andric 
22220b57cec5SDimitry Andric   // Check if the symbol exists.
22230b57cec5SDimitry Andric   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
22240b57cec5SDimitry Andric                                                Result.IsIfExists, Result.SS,
22250b57cec5SDimitry Andric                                                Result.Name)) {
22260b57cec5SDimitry Andric   case Sema::IER_Exists:
22270b57cec5SDimitry Andric     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
22280b57cec5SDimitry Andric     break;
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric   case Sema::IER_DoesNotExist:
22310b57cec5SDimitry Andric     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
22320b57cec5SDimitry Andric     break;
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric   case Sema::IER_Dependent:
22350b57cec5SDimitry Andric     Result.Behavior = IEB_Dependent;
22360b57cec5SDimitry Andric     break;
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric   case Sema::IER_Error:
22390b57cec5SDimitry Andric     return true;
22400b57cec5SDimitry Andric   }
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   return false;
22430b57cec5SDimitry Andric }
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
22460b57cec5SDimitry Andric   IfExistsCondition Result;
22470b57cec5SDimitry Andric   if (ParseMicrosoftIfExistsCondition(Result))
22480b57cec5SDimitry Andric     return;
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric   BalancedDelimiterTracker Braces(*this, tok::l_brace);
22510b57cec5SDimitry Andric   if (Braces.consumeOpen()) {
22520b57cec5SDimitry Andric     Diag(Tok, diag::err_expected) << tok::l_brace;
22530b57cec5SDimitry Andric     return;
22540b57cec5SDimitry Andric   }
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric   switch (Result.Behavior) {
22570b57cec5SDimitry Andric   case IEB_Parse:
22580b57cec5SDimitry Andric     // Parse declarations below.
22590b57cec5SDimitry Andric     break;
22600b57cec5SDimitry Andric 
22610b57cec5SDimitry Andric   case IEB_Dependent:
22620b57cec5SDimitry Andric     llvm_unreachable("Cannot have a dependent external declaration");
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   case IEB_Skip:
22650b57cec5SDimitry Andric     Braces.skipToEnd();
22660b57cec5SDimitry Andric     return;
22670b57cec5SDimitry Andric   }
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   // Parse the declarations.
22700b57cec5SDimitry Andric   // FIXME: Support module import within __if_exists?
22710b57cec5SDimitry Andric   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
22720b57cec5SDimitry Andric     ParsedAttributesWithRange attrs(AttrFactory);
22730b57cec5SDimitry Andric     MaybeParseCXX11Attributes(attrs);
22740b57cec5SDimitry Andric     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
22750b57cec5SDimitry Andric     if (Result && !getCurScope()->getParent())
22760b57cec5SDimitry Andric       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
22770b57cec5SDimitry Andric   }
22780b57cec5SDimitry Andric   Braces.consumeClose();
22790b57cec5SDimitry Andric }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric /// Parse a declaration beginning with the 'module' keyword or C++20
22820b57cec5SDimitry Andric /// context-sensitive keyword (optionally preceded by 'export').
22830b57cec5SDimitry Andric ///
22840b57cec5SDimitry Andric ///   module-declaration:   [Modules TS + P0629R0]
22850b57cec5SDimitry Andric ///     'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
22860b57cec5SDimitry Andric ///
22870b57cec5SDimitry Andric ///   global-module-fragment:  [C++2a]
22880b57cec5SDimitry Andric ///     'module' ';' top-level-declaration-seq[opt]
22890b57cec5SDimitry Andric ///   module-declaration:      [C++2a]
22900b57cec5SDimitry Andric ///     'export'[opt] 'module' module-name module-partition[opt]
22910b57cec5SDimitry Andric ///            attribute-specifier-seq[opt] ';'
22920b57cec5SDimitry Andric ///   private-module-fragment: [C++2a]
22930b57cec5SDimitry Andric ///     'module' ':' 'private' ';' top-level-declaration-seq[opt]
22940b57cec5SDimitry Andric Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) {
22950b57cec5SDimitry Andric   SourceLocation StartLoc = Tok.getLocation();
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
22980b57cec5SDimitry Andric                                  ? Sema::ModuleDeclKind::Interface
22990b57cec5SDimitry Andric                                  : Sema::ModuleDeclKind::Implementation;
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric   assert(
23020b57cec5SDimitry Andric       (Tok.is(tok::kw_module) ||
23030b57cec5SDimitry Andric        (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
23040b57cec5SDimitry Andric       "not a module declaration");
23050b57cec5SDimitry Andric   SourceLocation ModuleLoc = ConsumeToken();
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric   // Attributes appear after the module name, not before.
23080b57cec5SDimitry Andric   // FIXME: Suggest moving the attributes later with a fixit.
23090b57cec5SDimitry Andric   DiagnoseAndSkipCXX11Attributes();
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   // Parse a global-module-fragment, if present.
23120b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
23130b57cec5SDimitry Andric     SourceLocation SemiLoc = ConsumeToken();
23140b57cec5SDimitry Andric     if (!IsFirstDecl) {
23150b57cec5SDimitry Andric       Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
23160b57cec5SDimitry Andric         << SourceRange(StartLoc, SemiLoc);
23170b57cec5SDimitry Andric       return nullptr;
23180b57cec5SDimitry Andric     }
23190b57cec5SDimitry Andric     if (MDK == Sema::ModuleDeclKind::Interface) {
23200b57cec5SDimitry Andric       Diag(StartLoc, diag::err_module_fragment_exported)
23210b57cec5SDimitry Andric         << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric     return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
23240b57cec5SDimitry Andric   }
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   // Parse a private-module-fragment, if present.
23270b57cec5SDimitry Andric   if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
23280b57cec5SDimitry Andric       NextToken().is(tok::kw_private)) {
23290b57cec5SDimitry Andric     if (MDK == Sema::ModuleDeclKind::Interface) {
23300b57cec5SDimitry Andric       Diag(StartLoc, diag::err_module_fragment_exported)
23310b57cec5SDimitry Andric         << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
23320b57cec5SDimitry Andric     }
23330b57cec5SDimitry Andric     ConsumeToken();
23340b57cec5SDimitry Andric     SourceLocation PrivateLoc = ConsumeToken();
23350b57cec5SDimitry Andric     DiagnoseAndSkipCXX11Attributes();
23360b57cec5SDimitry Andric     ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
23370b57cec5SDimitry Andric     return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
23380b57cec5SDimitry Andric   }
23390b57cec5SDimitry Andric 
23400b57cec5SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
23410b57cec5SDimitry Andric   if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
23420b57cec5SDimitry Andric     return nullptr;
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   // Parse the optional module-partition.
23450b57cec5SDimitry Andric   if (Tok.is(tok::colon)) {
23460b57cec5SDimitry Andric     SourceLocation ColonLoc = ConsumeToken();
23470b57cec5SDimitry Andric     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
23480b57cec5SDimitry Andric     if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false))
23490b57cec5SDimitry Andric       return nullptr;
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric     // FIXME: Support module partition declarations.
23520b57cec5SDimitry Andric     Diag(ColonLoc, diag::err_unsupported_module_partition)
23530b57cec5SDimitry Andric       << SourceRange(ColonLoc, Partition.back().second);
23540b57cec5SDimitry Andric     // Recover by parsing as a non-partition.
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   // We don't support any module attributes yet; just parse them and diagnose.
23580b57cec5SDimitry Andric   ParsedAttributesWithRange Attrs(AttrFactory);
23590b57cec5SDimitry Andric   MaybeParseCXX11Attributes(Attrs);
23600b57cec5SDimitry Andric   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   ExpectAndConsumeSemi(diag::err_module_expected_semi);
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl);
23650b57cec5SDimitry Andric }
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric /// Parse a module import declaration. This is essentially the same for
23680b57cec5SDimitry Andric /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
23690b57cec5SDimitry Andric /// and the trailing optional attributes (in C++).
23700b57cec5SDimitry Andric ///
23710b57cec5SDimitry Andric /// [ObjC]  @import declaration:
23720b57cec5SDimitry Andric ///           '@' 'import' module-name ';'
23730b57cec5SDimitry Andric /// [ModTS] module-import-declaration:
23740b57cec5SDimitry Andric ///           'import' module-name attribute-specifier-seq[opt] ';'
23750b57cec5SDimitry Andric /// [C++2a] module-import-declaration:
23760b57cec5SDimitry Andric ///           'export'[opt] 'import' module-name
23770b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
23780b57cec5SDimitry Andric ///           'export'[opt] 'import' module-partition
23790b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
23800b57cec5SDimitry Andric ///           'export'[opt] 'import' header-name
23810b57cec5SDimitry Andric ///                   attribute-specifier-seq[opt] ';'
23820b57cec5SDimitry Andric Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
23830b57cec5SDimitry Andric   SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric   SourceLocation ExportLoc;
23860b57cec5SDimitry Andric   TryConsumeToken(tok::kw_export, ExportLoc);
23870b57cec5SDimitry Andric 
23880b57cec5SDimitry Andric   assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
23890b57cec5SDimitry Andric                             : Tok.isObjCAtKeyword(tok::objc_import)) &&
23900b57cec5SDimitry Andric          "Improper start to module import");
23910b57cec5SDimitry Andric   bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
23920b57cec5SDimitry Andric   SourceLocation ImportLoc = ConsumeToken();
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
23950b57cec5SDimitry Andric   Module *HeaderUnit = nullptr;
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric   if (Tok.is(tok::header_name)) {
23980b57cec5SDimitry Andric     // This is a header import that the preprocessor decided we should skip
23990b57cec5SDimitry Andric     // because it was malformed in some way. Parse and ignore it; it's already
24000b57cec5SDimitry Andric     // been diagnosed.
24010b57cec5SDimitry Andric     ConsumeToken();
24020b57cec5SDimitry Andric   } else if (Tok.is(tok::annot_header_unit)) {
24030b57cec5SDimitry Andric     // This is a header import that the preprocessor mapped to a module import.
24040b57cec5SDimitry Andric     HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
24050b57cec5SDimitry Andric     ConsumeAnnotationToken();
24060b57cec5SDimitry Andric   } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
24070b57cec5SDimitry Andric     SourceLocation ColonLoc = ConsumeToken();
24080b57cec5SDimitry Andric     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
24090b57cec5SDimitry Andric       return nullptr;
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric     // FIXME: Support module partition import.
24120b57cec5SDimitry Andric     Diag(ColonLoc, diag::err_unsupported_module_partition)
24130b57cec5SDimitry Andric       << SourceRange(ColonLoc, Path.back().second);
24140b57cec5SDimitry Andric     return nullptr;
24150b57cec5SDimitry Andric   } else {
24160b57cec5SDimitry Andric     if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
24170b57cec5SDimitry Andric       return nullptr;
24180b57cec5SDimitry Andric   }
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   ParsedAttributesWithRange Attrs(AttrFactory);
24210b57cec5SDimitry Andric   MaybeParseCXX11Attributes(Attrs);
24220b57cec5SDimitry Andric   // We don't support any module import attributes yet.
24230b57cec5SDimitry Andric   ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   if (PP.hadModuleLoaderFatalFailure()) {
24260b57cec5SDimitry Andric     // With a fatal failure in the module loader, we abort parsing.
24270b57cec5SDimitry Andric     cutOffParsing();
24280b57cec5SDimitry Andric     return nullptr;
24290b57cec5SDimitry Andric   }
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   DeclResult Import;
24320b57cec5SDimitry Andric   if (HeaderUnit)
24330b57cec5SDimitry Andric     Import =
24340b57cec5SDimitry Andric         Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
24350b57cec5SDimitry Andric   else if (!Path.empty())
24360b57cec5SDimitry Andric     Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path);
24370b57cec5SDimitry Andric   ExpectAndConsumeSemi(diag::err_module_expected_semi);
24380b57cec5SDimitry Andric   if (Import.isInvalid())
24390b57cec5SDimitry Andric     return nullptr;
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric   // Using '@import' in framework headers requires modules to be enabled so that
24420b57cec5SDimitry Andric   // the header is parseable. Emit a warning to make the user aware.
24430b57cec5SDimitry Andric   if (IsObjCAtImport && AtLoc.isValid()) {
24440b57cec5SDimitry Andric     auto &SrcMgr = PP.getSourceManager();
24450b57cec5SDimitry Andric     auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
24460b57cec5SDimitry Andric     if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
24470b57cec5SDimitry Andric                   .endswith(".framework"))
24480b57cec5SDimitry Andric       Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
24490b57cec5SDimitry Andric   }
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   return Import.get();
24520b57cec5SDimitry Andric }
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
24550b57cec5SDimitry Andric /// grammar).
24560b57cec5SDimitry Andric ///
24570b57cec5SDimitry Andric ///         module-name:
24580b57cec5SDimitry Andric ///           module-name-qualifier[opt] identifier
24590b57cec5SDimitry Andric ///         module-name-qualifier:
24600b57cec5SDimitry Andric ///           module-name-qualifier[opt] identifier '.'
24610b57cec5SDimitry Andric bool Parser::ParseModuleName(
24620b57cec5SDimitry Andric     SourceLocation UseLoc,
24630b57cec5SDimitry Andric     SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
24640b57cec5SDimitry Andric     bool IsImport) {
24650b57cec5SDimitry Andric   // Parse the module path.
24660b57cec5SDimitry Andric   while (true) {
24670b57cec5SDimitry Andric     if (!Tok.is(tok::identifier)) {
24680b57cec5SDimitry Andric       if (Tok.is(tok::code_completion)) {
24690b57cec5SDimitry Andric         cutOffParsing();
2470fe6060f1SDimitry Andric         Actions.CodeCompleteModuleImport(UseLoc, Path);
24710b57cec5SDimitry Andric         return true;
24720b57cec5SDimitry Andric       }
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric       Diag(Tok, diag::err_module_expected_ident) << IsImport;
24750b57cec5SDimitry Andric       SkipUntil(tok::semi);
24760b57cec5SDimitry Andric       return true;
24770b57cec5SDimitry Andric     }
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric     // Record this part of the module path.
24800b57cec5SDimitry Andric     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
24810b57cec5SDimitry Andric     ConsumeToken();
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     if (Tok.isNot(tok::period))
24840b57cec5SDimitry Andric       return false;
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric     ConsumeToken();
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric }
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric /// Try recover parser when module annotation appears where it must not
24910b57cec5SDimitry Andric /// be found.
24920b57cec5SDimitry Andric /// \returns false if the recover was successful and parsing may be continued, or
24930b57cec5SDimitry Andric /// true if parser must bail out to top level and handle the token there.
24940b57cec5SDimitry Andric bool Parser::parseMisplacedModuleImport() {
24950b57cec5SDimitry Andric   while (true) {
24960b57cec5SDimitry Andric     switch (Tok.getKind()) {
24970b57cec5SDimitry Andric     case tok::annot_module_end:
24980b57cec5SDimitry Andric       // If we recovered from a misplaced module begin, we expect to hit a
24990b57cec5SDimitry Andric       // misplaced module end too. Stay in the current context when this
25000b57cec5SDimitry Andric       // happens.
25010b57cec5SDimitry Andric       if (MisplacedModuleBeginCount) {
25020b57cec5SDimitry Andric         --MisplacedModuleBeginCount;
25030b57cec5SDimitry Andric         Actions.ActOnModuleEnd(Tok.getLocation(),
25040b57cec5SDimitry Andric                                reinterpret_cast<Module *>(
25050b57cec5SDimitry Andric                                    Tok.getAnnotationValue()));
25060b57cec5SDimitry Andric         ConsumeAnnotationToken();
25070b57cec5SDimitry Andric         continue;
25080b57cec5SDimitry Andric       }
25090b57cec5SDimitry Andric       // Inform caller that recovery failed, the error must be handled at upper
25100b57cec5SDimitry Andric       // level. This will generate the desired "missing '}' at end of module"
25110b57cec5SDimitry Andric       // diagnostics on the way out.
25120b57cec5SDimitry Andric       return true;
25130b57cec5SDimitry Andric     case tok::annot_module_begin:
25140b57cec5SDimitry Andric       // Recover by entering the module (Sema will diagnose).
25150b57cec5SDimitry Andric       Actions.ActOnModuleBegin(Tok.getLocation(),
25160b57cec5SDimitry Andric                                reinterpret_cast<Module *>(
25170b57cec5SDimitry Andric                                    Tok.getAnnotationValue()));
25180b57cec5SDimitry Andric       ConsumeAnnotationToken();
25190b57cec5SDimitry Andric       ++MisplacedModuleBeginCount;
25200b57cec5SDimitry Andric       continue;
25210b57cec5SDimitry Andric     case tok::annot_module_include:
25220b57cec5SDimitry Andric       // Module import found where it should not be, for instance, inside a
25230b57cec5SDimitry Andric       // namespace. Recover by importing the module.
25240b57cec5SDimitry Andric       Actions.ActOnModuleInclude(Tok.getLocation(),
25250b57cec5SDimitry Andric                                  reinterpret_cast<Module *>(
25260b57cec5SDimitry Andric                                      Tok.getAnnotationValue()));
25270b57cec5SDimitry Andric       ConsumeAnnotationToken();
25280b57cec5SDimitry Andric       // If there is another module import, process it.
25290b57cec5SDimitry Andric       continue;
25300b57cec5SDimitry Andric     default:
25310b57cec5SDimitry Andric       return false;
25320b57cec5SDimitry Andric     }
25330b57cec5SDimitry Andric   }
25340b57cec5SDimitry Andric   return false;
25350b57cec5SDimitry Andric }
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric bool BalancedDelimiterTracker::diagnoseOverflow() {
25380b57cec5SDimitry Andric   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
25390b57cec5SDimitry Andric     << P.getLangOpts().BracketDepth;
25400b57cec5SDimitry Andric   P.Diag(P.Tok, diag::note_bracket_depth);
25410b57cec5SDimitry Andric   P.cutOffParsing();
25420b57cec5SDimitry Andric   return true;
25430b57cec5SDimitry Andric }
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
25460b57cec5SDimitry Andric                                                 const char *Msg,
25470b57cec5SDimitry Andric                                                 tok::TokenKind SkipToTok) {
25480b57cec5SDimitry Andric   LOpen = P.Tok.getLocation();
25490b57cec5SDimitry Andric   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
25500b57cec5SDimitry Andric     if (SkipToTok != tok::unknown)
25510b57cec5SDimitry Andric       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
25520b57cec5SDimitry Andric     return true;
25530b57cec5SDimitry Andric   }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric   if (getDepth() < P.getLangOpts().BracketDepth)
25560b57cec5SDimitry Andric     return false;
25570b57cec5SDimitry Andric 
25580b57cec5SDimitry Andric   return diagnoseOverflow();
25590b57cec5SDimitry Andric }
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric bool BalancedDelimiterTracker::diagnoseMissingClose() {
25620b57cec5SDimitry Andric   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
25630b57cec5SDimitry Andric 
25640b57cec5SDimitry Andric   if (P.Tok.is(tok::annot_module_end))
25650b57cec5SDimitry Andric     P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
25660b57cec5SDimitry Andric   else
25670b57cec5SDimitry Andric     P.Diag(P.Tok, diag::err_expected) << Close;
25680b57cec5SDimitry Andric   P.Diag(LOpen, diag::note_matching) << Kind;
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   // If we're not already at some kind of closing bracket, skip to our closing
25710b57cec5SDimitry Andric   // token.
25720b57cec5SDimitry Andric   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
25730b57cec5SDimitry Andric       P.Tok.isNot(tok::r_square) &&
25740b57cec5SDimitry Andric       P.SkipUntil(Close, FinalToken,
25750b57cec5SDimitry Andric                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
25760b57cec5SDimitry Andric       P.Tok.is(Close))
25770b57cec5SDimitry Andric     LClose = P.ConsumeAnyToken();
25780b57cec5SDimitry Andric   return true;
25790b57cec5SDimitry Andric }
25800b57cec5SDimitry Andric 
25810b57cec5SDimitry Andric void BalancedDelimiterTracker::skipToEnd() {
25820b57cec5SDimitry Andric   P.SkipUntil(Close, Parser::StopBeforeMatch);
25830b57cec5SDimitry Andric   consumeClose();
25840b57cec5SDimitry Andric }
2585