[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Parse / Parser.cpp
blob176d2149e73184ed849b0dfeb51293bf7a22ac85
1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Parse/RAIIObjectsForParser.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/Scope.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/TimeProfiler.h"
26 using namespace clang;
29 namespace {
30 /// A comment handler that passes comments found by the preprocessor
31 /// to the parser action.
32 class ActionCommentHandler : public CommentHandler {
33 Sema &S;
35 public:
36 explicit ActionCommentHandler(Sema &S) : S(S) { }
38 bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
39 S.ActOnComment(Comment);
40 return false;
43 } // end anonymous namespace
45 IdentifierInfo *Parser::getSEHExceptKeyword() {
46 // __except is accepted as a (contextual) keyword
47 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
48 Ident__except = PP.getIdentifierInfo("__except");
50 return Ident__except;
53 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
54 : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
55 Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
56 ColonIsSacred(false), InMessageExpression(false),
57 TemplateParameterDepth(0), ParsingInObjCContainer(false) {
58 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
59 Tok.startToken();
60 Tok.setKind(tok::eof);
61 Actions.CurScope = nullptr;
62 NumCachedScopes = 0;
63 CurParsedObjCImpl = nullptr;
65 // Add #pragma handlers. These are removed and destroyed in the
66 // destructor.
67 initializePragmaHandlers();
69 CommentSemaHandler.reset(new ActionCommentHandler(actions));
70 PP.addCommentHandler(CommentSemaHandler.get());
72 PP.setCodeCompletionHandler(*this);
75 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
76 return Diags.Report(Loc, DiagID);
79 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
80 return Diag(Tok.getLocation(), DiagID);
83 /// Emits a diagnostic suggesting parentheses surrounding a
84 /// given range.
85 ///
86 /// \param Loc The location where we'll emit the diagnostic.
87 /// \param DK The kind of diagnostic to emit.
88 /// \param ParenRange Source range enclosing code that should be parenthesized.
89 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
90 SourceRange ParenRange) {
91 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
92 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
93 // We can't display the parentheses, so just dig the
94 // warning/error and return.
95 Diag(Loc, DK);
96 return;
99 Diag(Loc, DK)
100 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
101 << FixItHint::CreateInsertion(EndLoc, ")");
104 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
105 switch (ExpectedTok) {
106 case tok::semi:
107 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
108 default: return false;
112 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
113 StringRef Msg) {
114 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
115 ConsumeAnyToken();
116 return false;
119 // Detect common single-character typos and resume.
120 if (IsCommonTypo(ExpectedTok, Tok)) {
121 SourceLocation Loc = Tok.getLocation();
123 DiagnosticBuilder DB = Diag(Loc, DiagID);
124 DB << FixItHint::CreateReplacement(
125 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
126 if (DiagID == diag::err_expected)
127 DB << ExpectedTok;
128 else if (DiagID == diag::err_expected_after)
129 DB << Msg << ExpectedTok;
130 else
131 DB << Msg;
134 // Pretend there wasn't a problem.
135 ConsumeAnyToken();
136 return false;
139 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
140 const char *Spelling = nullptr;
141 if (EndLoc.isValid())
142 Spelling = tok::getPunctuatorSpelling(ExpectedTok);
144 DiagnosticBuilder DB =
145 Spelling
146 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
147 : Diag(Tok, DiagID);
148 if (DiagID == diag::err_expected)
149 DB << ExpectedTok;
150 else if (DiagID == diag::err_expected_after)
151 DB << Msg << ExpectedTok;
152 else
153 DB << Msg;
155 return true;
158 bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
159 if (TryConsumeToken(tok::semi))
160 return false;
162 if (Tok.is(tok::code_completion)) {
163 handleUnexpectedCodeCompletionToken();
164 return false;
167 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
168 NextToken().is(tok::semi)) {
169 Diag(Tok, diag::err_extraneous_token_before_semi)
170 << PP.getSpelling(Tok)
171 << FixItHint::CreateRemoval(Tok.getLocation());
172 ConsumeAnyToken(); // The ')' or ']'.
173 ConsumeToken(); // The ';'.
174 return false;
177 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
180 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
181 if (!Tok.is(tok::semi)) return;
183 bool HadMultipleSemis = false;
184 SourceLocation StartLoc = Tok.getLocation();
185 SourceLocation EndLoc = Tok.getLocation();
186 ConsumeToken();
188 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
189 HadMultipleSemis = true;
190 EndLoc = Tok.getLocation();
191 ConsumeToken();
194 // C++11 allows extra semicolons at namespace scope, but not in any of the
195 // other contexts.
196 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
197 if (getLangOpts().CPlusPlus11)
198 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
199 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
200 else
201 Diag(StartLoc, diag::ext_extra_semi_cxx11)
202 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
203 return;
206 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
207 Diag(StartLoc, diag::ext_extra_semi)
208 << Kind << DeclSpec::getSpecifierName(TST,
209 Actions.getASTContext().getPrintingPolicy())
210 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
211 else
212 // A single semicolon is valid after a member function definition.
213 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
214 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
217 bool Parser::expectIdentifier() {
218 if (Tok.is(tok::identifier))
219 return false;
220 if (const auto *II = Tok.getIdentifierInfo()) {
221 if (II->isCPlusPlusKeyword(getLangOpts())) {
222 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
223 << tok::identifier << Tok.getIdentifierInfo();
224 // Objective-C++: Recover by treating this keyword as a valid identifier.
225 return false;
228 Diag(Tok, diag::err_expected) << tok::identifier;
229 return true;
232 void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
233 tok::TokenKind FirstTokKind, CompoundToken Op) {
234 if (FirstTokLoc.isInvalid())
235 return;
236 SourceLocation SecondTokLoc = Tok.getLocation();
238 // If either token is in a macro, we expect both tokens to come from the same
239 // macro expansion.
240 if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
241 PP.getSourceManager().getFileID(FirstTokLoc) !=
242 PP.getSourceManager().getFileID(SecondTokLoc)) {
243 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
244 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
245 << static_cast<int>(Op) << SourceRange(FirstTokLoc);
246 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
247 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
248 << SourceRange(SecondTokLoc);
249 return;
252 // We expect the tokens to abut.
253 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
254 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
255 if (SpaceLoc.isInvalid())
256 SpaceLoc = FirstTokLoc;
257 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
258 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
259 << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
260 return;
264 //===----------------------------------------------------------------------===//
265 // Error recovery.
266 //===----------------------------------------------------------------------===//
268 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
269 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
272 /// SkipUntil - Read tokens until we get to the specified token, then consume
273 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
274 /// token will ever occur, this skips to the next token, or to some likely
275 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
276 /// character.
278 /// If SkipUntil finds the specified token, it returns true, otherwise it
279 /// returns false.
280 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
281 // We always want this function to skip at least one token if the first token
282 // isn't T and if not at EOF.
283 bool isFirstTokenSkipped = true;
284 while (true) {
285 // If we found one of the tokens, stop and return true.
286 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
287 if (Tok.is(Toks[i])) {
288 if (HasFlagsSet(Flags, StopBeforeMatch)) {
289 // Noop, don't consume the token.
290 } else {
291 ConsumeAnyToken();
293 return true;
297 // Important special case: The caller has given up and just wants us to
298 // skip the rest of the file. Do this without recursing, since we can
299 // get here precisely because the caller detected too much recursion.
300 if (Toks.size() == 1 && Toks[0] == tok::eof &&
301 !HasFlagsSet(Flags, StopAtSemi) &&
302 !HasFlagsSet(Flags, StopAtCodeCompletion)) {
303 while (Tok.isNot(tok::eof))
304 ConsumeAnyToken();
305 return true;
308 switch (Tok.getKind()) {
309 case tok::eof:
310 // Ran out of tokens.
311 return false;
313 case tok::annot_pragma_openmp:
314 case tok::annot_attr_openmp:
315 case tok::annot_pragma_openmp_end:
316 // Stop before an OpenMP pragma boundary.
317 if (OpenMPDirectiveParsing)
318 return false;
319 ConsumeAnnotationToken();
320 break;
321 case tok::annot_module_begin:
322 case tok::annot_module_end:
323 case tok::annot_module_include:
324 case tok::annot_repl_input_end:
325 // Stop before we change submodules. They generally indicate a "good"
326 // place to pick up parsing again (except in the special case where
327 // we're trying to skip to EOF).
328 return false;
330 case tok::code_completion:
331 if (!HasFlagsSet(Flags, StopAtCodeCompletion))
332 handleUnexpectedCodeCompletionToken();
333 return false;
335 case tok::l_paren:
336 // Recursively skip properly-nested parens.
337 ConsumeParen();
338 if (HasFlagsSet(Flags, StopAtCodeCompletion))
339 SkipUntil(tok::r_paren, StopAtCodeCompletion);
340 else
341 SkipUntil(tok::r_paren);
342 break;
343 case tok::l_square:
344 // Recursively skip properly-nested square brackets.
345 ConsumeBracket();
346 if (HasFlagsSet(Flags, StopAtCodeCompletion))
347 SkipUntil(tok::r_square, StopAtCodeCompletion);
348 else
349 SkipUntil(tok::r_square);
350 break;
351 case tok::l_brace:
352 // Recursively skip properly-nested braces.
353 ConsumeBrace();
354 if (HasFlagsSet(Flags, StopAtCodeCompletion))
355 SkipUntil(tok::r_brace, StopAtCodeCompletion);
356 else
357 SkipUntil(tok::r_brace);
358 break;
359 case tok::question:
360 // Recursively skip ? ... : pairs; these function as brackets. But
361 // still stop at a semicolon if requested.
362 ConsumeToken();
363 SkipUntil(tok::colon,
364 SkipUntilFlags(unsigned(Flags) &
365 unsigned(StopAtCodeCompletion | StopAtSemi)));
366 break;
368 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
369 // Since the user wasn't looking for this token (if they were, it would
370 // already be handled), this isn't balanced. If there is a LHS token at a
371 // higher level, we will assume that this matches the unbalanced token
372 // and return it. Otherwise, this is a spurious RHS token, which we skip.
373 case tok::r_paren:
374 if (ParenCount && !isFirstTokenSkipped)
375 return false; // Matches something.
376 ConsumeParen();
377 break;
378 case tok::r_square:
379 if (BracketCount && !isFirstTokenSkipped)
380 return false; // Matches something.
381 ConsumeBracket();
382 break;
383 case tok::r_brace:
384 if (BraceCount && !isFirstTokenSkipped)
385 return false; // Matches something.
386 ConsumeBrace();
387 break;
389 case tok::semi:
390 if (HasFlagsSet(Flags, StopAtSemi))
391 return false;
392 [[fallthrough]];
393 default:
394 // Skip this token.
395 ConsumeAnyToken();
396 break;
398 isFirstTokenSkipped = false;
402 //===----------------------------------------------------------------------===//
403 // Scope manipulation
404 //===----------------------------------------------------------------------===//
406 /// EnterScope - Start a new scope.
407 void Parser::EnterScope(unsigned ScopeFlags) {
408 if (NumCachedScopes) {
409 Scope *N = ScopeCache[--NumCachedScopes];
410 N->Init(getCurScope(), ScopeFlags);
411 Actions.CurScope = N;
412 } else {
413 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
417 /// ExitScope - Pop a scope off the scope stack.
418 void Parser::ExitScope() {
419 assert(getCurScope() && "Scope imbalance!");
421 // Inform the actions module that this scope is going away if there are any
422 // decls in it.
423 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
425 Scope *OldScope = getCurScope();
426 Actions.CurScope = OldScope->getParent();
428 if (NumCachedScopes == ScopeCacheSize)
429 delete OldScope;
430 else
431 ScopeCache[NumCachedScopes++] = OldScope;
434 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
435 /// this object does nothing.
436 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
437 bool ManageFlags)
438 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
439 if (CurScope) {
440 OldFlags = CurScope->getFlags();
441 CurScope->setFlags(ScopeFlags);
445 /// Restore the flags for the current scope to what they were before this
446 /// object overrode them.
447 Parser::ParseScopeFlags::~ParseScopeFlags() {
448 if (CurScope)
449 CurScope->setFlags(OldFlags);
453 //===----------------------------------------------------------------------===//
454 // C99 6.9: External Definitions.
455 //===----------------------------------------------------------------------===//
457 Parser::~Parser() {
458 // If we still have scopes active, delete the scope tree.
459 delete getCurScope();
460 Actions.CurScope = nullptr;
462 // Free the scope cache.
463 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
464 delete ScopeCache[i];
466 resetPragmaHandlers();
468 PP.removeCommentHandler(CommentSemaHandler.get());
470 PP.clearCodeCompletionHandler();
472 DestroyTemplateIds();
475 /// Initialize - Warm up the parser.
477 void Parser::Initialize() {
478 // Create the translation unit scope. Install it as the current scope.
479 assert(getCurScope() == nullptr && "A scope is already active?");
480 EnterScope(Scope::DeclScope);
481 Actions.ActOnTranslationUnitScope(getCurScope());
483 // Initialization for Objective-C context sensitive keywords recognition.
484 // Referenced in Parser::ParseObjCTypeQualifierList.
485 if (getLangOpts().ObjC) {
486 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
487 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
488 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
489 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
490 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
491 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
492 ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
493 ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
494 ObjCTypeQuals[objc_null_unspecified]
495 = &PP.getIdentifierTable().get("null_unspecified");
498 Ident_instancetype = nullptr;
499 Ident_final = nullptr;
500 Ident_sealed = nullptr;
501 Ident_abstract = nullptr;
502 Ident_override = nullptr;
503 Ident_GNU_final = nullptr;
504 Ident_import = nullptr;
505 Ident_module = nullptr;
507 Ident_super = &PP.getIdentifierTable().get("super");
509 Ident_vector = nullptr;
510 Ident_bool = nullptr;
511 Ident_Bool = nullptr;
512 Ident_pixel = nullptr;
513 if (getLangOpts().AltiVec || getLangOpts().ZVector) {
514 Ident_vector = &PP.getIdentifierTable().get("vector");
515 Ident_bool = &PP.getIdentifierTable().get("bool");
516 Ident_Bool = &PP.getIdentifierTable().get("_Bool");
518 if (getLangOpts().AltiVec)
519 Ident_pixel = &PP.getIdentifierTable().get("pixel");
521 Ident_introduced = nullptr;
522 Ident_deprecated = nullptr;
523 Ident_obsoleted = nullptr;
524 Ident_unavailable = nullptr;
525 Ident_strict = nullptr;
526 Ident_replacement = nullptr;
528 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
529 nullptr;
531 Ident__except = nullptr;
533 Ident__exception_code = Ident__exception_info = nullptr;
534 Ident__abnormal_termination = Ident___exception_code = nullptr;
535 Ident___exception_info = Ident___abnormal_termination = nullptr;
536 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
537 Ident_AbnormalTermination = nullptr;
539 if(getLangOpts().Borland) {
540 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
541 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
542 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
543 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
544 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
545 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
546 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
547 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
548 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
550 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
551 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
552 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
553 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
554 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
555 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
556 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
557 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
558 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
561 if (getLangOpts().CPlusPlusModules) {
562 Ident_import = PP.getIdentifierInfo("import");
563 Ident_module = PP.getIdentifierInfo("module");
566 Actions.Initialize();
568 // Prime the lexer look-ahead.
569 ConsumeToken();
572 void Parser::DestroyTemplateIds() {
573 for (TemplateIdAnnotation *Id : TemplateIds)
574 Id->Destroy();
575 TemplateIds.clear();
578 /// Parse the first top-level declaration in a translation unit.
580 /// translation-unit:
581 /// [C] external-declaration
582 /// [C] translation-unit external-declaration
583 /// [C++] top-level-declaration-seq[opt]
584 /// [C++20] global-module-fragment[opt] module-declaration
585 /// top-level-declaration-seq[opt] private-module-fragment[opt]
587 /// Note that in C, it is an error if there is no first declaration.
588 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
589 Sema::ModuleImportState &ImportState) {
590 Actions.ActOnStartOfTranslationUnit();
592 // For C++20 modules, a module decl must be the first in the TU. We also
593 // need to track module imports.
594 ImportState = Sema::ModuleImportState::FirstDecl;
595 bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
597 // C11 6.9p1 says translation units must have at least one top-level
598 // declaration. C++ doesn't have this restriction. We also don't want to
599 // complain if we have a precompiled header, although technically if the PCH
600 // is empty we should still emit the (pedantic) diagnostic.
601 // If the main file is a header, we're only pretending it's a TU; don't warn.
602 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
603 !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
604 Diag(diag::ext_empty_translation_unit);
606 return NoTopLevelDecls;
609 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
610 /// action tells us to. This returns true if the EOF was encountered.
612 /// top-level-declaration:
613 /// declaration
614 /// [C++20] module-import-declaration
615 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
616 Sema::ModuleImportState &ImportState) {
617 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
619 // Skip over the EOF token, flagging end of previous input for incremental
620 // processing
621 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
622 ConsumeToken();
624 Result = nullptr;
625 switch (Tok.getKind()) {
626 case tok::annot_pragma_unused:
627 HandlePragmaUnused();
628 return false;
630 case tok::kw_export:
631 switch (NextToken().getKind()) {
632 case tok::kw_module:
633 goto module_decl;
635 // Note: no need to handle kw_import here. We only form kw_import under
636 // the Standard C++ Modules, and in that case 'export import' is parsed as
637 // an export-declaration containing an import-declaration.
639 // Recognize context-sensitive C++20 'export module' and 'export import'
640 // declarations.
641 case tok::identifier: {
642 IdentifierInfo *II = NextToken().getIdentifierInfo();
643 if ((II == Ident_module || II == Ident_import) &&
644 GetLookAheadToken(2).isNot(tok::coloncolon)) {
645 if (II == Ident_module)
646 goto module_decl;
647 else
648 goto import_decl;
650 break;
653 default:
654 break;
656 break;
658 case tok::kw_module:
659 module_decl:
660 Result = ParseModuleDecl(ImportState);
661 return false;
663 case tok::kw_import:
664 import_decl: {
665 Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
666 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
667 return false;
670 case tok::annot_module_include: {
671 auto Loc = Tok.getLocation();
672 Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
673 // FIXME: We need a better way to disambiguate C++ clang modules and
674 // standard C++ modules.
675 if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
676 Actions.ActOnModuleInclude(Loc, Mod);
677 else {
678 DeclResult Import =
679 Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
680 Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
681 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
683 ConsumeAnnotationToken();
684 return false;
687 case tok::annot_module_begin:
688 Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
689 Tok.getAnnotationValue()));
690 ConsumeAnnotationToken();
691 ImportState = Sema::ModuleImportState::NotACXX20Module;
692 return false;
694 case tok::annot_module_end:
695 Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
696 Tok.getAnnotationValue()));
697 ConsumeAnnotationToken();
698 ImportState = Sema::ModuleImportState::NotACXX20Module;
699 return false;
701 case tok::eof:
702 case tok::annot_repl_input_end:
703 // Check whether -fmax-tokens= was reached.
704 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
705 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
706 << PP.getTokenCount() << PP.getMaxTokens();
707 SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
708 if (OverrideLoc.isValid()) {
709 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
713 // Late template parsing can begin.
714 Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
715 Actions.ActOnEndOfTranslationUnit();
716 //else don't tell Sema that we ended parsing: more input might come.
717 return true;
719 case tok::identifier:
720 // C++2a [basic.link]p3:
721 // A token sequence beginning with 'export[opt] module' or
722 // 'export[opt] import' and not immediately followed by '::'
723 // is never interpreted as the declaration of a top-level-declaration.
724 if ((Tok.getIdentifierInfo() == Ident_module ||
725 Tok.getIdentifierInfo() == Ident_import) &&
726 NextToken().isNot(tok::coloncolon)) {
727 if (Tok.getIdentifierInfo() == Ident_module)
728 goto module_decl;
729 else
730 goto import_decl;
732 break;
734 default:
735 break;
738 ParsedAttributes DeclAttrs(AttrFactory);
739 ParsedAttributes DeclSpecAttrs(AttrFactory);
740 // GNU attributes are applied to the declaration specification while the
741 // standard attributes are applied to the declaration. We parse the two
742 // attribute sets into different containters so we can apply them during
743 // the regular parsing process.
744 while (MaybeParseCXX11Attributes(DeclAttrs) ||
745 MaybeParseGNUAttributes(DeclSpecAttrs))
748 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
749 // An empty Result might mean a line with ';' or some parsing error, ignore
750 // it.
751 if (Result) {
752 if (ImportState == Sema::ModuleImportState::FirstDecl)
753 // First decl was not modular.
754 ImportState = Sema::ModuleImportState::NotACXX20Module;
755 else if (ImportState == Sema::ModuleImportState::ImportAllowed)
756 // Non-imports disallow further imports.
757 ImportState = Sema::ModuleImportState::ImportFinished;
758 else if (ImportState ==
759 Sema::ModuleImportState::PrivateFragmentImportAllowed)
760 // Non-imports disallow further imports.
761 ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
763 return false;
766 /// ParseExternalDeclaration:
768 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
769 /// declaration.
771 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
772 /// function-definition
773 /// declaration
774 /// [GNU] asm-definition
775 /// [GNU] __extension__ external-declaration
776 /// [OBJC] objc-class-definition
777 /// [OBJC] objc-class-declaration
778 /// [OBJC] objc-alias-declaration
779 /// [OBJC] objc-protocol-definition
780 /// [OBJC] objc-method-definition
781 /// [OBJC] @end
782 /// [C++] linkage-specification
783 /// [GNU] asm-definition:
784 /// simple-asm-expr ';'
785 /// [C++11] empty-declaration
786 /// [C++11] attribute-declaration
788 /// [C++11] empty-declaration:
789 /// ';'
791 /// [C++0x/GNU] 'extern' 'template' declaration
793 /// [C++20] module-import-declaration
795 Parser::DeclGroupPtrTy
796 Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
797 ParsedAttributes &DeclSpecAttrs,
798 ParsingDeclSpec *DS) {
799 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
800 ParenBraceBracketBalancer BalancerRAIIObj(*this);
802 if (PP.isCodeCompletionReached()) {
803 cutOffParsing();
804 return nullptr;
807 Decl *SingleDecl = nullptr;
808 switch (Tok.getKind()) {
809 case tok::annot_pragma_vis:
810 HandlePragmaVisibility();
811 return nullptr;
812 case tok::annot_pragma_pack:
813 HandlePragmaPack();
814 return nullptr;
815 case tok::annot_pragma_msstruct:
816 HandlePragmaMSStruct();
817 return nullptr;
818 case tok::annot_pragma_align:
819 HandlePragmaAlign();
820 return nullptr;
821 case tok::annot_pragma_weak:
822 HandlePragmaWeak();
823 return nullptr;
824 case tok::annot_pragma_weakalias:
825 HandlePragmaWeakAlias();
826 return nullptr;
827 case tok::annot_pragma_redefine_extname:
828 HandlePragmaRedefineExtname();
829 return nullptr;
830 case tok::annot_pragma_fp_contract:
831 HandlePragmaFPContract();
832 return nullptr;
833 case tok::annot_pragma_fenv_access:
834 case tok::annot_pragma_fenv_access_ms:
835 HandlePragmaFEnvAccess();
836 return nullptr;
837 case tok::annot_pragma_fenv_round:
838 HandlePragmaFEnvRound();
839 return nullptr;
840 case tok::annot_pragma_float_control:
841 HandlePragmaFloatControl();
842 return nullptr;
843 case tok::annot_pragma_fp:
844 HandlePragmaFP();
845 break;
846 case tok::annot_pragma_opencl_extension:
847 HandlePragmaOpenCLExtension();
848 return nullptr;
849 case tok::annot_attr_openmp:
850 case tok::annot_pragma_openmp: {
851 AccessSpecifier AS = AS_none;
852 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
854 case tok::annot_pragma_ms_pointers_to_members:
855 HandlePragmaMSPointersToMembers();
856 return nullptr;
857 case tok::annot_pragma_ms_vtordisp:
858 HandlePragmaMSVtorDisp();
859 return nullptr;
860 case tok::annot_pragma_ms_pragma:
861 HandlePragmaMSPragma();
862 return nullptr;
863 case tok::annot_pragma_dump:
864 HandlePragmaDump();
865 return nullptr;
866 case tok::annot_pragma_attribute:
867 HandlePragmaAttribute();
868 return nullptr;
869 case tok::semi:
870 // Either a C++11 empty-declaration or attribute-declaration.
871 SingleDecl =
872 Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
873 ConsumeExtraSemi(OutsideFunction);
874 break;
875 case tok::r_brace:
876 Diag(Tok, diag::err_extraneous_closing_brace);
877 ConsumeBrace();
878 return nullptr;
879 case tok::eof:
880 Diag(Tok, diag::err_expected_external_declaration);
881 return nullptr;
882 case tok::kw___extension__: {
883 // __extension__ silences extension warnings in the subexpression.
884 ExtensionRAIIObject O(Diags); // Use RAII to do this.
885 ConsumeToken();
886 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
888 case tok::kw_asm: {
889 ProhibitAttributes(Attrs);
891 SourceLocation StartLoc = Tok.getLocation();
892 SourceLocation EndLoc;
894 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
896 // Check if GNU-style InlineAsm is disabled.
897 // Empty asm string is allowed because it will not introduce
898 // any assembly code.
899 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
900 const auto *SL = cast<StringLiteral>(Result.get());
901 if (!SL->getString().trim().empty())
902 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
905 ExpectAndConsume(tok::semi, diag::err_expected_after,
906 "top-level asm block");
908 if (Result.isInvalid())
909 return nullptr;
910 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
911 break;
913 case tok::at:
914 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
915 case tok::minus:
916 case tok::plus:
917 if (!getLangOpts().ObjC) {
918 Diag(Tok, diag::err_expected_external_declaration);
919 ConsumeToken();
920 return nullptr;
922 SingleDecl = ParseObjCMethodDefinition();
923 break;
924 case tok::code_completion:
925 cutOffParsing();
926 if (CurParsedObjCImpl) {
927 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
928 Actions.CodeCompleteObjCMethodDecl(getCurScope(),
929 /*IsInstanceMethod=*/std::nullopt,
930 /*ReturnType=*/nullptr);
933 Sema::ParserCompletionContext PCC;
934 if (CurParsedObjCImpl) {
935 PCC = Sema::PCC_ObjCImplementation;
936 } else if (PP.isIncrementalProcessingEnabled()) {
937 PCC = Sema::PCC_TopLevelOrExpression;
938 } else {
939 PCC = Sema::PCC_Namespace;
941 Actions.CodeCompleteOrdinaryName(getCurScope(), PCC);
942 return nullptr;
943 case tok::kw_import: {
944 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
945 if (getLangOpts().CPlusPlusModules) {
946 llvm_unreachable("not expecting a c++20 import here");
947 ProhibitAttributes(Attrs);
949 SingleDecl = ParseModuleImport(SourceLocation(), IS);
950 } break;
951 case tok::kw_export:
952 if (getLangOpts().CPlusPlusModules) {
953 ProhibitAttributes(Attrs);
954 SingleDecl = ParseExportDeclaration();
955 break;
957 // This must be 'export template'. Parse it so we can diagnose our lack
958 // of support.
959 [[fallthrough]];
960 case tok::kw_using:
961 case tok::kw_namespace:
962 case tok::kw_typedef:
963 case tok::kw_template:
964 case tok::kw_static_assert:
965 case tok::kw__Static_assert:
966 // A function definition cannot start with any of these keywords.
968 SourceLocation DeclEnd;
969 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
970 DeclSpecAttrs);
973 case tok::kw_cbuffer:
974 case tok::kw_tbuffer:
975 if (getLangOpts().HLSL) {
976 SourceLocation DeclEnd;
977 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
978 DeclSpecAttrs);
980 goto dont_know;
982 case tok::kw_static:
983 // Parse (then ignore) 'static' prior to a template instantiation. This is
984 // a GCC extension that we intentionally do not support.
985 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
986 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
987 << 0;
988 SourceLocation DeclEnd;
989 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
990 DeclSpecAttrs);
992 goto dont_know;
994 case tok::kw_inline:
995 if (getLangOpts().CPlusPlus) {
996 tok::TokenKind NextKind = NextToken().getKind();
998 // Inline namespaces. Allowed as an extension even in C++03.
999 if (NextKind == tok::kw_namespace) {
1000 SourceLocation DeclEnd;
1001 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1002 DeclSpecAttrs);
1005 // Parse (then ignore) 'inline' prior to a template instantiation. This is
1006 // a GCC extension that we intentionally do not support.
1007 if (NextKind == tok::kw_template) {
1008 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
1009 << 1;
1010 SourceLocation DeclEnd;
1011 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1012 DeclSpecAttrs);
1015 goto dont_know;
1017 case tok::kw_extern:
1018 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1019 // Extern templates
1020 SourceLocation ExternLoc = ConsumeToken();
1021 SourceLocation TemplateLoc = ConsumeToken();
1022 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
1023 diag::warn_cxx98_compat_extern_template :
1024 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1025 SourceLocation DeclEnd;
1026 return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
1027 DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs));
1029 goto dont_know;
1031 case tok::kw___if_exists:
1032 case tok::kw___if_not_exists:
1033 ParseMicrosoftIfExistsExternalDeclaration();
1034 return nullptr;
1036 case tok::kw_module:
1037 Diag(Tok, diag::err_unexpected_module_decl);
1038 SkipUntil(tok::semi);
1039 return nullptr;
1041 default:
1042 dont_know:
1043 if (Tok.isEditorPlaceholder()) {
1044 ConsumeToken();
1045 return nullptr;
1047 if (getLangOpts().IncrementalExtensions &&
1048 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1049 return ParseTopLevelStmtDecl();
1051 // We can't tell whether this is a function-definition or declaration yet.
1052 if (!SingleDecl)
1053 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1056 // This routine returns a DeclGroup, if the thing we parsed only contains a
1057 // single decl, convert it now.
1058 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1061 /// Determine whether the current token, if it occurs after a
1062 /// declarator, continues a declaration or declaration list.
1063 bool Parser::isDeclarationAfterDeclarator() {
1064 // Check for '= delete' or '= default'
1065 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1066 const Token &KW = NextToken();
1067 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
1068 return false;
1071 return Tok.is(tok::equal) || // int X()= -> not a function def
1072 Tok.is(tok::comma) || // int X(), -> not a function def
1073 Tok.is(tok::semi) || // int X(); -> not a function def
1074 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
1075 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
1076 (getLangOpts().CPlusPlus &&
1077 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
1080 /// Determine whether the current token, if it occurs after a
1081 /// declarator, indicates the start of a function definition.
1082 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1083 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1084 if (Tok.is(tok::l_brace)) // int X() {}
1085 return true;
1087 // Handle K&R C argument lists: int X(f) int f; {}
1088 if (!getLangOpts().CPlusPlus &&
1089 Declarator.getFunctionTypeInfo().isKNRPrototype())
1090 return isDeclarationSpecifier(ImplicitTypenameContext::No);
1092 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1093 const Token &KW = NextToken();
1094 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1097 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1098 Tok.is(tok::kw_try); // X() try { ... }
1101 /// Parse either a function-definition or a declaration. We can't tell which
1102 /// we have until we read up to the compound-statement in function-definition.
1103 /// TemplateParams, if non-NULL, provides the template parameters when we're
1104 /// parsing a C++ template-declaration.
1106 /// function-definition: [C99 6.9.1]
1107 /// decl-specs declarator declaration-list[opt] compound-statement
1108 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1109 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1111 /// declaration: [C99 6.7]
1112 /// declaration-specifiers init-declarator-list[opt] ';'
1113 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1114 /// [OMP] threadprivate-directive
1115 /// [OMP] allocate-directive [TODO]
1117 Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1118 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1119 ParsingDeclSpec &DS, AccessSpecifier AS) {
1120 // Because we assume that the DeclSpec has not yet been initialised, we simply
1121 // overwrite the source range and attribute the provided leading declspec
1122 // attributes.
1123 assert(DS.getSourceRange().isInvalid() &&
1124 "expected uninitialised source range");
1125 DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1126 DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1127 DS.takeAttributesFrom(DeclSpecAttrs);
1129 MaybeParseMicrosoftAttributes(DS.getAttributes());
1130 // Parse the common declaration-specifiers piece.
1131 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1132 DeclSpecContext::DSC_top_level);
1134 // If we had a free-standing type definition with a missing semicolon, we
1135 // may get this far before the problem becomes obvious.
1136 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1137 DS, AS, DeclSpecContext::DSC_top_level))
1138 return nullptr;
1140 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1141 // declaration-specifiers init-declarator-list[opt] ';'
1142 if (Tok.is(tok::semi)) {
1143 auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1144 assert(DeclSpec::isDeclRep(TKind));
1145 switch(TKind) {
1146 case DeclSpec::TST_class:
1147 return 5;
1148 case DeclSpec::TST_struct:
1149 return 6;
1150 case DeclSpec::TST_union:
1151 return 5;
1152 case DeclSpec::TST_enum:
1153 return 4;
1154 case DeclSpec::TST_interface:
1155 return 9;
1156 default:
1157 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1161 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1162 SourceLocation CorrectLocationForAttributes =
1163 DeclSpec::isDeclRep(DS.getTypeSpecType())
1164 ? DS.getTypeSpecTypeLoc().getLocWithOffset(
1165 LengthOfTSTToken(DS.getTypeSpecType()))
1166 : SourceLocation();
1167 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1168 ConsumeToken();
1169 RecordDecl *AnonRecord = nullptr;
1170 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1171 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1172 DS.complete(TheDecl);
1173 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1174 if (AnonRecord) {
1175 Decl* decls[] = {AnonRecord, TheDecl};
1176 return Actions.BuildDeclaratorGroup(decls);
1178 return Actions.ConvertDeclToDeclGroup(TheDecl);
1181 if (DS.hasTagDefinition())
1182 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
1184 // ObjC2 allows prefix attributes on class interfaces and protocols.
1185 // FIXME: This still needs better diagnostics. We should only accept
1186 // attributes here, no types, etc.
1187 if (getLangOpts().ObjC && Tok.is(tok::at)) {
1188 SourceLocation AtLoc = ConsumeToken(); // the "@"
1189 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1190 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1191 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1192 Diag(Tok, diag::err_objc_unexpected_attr);
1193 SkipUntil(tok::semi);
1194 return nullptr;
1197 DS.abort();
1198 DS.takeAttributesFrom(Attrs);
1200 const char *PrevSpec = nullptr;
1201 unsigned DiagID;
1202 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1203 Actions.getASTContext().getPrintingPolicy()))
1204 Diag(AtLoc, DiagID) << PrevSpec;
1206 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1207 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1209 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1210 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1212 return Actions.ConvertDeclToDeclGroup(
1213 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1216 // If the declspec consisted only of 'extern' and we have a string
1217 // literal following it, this must be a C++ linkage specifier like
1218 // 'extern "C"'.
1219 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1220 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1221 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1222 ProhibitAttributes(Attrs);
1223 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1224 return Actions.ConvertDeclToDeclGroup(TheDecl);
1227 return ParseDeclGroup(DS, DeclaratorContext::File, Attrs);
1230 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1231 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1232 ParsingDeclSpec *DS, AccessSpecifier AS) {
1233 // Add an enclosing time trace scope for a bunch of small scopes with
1234 // "EvaluateAsConstExpr".
1235 llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
1236 return Tok.getLocation().printToString(
1237 Actions.getASTContext().getSourceManager());
1240 if (DS) {
1241 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1242 } else {
1243 ParsingDeclSpec PDS(*this);
1244 // Must temporarily exit the objective-c container scope for
1245 // parsing c constructs and re-enter objc container scope
1246 // afterwards.
1247 ObjCDeclContextSwitch ObjCDC(*this);
1249 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1253 /// ParseFunctionDefinition - We parsed and verified that the specified
1254 /// Declarator is well formed. If this is a K&R-style function, read the
1255 /// parameters declaration-list, then start the compound-statement.
1257 /// function-definition: [C99 6.9.1]
1258 /// decl-specs declarator declaration-list[opt] compound-statement
1259 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1260 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1261 /// [C++] function-definition: [C++ 8.4]
1262 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1263 /// function-body
1264 /// [C++] function-definition: [C++ 8.4]
1265 /// decl-specifier-seq[opt] declarator function-try-block
1267 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1268 const ParsedTemplateInfo &TemplateInfo,
1269 LateParsedAttrList *LateParsedAttrs) {
1270 llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {
1271 return Actions.GetNameForDeclarator(D).getName().getAsString();
1274 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1275 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1276 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1277 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1279 // If this is C89 and the declspecs were completely missing, fudge in an
1280 // implicit int. We do this here because this is the only place where
1281 // declaration-specifiers are completely optional in the grammar.
1282 if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1283 Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
1284 << D.getDeclSpec().getSourceRange();
1285 const char *PrevSpec;
1286 unsigned DiagID;
1287 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1288 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1289 D.getIdentifierLoc(),
1290 PrevSpec, DiagID,
1291 Policy);
1292 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1295 // If this declaration was formed with a K&R-style identifier list for the
1296 // arguments, parse declarations for all of the args next.
1297 // int foo(a,b) int a; float b; {}
1298 if (FTI.isKNRPrototype())
1299 ParseKNRParamDeclarations(D);
1301 // We should have either an opening brace or, in a C++ constructor,
1302 // we may have a colon.
1303 if (Tok.isNot(tok::l_brace) &&
1304 (!getLangOpts().CPlusPlus ||
1305 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1306 Tok.isNot(tok::equal)))) {
1307 Diag(Tok, diag::err_expected_fn_body);
1309 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1310 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1312 // If we didn't find the '{', bail out.
1313 if (Tok.isNot(tok::l_brace))
1314 return nullptr;
1317 // Check to make sure that any normal attributes are allowed to be on
1318 // a definition. Late parsed attributes are checked at the end.
1319 if (Tok.isNot(tok::equal)) {
1320 for (const ParsedAttr &AL : D.getAttributes())
1321 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1322 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1325 // In delayed template parsing mode, for function template we consume the
1326 // tokens and store them for late parsing at the end of the translation unit.
1327 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1328 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1329 Actions.canDelayFunctionBody(D)) {
1330 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1332 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1333 Scope::CompoundStmtScope);
1334 Scope *ParentScope = getCurScope()->getParent();
1336 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1337 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1338 TemplateParameterLists);
1339 D.complete(DP);
1340 D.getMutableDeclSpec().abort();
1342 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1343 trySkippingFunctionBody()) {
1344 BodyScope.Exit();
1345 return Actions.ActOnSkippedFunctionBody(DP);
1348 CachedTokens Toks;
1349 LexTemplateFunctionForLateParsing(Toks);
1351 if (DP) {
1352 FunctionDecl *FnD = DP->getAsFunction();
1353 Actions.CheckForFunctionRedefinition(FnD);
1354 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1356 return DP;
1358 else if (CurParsedObjCImpl &&
1359 !TemplateInfo.TemplateParams &&
1360 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1361 Tok.is(tok::colon)) &&
1362 Actions.CurContext->isTranslationUnit()) {
1363 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1364 Scope::CompoundStmtScope);
1365 Scope *ParentScope = getCurScope()->getParent();
1367 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1368 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1369 MultiTemplateParamsArg());
1370 D.complete(FuncDecl);
1371 D.getMutableDeclSpec().abort();
1372 if (FuncDecl) {
1373 // Consume the tokens and store them for later parsing.
1374 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1375 CurParsedObjCImpl->HasCFunction = true;
1376 return FuncDecl;
1378 // FIXME: Should we really fall through here?
1381 // Enter a scope for the function body.
1382 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1383 Scope::CompoundStmtScope);
1385 // Parse function body eagerly if it is either '= delete;' or '= default;' as
1386 // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1387 Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
1388 SourceLocation KWLoc;
1389 if (TryConsumeToken(tok::equal)) {
1390 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1392 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1393 Diag(KWLoc, getLangOpts().CPlusPlus11
1394 ? diag::warn_cxx98_compat_defaulted_deleted_function
1395 : diag::ext_defaulted_deleted_function)
1396 << 1 /* deleted */;
1397 BodyKind = Sema::FnBodyKind::Delete;
1398 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1399 Diag(KWLoc, getLangOpts().CPlusPlus11
1400 ? diag::warn_cxx98_compat_defaulted_deleted_function
1401 : diag::ext_defaulted_deleted_function)
1402 << 0 /* defaulted */;
1403 BodyKind = Sema::FnBodyKind::Default;
1404 } else {
1405 llvm_unreachable("function definition after = not 'delete' or 'default'");
1408 if (Tok.is(tok::comma)) {
1409 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1410 << (BodyKind == Sema::FnBodyKind::Delete);
1411 SkipUntil(tok::semi);
1412 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1413 BodyKind == Sema::FnBodyKind::Delete
1414 ? "delete"
1415 : "default")) {
1416 SkipUntil(tok::semi);
1420 // Tell the actions module that we have entered a function definition with the
1421 // specified Declarator for the function.
1422 Sema::SkipBodyInfo SkipBody;
1423 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1424 TemplateInfo.TemplateParams
1425 ? *TemplateInfo.TemplateParams
1426 : MultiTemplateParamsArg(),
1427 &SkipBody, BodyKind);
1429 if (SkipBody.ShouldSkip) {
1430 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1431 if (BodyKind == Sema::FnBodyKind::Other)
1432 SkipFunctionBody();
1434 // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1435 // and it would be popped in ActOnFinishFunctionBody.
1436 // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1438 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1439 // one is already popped when finishing the lambda in BuildLambdaExpr().
1441 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1442 // and PopExpressionEvaluationContext().
1443 if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
1444 Actions.PopExpressionEvaluationContext();
1445 return Res;
1448 // Break out of the ParsingDeclarator context before we parse the body.
1449 D.complete(Res);
1451 // Break out of the ParsingDeclSpec context, too. This const_cast is
1452 // safe because we're always the sole owner.
1453 D.getMutableDeclSpec().abort();
1455 if (BodyKind != Sema::FnBodyKind::Other) {
1456 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind);
1457 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1458 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1459 return Res;
1462 // With abbreviated function templates - we need to explicitly add depth to
1463 // account for the implicit template parameter list induced by the template.
1464 if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1465 Template && Template->isAbbreviated() &&
1466 Template->getTemplateParameters()->getParam(0)->isImplicit())
1467 // First template parameter is implicit - meaning no explicit template
1468 // parameter list was specified.
1469 CurTemplateDepthTracker.addDepth(1);
1471 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1472 trySkippingFunctionBody()) {
1473 BodyScope.Exit();
1474 Actions.ActOnSkippedFunctionBody(Res);
1475 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1478 if (Tok.is(tok::kw_try))
1479 return ParseFunctionTryBlock(Res, BodyScope);
1481 // If we have a colon, then we're probably parsing a C++
1482 // ctor-initializer.
1483 if (Tok.is(tok::colon)) {
1484 ParseConstructorInitializer(Res);
1486 // Recover from error.
1487 if (!Tok.is(tok::l_brace)) {
1488 BodyScope.Exit();
1489 Actions.ActOnFinishFunctionBody(Res, nullptr);
1490 return Res;
1492 } else
1493 Actions.ActOnDefaultCtorInitializers(Res);
1495 // Late attributes are parsed in the same scope as the function body.
1496 if (LateParsedAttrs)
1497 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1499 return ParseFunctionStatementBody(Res, BodyScope);
1502 void Parser::SkipFunctionBody() {
1503 if (Tok.is(tok::equal)) {
1504 SkipUntil(tok::semi);
1505 return;
1508 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1509 if (IsFunctionTryBlock)
1510 ConsumeToken();
1512 CachedTokens Skipped;
1513 if (ConsumeAndStoreFunctionPrologue(Skipped))
1514 SkipMalformedDecl();
1515 else {
1516 SkipUntil(tok::r_brace);
1517 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1518 SkipUntil(tok::l_brace);
1519 SkipUntil(tok::r_brace);
1524 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1525 /// types for a function with a K&R-style identifier list for arguments.
1526 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1527 // We know that the top-level of this declarator is a function.
1528 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1530 // Enter function-declaration scope, limiting any declarators to the
1531 // function prototype scope, including parameter declarators.
1532 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1533 Scope::FunctionDeclarationScope | Scope::DeclScope);
1535 // Read all the argument declarations.
1536 while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1537 SourceLocation DSStart = Tok.getLocation();
1539 // Parse the common declaration-specifiers piece.
1540 DeclSpec DS(AttrFactory);
1541 ParseDeclarationSpecifiers(DS);
1543 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1544 // least one declarator'.
1545 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1546 // the declarations though. It's trivial to ignore them, really hard to do
1547 // anything else with them.
1548 if (TryConsumeToken(tok::semi)) {
1549 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1550 continue;
1553 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1554 // than register.
1555 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1556 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1557 Diag(DS.getStorageClassSpecLoc(),
1558 diag::err_invalid_storage_class_in_func_decl);
1559 DS.ClearStorageClassSpecs();
1561 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1562 Diag(DS.getThreadStorageClassSpecLoc(),
1563 diag::err_invalid_storage_class_in_func_decl);
1564 DS.ClearStorageClassSpecs();
1567 // Parse the first declarator attached to this declspec.
1568 Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1569 DeclaratorContext::KNRTypeList);
1570 ParseDeclarator(ParmDeclarator);
1572 // Handle the full declarator list.
1573 while (true) {
1574 // If attributes are present, parse them.
1575 MaybeParseGNUAttributes(ParmDeclarator);
1577 // Ask the actions module to compute the type for this declarator.
1578 Decl *Param =
1579 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1581 if (Param &&
1582 // A missing identifier has already been diagnosed.
1583 ParmDeclarator.getIdentifier()) {
1585 // Scan the argument list looking for the correct param to apply this
1586 // type.
1587 for (unsigned i = 0; ; ++i) {
1588 // C99 6.9.1p6: those declarators shall declare only identifiers from
1589 // the identifier list.
1590 if (i == FTI.NumParams) {
1591 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1592 << ParmDeclarator.getIdentifier();
1593 break;
1596 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1597 // Reject redefinitions of parameters.
1598 if (FTI.Params[i].Param) {
1599 Diag(ParmDeclarator.getIdentifierLoc(),
1600 diag::err_param_redefinition)
1601 << ParmDeclarator.getIdentifier();
1602 } else {
1603 FTI.Params[i].Param = Param;
1605 break;
1610 // If we don't have a comma, it is either the end of the list (a ';') or
1611 // an error, bail out.
1612 if (Tok.isNot(tok::comma))
1613 break;
1615 ParmDeclarator.clear();
1617 // Consume the comma.
1618 ParmDeclarator.setCommaLoc(ConsumeToken());
1620 // Parse the next declarator.
1621 ParseDeclarator(ParmDeclarator);
1624 // Consume ';' and continue parsing.
1625 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1626 continue;
1628 // Otherwise recover by skipping to next semi or mandatory function body.
1629 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1630 break;
1631 TryConsumeToken(tok::semi);
1634 // The actions module must verify that all arguments were declared.
1635 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1639 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1640 /// allowed to be a wide string, and is not subject to character translation.
1641 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1642 /// asm label as opposed to an asm statement, because such a construct does not
1643 /// behave well.
1645 /// [GNU] asm-string-literal:
1646 /// string-literal
1648 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1649 if (!isTokenStringLiteral()) {
1650 Diag(Tok, diag::err_expected_string_literal)
1651 << /*Source='in...'*/0 << "'asm'";
1652 return ExprError();
1655 ExprResult AsmString(ParseStringLiteralExpression());
1656 if (!AsmString.isInvalid()) {
1657 const auto *SL = cast<StringLiteral>(AsmString.get());
1658 if (!SL->isOrdinary()) {
1659 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1660 << SL->isWide()
1661 << SL->getSourceRange();
1662 return ExprError();
1664 if (ForAsmLabel && SL->getString().empty()) {
1665 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1666 << 2 /* an empty */ << SL->getSourceRange();
1667 return ExprError();
1670 return AsmString;
1673 /// ParseSimpleAsm
1675 /// [GNU] simple-asm-expr:
1676 /// 'asm' '(' asm-string-literal ')'
1678 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1679 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1680 SourceLocation Loc = ConsumeToken();
1682 if (isGNUAsmQualifier(Tok)) {
1683 // Remove from the end of 'asm' to the end of the asm qualifier.
1684 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1685 PP.getLocForEndOfToken(Tok.getLocation()));
1686 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1687 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1688 << FixItHint::CreateRemoval(RemovalRange);
1689 ConsumeToken();
1692 BalancedDelimiterTracker T(*this, tok::l_paren);
1693 if (T.consumeOpen()) {
1694 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1695 return ExprError();
1698 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1700 if (!Result.isInvalid()) {
1701 // Close the paren and get the location of the end bracket
1702 T.consumeClose();
1703 if (EndLoc)
1704 *EndLoc = T.getCloseLocation();
1705 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1706 if (EndLoc)
1707 *EndLoc = Tok.getLocation();
1708 ConsumeParen();
1711 return Result;
1714 /// Get the TemplateIdAnnotation from the token and put it in the
1715 /// cleanup pool so that it gets destroyed when parsing the current top level
1716 /// declaration is finished.
1717 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1718 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1719 TemplateIdAnnotation *
1720 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1721 return Id;
1724 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1725 // Push the current token back into the token stream (or revert it if it is
1726 // cached) and use an annotation scope token for current token.
1727 if (PP.isBacktrackEnabled())
1728 PP.RevertCachedTokens(1);
1729 else
1730 PP.EnterToken(Tok, /*IsReinject=*/true);
1731 Tok.setKind(tok::annot_cxxscope);
1732 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1733 Tok.setAnnotationRange(SS.getRange());
1735 // In case the tokens were cached, have Preprocessor replace them
1736 // with the annotation token. We don't need to do this if we've
1737 // just reverted back to a prior state.
1738 if (IsNewAnnotation)
1739 PP.AnnotateCachedTokens(Tok);
1742 /// Attempt to classify the name at the current token position. This may
1743 /// form a type, scope or primary expression annotation, or replace the token
1744 /// with a typo-corrected keyword. This is only appropriate when the current
1745 /// name must refer to an entity which has already been declared.
1747 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1748 /// no typo correction will be performed.
1749 /// \param AllowImplicitTypename Whether we are in a context where a dependent
1750 /// nested-name-specifier without typename is treated as a type (e.g.
1751 /// T::type).
1752 Parser::AnnotatedNameKind
1753 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1754 ImplicitTypenameContext AllowImplicitTypename) {
1755 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1757 const bool EnteringContext = false;
1758 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1760 CXXScopeSpec SS;
1761 if (getLangOpts().CPlusPlus &&
1762 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1763 /*ObjectHasErrors=*/false,
1764 EnteringContext))
1765 return ANK_Error;
1767 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1768 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1769 AllowImplicitTypename))
1770 return ANK_Error;
1771 return ANK_Unresolved;
1774 IdentifierInfo *Name = Tok.getIdentifierInfo();
1775 SourceLocation NameLoc = Tok.getLocation();
1777 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1778 // typo-correct to tentatively-declared identifiers.
1779 if (isTentativelyDeclared(Name) && SS.isEmpty()) {
1780 // Identifier has been tentatively declared, and thus cannot be resolved as
1781 // an expression. Fall back to annotating it as a type.
1782 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1783 AllowImplicitTypename))
1784 return ANK_Error;
1785 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1788 Token Next = NextToken();
1790 // Look up and classify the identifier. We don't perform any typo-correction
1791 // after a scope specifier, because in general we can't recover from typos
1792 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1793 // jump back into scope specifier parsing).
1794 Sema::NameClassification Classification = Actions.ClassifyName(
1795 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1797 // If name lookup found nothing and we guessed that this was a template name,
1798 // double-check before committing to that interpretation. C++20 requires that
1799 // we interpret this as a template-id if it can be, but if it can't be, then
1800 // this is an error recovery case.
1801 if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1802 isTemplateArgumentList(1) == TPResult::False) {
1803 // It's not a template-id; re-classify without the '<' as a hint.
1804 Token FakeNext = Next;
1805 FakeNext.setKind(tok::unknown);
1806 Classification =
1807 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1808 SS.isEmpty() ? CCC : nullptr);
1811 switch (Classification.getKind()) {
1812 case Sema::NC_Error:
1813 return ANK_Error;
1815 case Sema::NC_Keyword:
1816 // The identifier was typo-corrected to a keyword.
1817 Tok.setIdentifierInfo(Name);
1818 Tok.setKind(Name->getTokenID());
1819 PP.TypoCorrectToken(Tok);
1820 if (SS.isNotEmpty())
1821 AnnotateScopeToken(SS, !WasScopeAnnotation);
1822 // We've "annotated" this as a keyword.
1823 return ANK_Success;
1825 case Sema::NC_Unknown:
1826 // It's not something we know about. Leave it unannotated.
1827 break;
1829 case Sema::NC_Type: {
1830 if (TryAltiVecVectorToken())
1831 // vector has been found as a type id when altivec is enabled but
1832 // this is followed by a declaration specifier so this is really the
1833 // altivec vector token. Leave it unannotated.
1834 break;
1835 SourceLocation BeginLoc = NameLoc;
1836 if (SS.isNotEmpty())
1837 BeginLoc = SS.getBeginLoc();
1839 /// An Objective-C object type followed by '<' is a specialization of
1840 /// a parameterized class type or a protocol-qualified type.
1841 ParsedType Ty = Classification.getType();
1842 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1843 (Ty.get()->isObjCObjectType() ||
1844 Ty.get()->isObjCObjectPointerType())) {
1845 // Consume the name.
1846 SourceLocation IdentifierLoc = ConsumeToken();
1847 SourceLocation NewEndLoc;
1848 TypeResult NewType
1849 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1850 /*consumeLastToken=*/false,
1851 NewEndLoc);
1852 if (NewType.isUsable())
1853 Ty = NewType.get();
1854 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1855 return ANK_Error;
1858 Tok.setKind(tok::annot_typename);
1859 setTypeAnnotation(Tok, Ty);
1860 Tok.setAnnotationEndLoc(Tok.getLocation());
1861 Tok.setLocation(BeginLoc);
1862 PP.AnnotateCachedTokens(Tok);
1863 return ANK_Success;
1866 case Sema::NC_OverloadSet:
1867 Tok.setKind(tok::annot_overload_set);
1868 setExprAnnotation(Tok, Classification.getExpression());
1869 Tok.setAnnotationEndLoc(NameLoc);
1870 if (SS.isNotEmpty())
1871 Tok.setLocation(SS.getBeginLoc());
1872 PP.AnnotateCachedTokens(Tok);
1873 return ANK_Success;
1875 case Sema::NC_NonType:
1876 if (TryAltiVecVectorToken())
1877 // vector has been found as a non-type id when altivec is enabled but
1878 // this is followed by a declaration specifier so this is really the
1879 // altivec vector token. Leave it unannotated.
1880 break;
1881 Tok.setKind(tok::annot_non_type);
1882 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1883 Tok.setLocation(NameLoc);
1884 Tok.setAnnotationEndLoc(NameLoc);
1885 PP.AnnotateCachedTokens(Tok);
1886 if (SS.isNotEmpty())
1887 AnnotateScopeToken(SS, !WasScopeAnnotation);
1888 return ANK_Success;
1890 case Sema::NC_UndeclaredNonType:
1891 case Sema::NC_DependentNonType:
1892 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1893 ? tok::annot_non_type_undeclared
1894 : tok::annot_non_type_dependent);
1895 setIdentifierAnnotation(Tok, Name);
1896 Tok.setLocation(NameLoc);
1897 Tok.setAnnotationEndLoc(NameLoc);
1898 PP.AnnotateCachedTokens(Tok);
1899 if (SS.isNotEmpty())
1900 AnnotateScopeToken(SS, !WasScopeAnnotation);
1901 return ANK_Success;
1903 case Sema::NC_TypeTemplate:
1904 if (Next.isNot(tok::less)) {
1905 // This may be a type template being used as a template template argument.
1906 if (SS.isNotEmpty())
1907 AnnotateScopeToken(SS, !WasScopeAnnotation);
1908 return ANK_TemplateName;
1910 [[fallthrough]];
1911 case Sema::NC_Concept:
1912 case Sema::NC_VarTemplate:
1913 case Sema::NC_FunctionTemplate:
1914 case Sema::NC_UndeclaredTemplate: {
1915 bool IsConceptName = Classification.getKind() == Sema::NC_Concept;
1916 // We have a template name followed by '<'. Consume the identifier token so
1917 // we reach the '<' and annotate it.
1918 if (Next.is(tok::less))
1919 ConsumeToken();
1920 UnqualifiedId Id;
1921 Id.setIdentifier(Name, NameLoc);
1922 if (AnnotateTemplateIdToken(
1923 TemplateTy::make(Classification.getTemplateName()),
1924 Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1925 /*AllowTypeAnnotation=*/!IsConceptName,
1926 /*TypeConstraint=*/IsConceptName))
1927 return ANK_Error;
1928 if (SS.isNotEmpty())
1929 AnnotateScopeToken(SS, !WasScopeAnnotation);
1930 return ANK_Success;
1934 // Unable to classify the name, but maybe we can annotate a scope specifier.
1935 if (SS.isNotEmpty())
1936 AnnotateScopeToken(SS, !WasScopeAnnotation);
1937 return ANK_Unresolved;
1940 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1941 assert(Tok.isNot(tok::identifier));
1942 Diag(Tok, diag::ext_keyword_as_ident)
1943 << PP.getSpelling(Tok)
1944 << DisableKeyword;
1945 if (DisableKeyword)
1946 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1947 Tok.setKind(tok::identifier);
1948 return true;
1951 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1952 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1953 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1954 /// with a single annotation token representing the typename or C++ scope
1955 /// respectively.
1956 /// This simplifies handling of C++ scope specifiers and allows efficient
1957 /// backtracking without the need to re-parse and resolve nested-names and
1958 /// typenames.
1959 /// It will mainly be called when we expect to treat identifiers as typenames
1960 /// (if they are typenames). For example, in C we do not expect identifiers
1961 /// inside expressions to be treated as typenames so it will not be called
1962 /// for expressions in C.
1963 /// The benefit for C/ObjC is that a typename will be annotated and
1964 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1965 /// will not be called twice, once to check whether we have a declaration
1966 /// specifier, and another one to get the actual type inside
1967 /// ParseDeclarationSpecifiers).
1969 /// This returns true if an error occurred.
1971 /// Note that this routine emits an error if you call it with ::new or ::delete
1972 /// as the current tokens, so only call it in contexts where these are invalid.
1973 bool Parser::TryAnnotateTypeOrScopeToken(
1974 ImplicitTypenameContext AllowImplicitTypename) {
1975 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1976 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1977 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1978 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto)) &&
1979 "Cannot be a type or scope token!");
1981 if (Tok.is(tok::kw_typename)) {
1982 // MSVC lets you do stuff like:
1983 // typename typedef T_::D D;
1985 // We will consume the typedef token here and put it back after we have
1986 // parsed the first identifier, transforming it into something more like:
1987 // typename T_::D typedef D;
1988 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1989 Token TypedefToken;
1990 PP.Lex(TypedefToken);
1991 bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
1992 PP.EnterToken(Tok, /*IsReinject=*/true);
1993 Tok = TypedefToken;
1994 if (!Result)
1995 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1996 return Result;
1999 // Parse a C++ typename-specifier, e.g., "typename T::type".
2001 // typename-specifier:
2002 // 'typename' '::' [opt] nested-name-specifier identifier
2003 // 'typename' '::' [opt] nested-name-specifier template [opt]
2004 // simple-template-id
2005 SourceLocation TypenameLoc = ConsumeToken();
2006 CXXScopeSpec SS;
2007 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2008 /*ObjectHasErrors=*/false,
2009 /*EnteringContext=*/false, nullptr,
2010 /*IsTypename*/ true))
2011 return true;
2012 if (SS.isEmpty()) {
2013 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
2014 Tok.is(tok::annot_decltype)) {
2015 // Attempt to recover by skipping the invalid 'typename'
2016 if (Tok.is(tok::annot_decltype) ||
2017 (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
2018 Tok.isAnnotation())) {
2019 unsigned DiagID = diag::err_expected_qualified_after_typename;
2020 // MS compatibility: MSVC permits using known types with typename.
2021 // e.g. "typedef typename T* pointer_type"
2022 if (getLangOpts().MicrosoftExt)
2023 DiagID = diag::warn_expected_qualified_after_typename;
2024 Diag(Tok.getLocation(), DiagID);
2025 return false;
2028 if (Tok.isEditorPlaceholder())
2029 return true;
2031 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
2032 return true;
2035 TypeResult Ty;
2036 if (Tok.is(tok::identifier)) {
2037 // FIXME: check whether the next token is '<', first!
2038 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
2039 *Tok.getIdentifierInfo(),
2040 Tok.getLocation());
2041 } else if (Tok.is(tok::annot_template_id)) {
2042 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2043 if (!TemplateId->mightBeType()) {
2044 Diag(Tok, diag::err_typename_refers_to_non_type_template)
2045 << Tok.getAnnotationRange();
2046 return true;
2049 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2050 TemplateId->NumArgs);
2052 Ty = TemplateId->isInvalid()
2053 ? TypeError()
2054 : Actions.ActOnTypenameType(
2055 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
2056 TemplateId->Template, TemplateId->Name,
2057 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
2058 TemplateArgsPtr, TemplateId->RAngleLoc);
2059 } else {
2060 Diag(Tok, diag::err_expected_type_name_after_typename)
2061 << SS.getRange();
2062 return true;
2065 SourceLocation EndLoc = Tok.getLastLoc();
2066 Tok.setKind(tok::annot_typename);
2067 setTypeAnnotation(Tok, Ty);
2068 Tok.setAnnotationEndLoc(EndLoc);
2069 Tok.setLocation(TypenameLoc);
2070 PP.AnnotateCachedTokens(Tok);
2071 return false;
2074 // Remembers whether the token was originally a scope annotation.
2075 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2077 CXXScopeSpec SS;
2078 if (getLangOpts().CPlusPlus)
2079 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2080 /*ObjectHasErrors=*/false,
2081 /*EnteringContext*/ false))
2082 return true;
2084 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2085 AllowImplicitTypename);
2088 /// Try to annotate a type or scope token, having already parsed an
2089 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
2090 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
2091 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
2092 CXXScopeSpec &SS, bool IsNewScope,
2093 ImplicitTypenameContext AllowImplicitTypename) {
2094 if (Tok.is(tok::identifier)) {
2095 // Determine whether the identifier is a type name.
2096 if (ParsedType Ty = Actions.getTypeName(
2097 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
2098 false, NextToken().is(tok::period), nullptr,
2099 /*IsCtorOrDtorName=*/false,
2100 /*NonTrivialTypeSourceInfo=*/true,
2101 /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2102 SourceLocation BeginLoc = Tok.getLocation();
2103 if (SS.isNotEmpty()) // it was a C++ qualified type name.
2104 BeginLoc = SS.getBeginLoc();
2106 /// An Objective-C object type followed by '<' is a specialization of
2107 /// a parameterized class type or a protocol-qualified type.
2108 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
2109 (Ty.get()->isObjCObjectType() ||
2110 Ty.get()->isObjCObjectPointerType())) {
2111 // Consume the name.
2112 SourceLocation IdentifierLoc = ConsumeToken();
2113 SourceLocation NewEndLoc;
2114 TypeResult NewType
2115 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
2116 /*consumeLastToken=*/false,
2117 NewEndLoc);
2118 if (NewType.isUsable())
2119 Ty = NewType.get();
2120 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
2121 return false;
2124 // This is a typename. Replace the current token in-place with an
2125 // annotation type token.
2126 Tok.setKind(tok::annot_typename);
2127 setTypeAnnotation(Tok, Ty);
2128 Tok.setAnnotationEndLoc(Tok.getLocation());
2129 Tok.setLocation(BeginLoc);
2131 // In case the tokens were cached, have Preprocessor replace
2132 // them with the annotation token.
2133 PP.AnnotateCachedTokens(Tok);
2134 return false;
2137 if (!getLangOpts().CPlusPlus) {
2138 // If we're in C, the only place we can have :: tokens is C23
2139 // attribute which is parsed elsewhere. If the identifier is not a type,
2140 // then it can't be scope either, just early exit.
2141 return false;
2144 // If this is a template-id, annotate with a template-id or type token.
2145 // FIXME: This appears to be dead code. We already have formed template-id
2146 // tokens when parsing the scope specifier; this can never form a new one.
2147 if (NextToken().is(tok::less)) {
2148 TemplateTy Template;
2149 UnqualifiedId TemplateName;
2150 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2151 bool MemberOfUnknownSpecialization;
2152 if (TemplateNameKind TNK = Actions.isTemplateName(
2153 getCurScope(), SS,
2154 /*hasTemplateKeyword=*/false, TemplateName,
2155 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2156 MemberOfUnknownSpecialization)) {
2157 // Only annotate an undeclared template name as a template-id if the
2158 // following tokens have the form of a template argument list.
2159 if (TNK != TNK_Undeclared_template ||
2160 isTemplateArgumentList(1) != TPResult::False) {
2161 // Consume the identifier.
2162 ConsumeToken();
2163 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2164 TemplateName)) {
2165 // If an unrecoverable error occurred, we need to return true here,
2166 // because the token stream is in a damaged state. We may not
2167 // return a valid identifier.
2168 return true;
2174 // The current token, which is either an identifier or a
2175 // template-id, is not part of the annotation. Fall through to
2176 // push that token back into the stream and complete the C++ scope
2177 // specifier annotation.
2180 if (Tok.is(tok::annot_template_id)) {
2181 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2182 if (TemplateId->Kind == TNK_Type_template) {
2183 // A template-id that refers to a type was parsed into a
2184 // template-id annotation in a context where we weren't allowed
2185 // to produce a type annotation token. Update the template-id
2186 // annotation token to a type annotation token now.
2187 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2188 return false;
2192 if (SS.isEmpty())
2193 return false;
2195 // A C++ scope specifier that isn't followed by a typename.
2196 AnnotateScopeToken(SS, IsNewScope);
2197 return false;
2200 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2201 /// annotates C++ scope specifiers and template-ids. This returns
2202 /// true if there was an error that could not be recovered from.
2204 /// Note that this routine emits an error if you call it with ::new or ::delete
2205 /// as the current tokens, so only call it in contexts where these are invalid.
2206 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2207 assert(getLangOpts().CPlusPlus &&
2208 "Call sites of this function should be guarded by checking for C++");
2209 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2211 CXXScopeSpec SS;
2212 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2213 /*ObjectHasErrors=*/false,
2214 EnteringContext))
2215 return true;
2216 if (SS.isEmpty())
2217 return false;
2219 AnnotateScopeToken(SS, true);
2220 return false;
2223 bool Parser::isTokenEqualOrEqualTypo() {
2224 tok::TokenKind Kind = Tok.getKind();
2225 switch (Kind) {
2226 default:
2227 return false;
2228 case tok::ampequal: // &=
2229 case tok::starequal: // *=
2230 case tok::plusequal: // +=
2231 case tok::minusequal: // -=
2232 case tok::exclaimequal: // !=
2233 case tok::slashequal: // /=
2234 case tok::percentequal: // %=
2235 case tok::lessequal: // <=
2236 case tok::lesslessequal: // <<=
2237 case tok::greaterequal: // >=
2238 case tok::greatergreaterequal: // >>=
2239 case tok::caretequal: // ^=
2240 case tok::pipeequal: // |=
2241 case tok::equalequal: // ==
2242 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2243 << Kind
2244 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2245 [[fallthrough]];
2246 case tok::equal:
2247 return true;
2251 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2252 assert(Tok.is(tok::code_completion));
2253 PrevTokLocation = Tok.getLocation();
2255 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2256 if (S->isFunctionScope()) {
2257 cutOffParsing();
2258 Actions.CodeCompleteOrdinaryName(getCurScope(),
2259 Sema::PCC_RecoveryInFunction);
2260 return PrevTokLocation;
2263 if (S->isClassScope()) {
2264 cutOffParsing();
2265 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2266 return PrevTokLocation;
2270 cutOffParsing();
2271 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2272 return PrevTokLocation;
2275 // Code-completion pass-through functions
2277 void Parser::CodeCompleteDirective(bool InConditional) {
2278 Actions.CodeCompletePreprocessorDirective(InConditional);
2281 void Parser::CodeCompleteInConditionalExclusion() {
2282 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2285 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2286 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2289 void Parser::CodeCompletePreprocessorExpression() {
2290 Actions.CodeCompletePreprocessorExpression();
2293 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2294 MacroInfo *MacroInfo,
2295 unsigned ArgumentIndex) {
2296 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2297 ArgumentIndex);
2300 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2301 Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2304 void Parser::CodeCompleteNaturalLanguage() {
2305 Actions.CodeCompleteNaturalLanguage();
2308 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2309 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2310 "Expected '__if_exists' or '__if_not_exists'");
2311 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2312 Result.KeywordLoc = ConsumeToken();
2314 BalancedDelimiterTracker T(*this, tok::l_paren);
2315 if (T.consumeOpen()) {
2316 Diag(Tok, diag::err_expected_lparen_after)
2317 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2318 return true;
2321 // Parse nested-name-specifier.
2322 if (getLangOpts().CPlusPlus)
2323 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2324 /*ObjectHasErrors=*/false,
2325 /*EnteringContext=*/false);
2327 // Check nested-name specifier.
2328 if (Result.SS.isInvalid()) {
2329 T.skipToEnd();
2330 return true;
2333 // Parse the unqualified-id.
2334 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2335 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2336 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2337 /*AllowDestructorName*/ true,
2338 /*AllowConstructorName*/ true,
2339 /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2340 Result.Name)) {
2341 T.skipToEnd();
2342 return true;
2345 if (T.consumeClose())
2346 return true;
2348 // Check if the symbol exists.
2349 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2350 Result.IsIfExists, Result.SS,
2351 Result.Name)) {
2352 case Sema::IER_Exists:
2353 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2354 break;
2356 case Sema::IER_DoesNotExist:
2357 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2358 break;
2360 case Sema::IER_Dependent:
2361 Result.Behavior = IEB_Dependent;
2362 break;
2364 case Sema::IER_Error:
2365 return true;
2368 return false;
2371 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2372 IfExistsCondition Result;
2373 if (ParseMicrosoftIfExistsCondition(Result))
2374 return;
2376 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2377 if (Braces.consumeOpen()) {
2378 Diag(Tok, diag::err_expected) << tok::l_brace;
2379 return;
2382 switch (Result.Behavior) {
2383 case IEB_Parse:
2384 // Parse declarations below.
2385 break;
2387 case IEB_Dependent:
2388 llvm_unreachable("Cannot have a dependent external declaration");
2390 case IEB_Skip:
2391 Braces.skipToEnd();
2392 return;
2395 // Parse the declarations.
2396 // FIXME: Support module import within __if_exists?
2397 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2398 ParsedAttributes Attrs(AttrFactory);
2399 MaybeParseCXX11Attributes(Attrs);
2400 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2401 DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
2402 if (Result && !getCurScope()->getParent())
2403 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2405 Braces.consumeClose();
2408 /// Parse a declaration beginning with the 'module' keyword or C++20
2409 /// context-sensitive keyword (optionally preceded by 'export').
2411 /// module-declaration: [C++20]
2412 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2414 /// global-module-fragment: [C++2a]
2415 /// 'module' ';' top-level-declaration-seq[opt]
2416 /// module-declaration: [C++2a]
2417 /// 'export'[opt] 'module' module-name module-partition[opt]
2418 /// attribute-specifier-seq[opt] ';'
2419 /// private-module-fragment: [C++2a]
2420 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2421 Parser::DeclGroupPtrTy
2422 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2423 SourceLocation StartLoc = Tok.getLocation();
2425 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2426 ? Sema::ModuleDeclKind::Interface
2427 : Sema::ModuleDeclKind::Implementation;
2429 assert(
2430 (Tok.is(tok::kw_module) ||
2431 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2432 "not a module declaration");
2433 SourceLocation ModuleLoc = ConsumeToken();
2435 // Attributes appear after the module name, not before.
2436 // FIXME: Suggest moving the attributes later with a fixit.
2437 DiagnoseAndSkipCXX11Attributes();
2439 // Parse a global-module-fragment, if present.
2440 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2441 SourceLocation SemiLoc = ConsumeToken();
2442 if (ImportState != Sema::ModuleImportState::FirstDecl) {
2443 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2444 << SourceRange(StartLoc, SemiLoc);
2445 return nullptr;
2447 if (MDK == Sema::ModuleDeclKind::Interface) {
2448 Diag(StartLoc, diag::err_module_fragment_exported)
2449 << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2451 ImportState = Sema::ModuleImportState::GlobalFragment;
2452 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2455 // Parse a private-module-fragment, if present.
2456 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2457 NextToken().is(tok::kw_private)) {
2458 if (MDK == Sema::ModuleDeclKind::Interface) {
2459 Diag(StartLoc, diag::err_module_fragment_exported)
2460 << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2462 ConsumeToken();
2463 SourceLocation PrivateLoc = ConsumeToken();
2464 DiagnoseAndSkipCXX11Attributes();
2465 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2466 ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2467 ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2468 : Sema::ModuleImportState::PrivateFragmentImportFinished;
2469 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2472 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2473 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2474 return nullptr;
2476 // Parse the optional module-partition.
2477 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2478 if (Tok.is(tok::colon)) {
2479 SourceLocation ColonLoc = ConsumeToken();
2480 if (!getLangOpts().CPlusPlusModules)
2481 Diag(ColonLoc, diag::err_unsupported_module_partition)
2482 << SourceRange(ColonLoc, Partition.back().second);
2483 // Recover by ignoring the partition name.
2484 else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
2485 return nullptr;
2488 // We don't support any module attributes yet; just parse them and diagnose.
2489 ParsedAttributes Attrs(AttrFactory);
2490 MaybeParseCXX11Attributes(Attrs);
2491 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2492 diag::err_keyword_not_module_attr,
2493 /*DiagnoseEmptyAttrs=*/false,
2494 /*WarnOnUnknownAttrs=*/true);
2496 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2498 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2499 ImportState);
2502 /// Parse a module import declaration. This is essentially the same for
2503 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2504 /// trailing optional attributes (in C++).
2506 /// [ObjC] @import declaration:
2507 /// '@' 'import' module-name ';'
2508 /// [ModTS] module-import-declaration:
2509 /// 'import' module-name attribute-specifier-seq[opt] ';'
2510 /// [C++20] module-import-declaration:
2511 /// 'export'[opt] 'import' module-name
2512 /// attribute-specifier-seq[opt] ';'
2513 /// 'export'[opt] 'import' module-partition
2514 /// attribute-specifier-seq[opt] ';'
2515 /// 'export'[opt] 'import' header-name
2516 /// attribute-specifier-seq[opt] ';'
2517 Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2518 Sema::ModuleImportState &ImportState) {
2519 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2521 SourceLocation ExportLoc;
2522 TryConsumeToken(tok::kw_export, ExportLoc);
2524 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2525 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2526 "Improper start to module import");
2527 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2528 SourceLocation ImportLoc = ConsumeToken();
2530 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2531 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2532 bool IsPartition = false;
2533 Module *HeaderUnit = nullptr;
2534 if (Tok.is(tok::header_name)) {
2535 // This is a header import that the preprocessor decided we should skip
2536 // because it was malformed in some way. Parse and ignore it; it's already
2537 // been diagnosed.
2538 ConsumeToken();
2539 } else if (Tok.is(tok::annot_header_unit)) {
2540 // This is a header import that the preprocessor mapped to a module import.
2541 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2542 ConsumeAnnotationToken();
2543 } else if (Tok.is(tok::colon)) {
2544 SourceLocation ColonLoc = ConsumeToken();
2545 if (!getLangOpts().CPlusPlusModules)
2546 Diag(ColonLoc, diag::err_unsupported_module_partition)
2547 << SourceRange(ColonLoc, Path.back().second);
2548 // Recover by leaving partition empty.
2549 else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
2550 return nullptr;
2551 else
2552 IsPartition = true;
2553 } else {
2554 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
2555 return nullptr;
2558 ParsedAttributes Attrs(AttrFactory);
2559 MaybeParseCXX11Attributes(Attrs);
2560 // We don't support any module import attributes yet.
2561 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2562 diag::err_keyword_not_import_attr,
2563 /*DiagnoseEmptyAttrs=*/false,
2564 /*WarnOnUnknownAttrs=*/true);
2566 if (PP.hadModuleLoaderFatalFailure()) {
2567 // With a fatal failure in the module loader, we abort parsing.
2568 cutOffParsing();
2569 return nullptr;
2572 // Diagnose mis-imports.
2573 bool SeenError = true;
2574 switch (ImportState) {
2575 case Sema::ModuleImportState::ImportAllowed:
2576 SeenError = false;
2577 break;
2578 case Sema::ModuleImportState::FirstDecl:
2579 // If we found an import decl as the first declaration, we must be not in
2580 // a C++20 module unit or we are in an invalid state.
2581 ImportState = Sema::ModuleImportState::NotACXX20Module;
2582 [[fallthrough]];
2583 case Sema::ModuleImportState::NotACXX20Module:
2584 // We can only import a partition within a module purview.
2585 if (IsPartition)
2586 Diag(ImportLoc, diag::err_partition_import_outside_module);
2587 else
2588 SeenError = false;
2589 break;
2590 case Sema::ModuleImportState::GlobalFragment:
2591 case Sema::ModuleImportState::PrivateFragmentImportAllowed:
2592 // We can only have pre-processor directives in the global module fragment
2593 // which allows pp-import, but not of a partition (since the global module
2594 // does not have partitions).
2595 // We cannot import a partition into a private module fragment, since
2596 // [module.private.frag]/1 disallows private module fragments in a multi-
2597 // TU module.
2598 if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2599 Module::ModuleKind::ModuleHeaderUnit))
2600 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2601 << IsPartition
2602 << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
2603 else
2604 SeenError = false;
2605 break;
2606 case Sema::ModuleImportState::ImportFinished:
2607 case Sema::ModuleImportState::PrivateFragmentImportFinished:
2608 if (getLangOpts().CPlusPlusModules)
2609 Diag(ImportLoc, diag::err_import_not_allowed_here);
2610 else
2611 SeenError = false;
2612 break;
2614 if (SeenError) {
2615 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2616 return nullptr;
2619 DeclResult Import;
2620 if (HeaderUnit)
2621 Import =
2622 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2623 else if (!Path.empty())
2624 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2625 IsPartition);
2626 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2627 if (Import.isInvalid())
2628 return nullptr;
2630 // Using '@import' in framework headers requires modules to be enabled so that
2631 // the header is parseable. Emit a warning to make the user aware.
2632 if (IsObjCAtImport && AtLoc.isValid()) {
2633 auto &SrcMgr = PP.getSourceManager();
2634 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2635 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2636 .endswith(".framework"))
2637 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2640 return Import.get();
2643 /// Parse a C++ / Objective-C module name (both forms use the same
2644 /// grammar).
2646 /// module-name:
2647 /// module-name-qualifier[opt] identifier
2648 /// module-name-qualifier:
2649 /// module-name-qualifier[opt] identifier '.'
2650 bool Parser::ParseModuleName(
2651 SourceLocation UseLoc,
2652 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2653 bool IsImport) {
2654 // Parse the module path.
2655 while (true) {
2656 if (!Tok.is(tok::identifier)) {
2657 if (Tok.is(tok::code_completion)) {
2658 cutOffParsing();
2659 Actions.CodeCompleteModuleImport(UseLoc, Path);
2660 return true;
2663 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2664 SkipUntil(tok::semi);
2665 return true;
2668 // Record this part of the module path.
2669 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2670 ConsumeToken();
2672 if (Tok.isNot(tok::period))
2673 return false;
2675 ConsumeToken();
2679 /// Try recover parser when module annotation appears where it must not
2680 /// be found.
2681 /// \returns false if the recover was successful and parsing may be continued, or
2682 /// true if parser must bail out to top level and handle the token there.
2683 bool Parser::parseMisplacedModuleImport() {
2684 while (true) {
2685 switch (Tok.getKind()) {
2686 case tok::annot_module_end:
2687 // If we recovered from a misplaced module begin, we expect to hit a
2688 // misplaced module end too. Stay in the current context when this
2689 // happens.
2690 if (MisplacedModuleBeginCount) {
2691 --MisplacedModuleBeginCount;
2692 Actions.ActOnModuleEnd(Tok.getLocation(),
2693 reinterpret_cast<Module *>(
2694 Tok.getAnnotationValue()));
2695 ConsumeAnnotationToken();
2696 continue;
2698 // Inform caller that recovery failed, the error must be handled at upper
2699 // level. This will generate the desired "missing '}' at end of module"
2700 // diagnostics on the way out.
2701 return true;
2702 case tok::annot_module_begin:
2703 // Recover by entering the module (Sema will diagnose).
2704 Actions.ActOnModuleBegin(Tok.getLocation(),
2705 reinterpret_cast<Module *>(
2706 Tok.getAnnotationValue()));
2707 ConsumeAnnotationToken();
2708 ++MisplacedModuleBeginCount;
2709 continue;
2710 case tok::annot_module_include:
2711 // Module import found where it should not be, for instance, inside a
2712 // namespace. Recover by importing the module.
2713 Actions.ActOnModuleInclude(Tok.getLocation(),
2714 reinterpret_cast<Module *>(
2715 Tok.getAnnotationValue()));
2716 ConsumeAnnotationToken();
2717 // If there is another module import, process it.
2718 continue;
2719 default:
2720 return false;
2723 return false;
2726 bool BalancedDelimiterTracker::diagnoseOverflow() {
2727 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2728 << P.getLangOpts().BracketDepth;
2729 P.Diag(P.Tok, diag::note_bracket_depth);
2730 P.cutOffParsing();
2731 return true;
2734 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2735 const char *Msg,
2736 tok::TokenKind SkipToTok) {
2737 LOpen = P.Tok.getLocation();
2738 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2739 if (SkipToTok != tok::unknown)
2740 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2741 return true;
2744 if (getDepth() < P.getLangOpts().BracketDepth)
2745 return false;
2747 return diagnoseOverflow();
2750 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2751 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2753 if (P.Tok.is(tok::annot_module_end))
2754 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2755 else
2756 P.Diag(P.Tok, diag::err_expected) << Close;
2757 P.Diag(LOpen, diag::note_matching) << Kind;
2759 // If we're not already at some kind of closing bracket, skip to our closing
2760 // token.
2761 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2762 P.Tok.isNot(tok::r_square) &&
2763 P.SkipUntil(Close, FinalToken,
2764 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2765 P.Tok.is(Close))
2766 LClose = P.ConsumeAnyToken();
2767 return true;
2770 void BalancedDelimiterTracker::skipToEnd() {
2771 P.SkipUntil(Close, Parser::StopBeforeMatch);
2772 consumeClose();