[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / Parse / Parser.cpp
blobc197d6bdde6724f51283e1c34625b92ee63b9c6c
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/DeclTemplate.h"
17 #include "clang/AST/ASTLambda.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 using namespace clang;
28 namespace {
29 /// A comment handler that passes comments found by the preprocessor
30 /// to the parser action.
31 class ActionCommentHandler : public CommentHandler {
32 Sema &S;
34 public:
35 explicit ActionCommentHandler(Sema &S) : S(S) { }
37 bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
38 S.ActOnComment(Comment);
39 return false;
42 } // end anonymous namespace
44 IdentifierInfo *Parser::getSEHExceptKeyword() {
45 // __except is accepted as a (contextual) keyword
46 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
47 Ident__except = PP.getIdentifierInfo("__except");
49 return Ident__except;
52 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
53 : PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),
54 Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),
55 ColonIsSacred(false), InMessageExpression(false),
56 TemplateParameterDepth(0), ParsingInObjCContainer(false) {
57 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
58 Tok.startToken();
59 Tok.setKind(tok::eof);
60 Actions.CurScope = nullptr;
61 NumCachedScopes = 0;
62 CurParsedObjCImpl = nullptr;
64 // Add #pragma handlers. These are removed and destroyed in the
65 // destructor.
66 initializePragmaHandlers();
68 CommentSemaHandler.reset(new ActionCommentHandler(actions));
69 PP.addCommentHandler(CommentSemaHandler.get());
71 PP.setCodeCompletionHandler(*this);
74 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
75 return Diags.Report(Loc, DiagID);
78 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
79 return Diag(Tok.getLocation(), DiagID);
82 /// Emits a diagnostic suggesting parentheses surrounding a
83 /// given range.
84 ///
85 /// \param Loc The location where we'll emit the diagnostic.
86 /// \param DK The kind of diagnostic to emit.
87 /// \param ParenRange Source range enclosing code that should be parenthesized.
88 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
89 SourceRange ParenRange) {
90 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
91 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
92 // We can't display the parentheses, so just dig the
93 // warning/error and return.
94 Diag(Loc, DK);
95 return;
98 Diag(Loc, DK)
99 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
100 << FixItHint::CreateInsertion(EndLoc, ")");
103 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
104 switch (ExpectedTok) {
105 case tok::semi:
106 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
107 default: return false;
111 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
112 StringRef Msg) {
113 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
114 ConsumeAnyToken();
115 return false;
118 // Detect common single-character typos and resume.
119 if (IsCommonTypo(ExpectedTok, Tok)) {
120 SourceLocation Loc = Tok.getLocation();
122 DiagnosticBuilder DB = Diag(Loc, DiagID);
123 DB << FixItHint::CreateReplacement(
124 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
125 if (DiagID == diag::err_expected)
126 DB << ExpectedTok;
127 else if (DiagID == diag::err_expected_after)
128 DB << Msg << ExpectedTok;
129 else
130 DB << Msg;
133 // Pretend there wasn't a problem.
134 ConsumeAnyToken();
135 return false;
138 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
139 const char *Spelling = nullptr;
140 if (EndLoc.isValid())
141 Spelling = tok::getPunctuatorSpelling(ExpectedTok);
143 DiagnosticBuilder DB =
144 Spelling
145 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
146 : Diag(Tok, DiagID);
147 if (DiagID == diag::err_expected)
148 DB << ExpectedTok;
149 else if (DiagID == diag::err_expected_after)
150 DB << Msg << ExpectedTok;
151 else
152 DB << Msg;
154 return true;
157 bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {
158 if (TryConsumeToken(tok::semi))
159 return false;
161 if (Tok.is(tok::code_completion)) {
162 handleUnexpectedCodeCompletionToken();
163 return false;
166 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
167 NextToken().is(tok::semi)) {
168 Diag(Tok, diag::err_extraneous_token_before_semi)
169 << PP.getSpelling(Tok)
170 << FixItHint::CreateRemoval(Tok.getLocation());
171 ConsumeAnyToken(); // The ')' or ']'.
172 ConsumeToken(); // The ';'.
173 return false;
176 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
179 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {
180 if (!Tok.is(tok::semi)) return;
182 bool HadMultipleSemis = false;
183 SourceLocation StartLoc = Tok.getLocation();
184 SourceLocation EndLoc = Tok.getLocation();
185 ConsumeToken();
187 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
188 HadMultipleSemis = true;
189 EndLoc = Tok.getLocation();
190 ConsumeToken();
193 // C++11 allows extra semicolons at namespace scope, but not in any of the
194 // other contexts.
195 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
196 if (getLangOpts().CPlusPlus11)
197 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
198 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
199 else
200 Diag(StartLoc, diag::ext_extra_semi_cxx11)
201 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
202 return;
205 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
206 Diag(StartLoc, diag::ext_extra_semi)
207 << Kind << DeclSpec::getSpecifierName(TST,
208 Actions.getASTContext().getPrintingPolicy())
209 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
210 else
211 // A single semicolon is valid after a member function definition.
212 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
213 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
216 bool Parser::expectIdentifier() {
217 if (Tok.is(tok::identifier))
218 return false;
219 if (const auto *II = Tok.getIdentifierInfo()) {
220 if (II->isCPlusPlusKeyword(getLangOpts())) {
221 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
222 << tok::identifier << Tok.getIdentifierInfo();
223 // Objective-C++: Recover by treating this keyword as a valid identifier.
224 return false;
227 Diag(Tok, diag::err_expected) << tok::identifier;
228 return true;
231 void Parser::checkCompoundToken(SourceLocation FirstTokLoc,
232 tok::TokenKind FirstTokKind, CompoundToken Op) {
233 if (FirstTokLoc.isInvalid())
234 return;
235 SourceLocation SecondTokLoc = Tok.getLocation();
237 // If either token is in a macro, we expect both tokens to come from the same
238 // macro expansion.
239 if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&
240 PP.getSourceManager().getFileID(FirstTokLoc) !=
241 PP.getSourceManager().getFileID(SecondTokLoc)) {
242 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
243 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
244 << static_cast<int>(Op) << SourceRange(FirstTokLoc);
245 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
246 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
247 << SourceRange(SecondTokLoc);
248 return;
251 // We expect the tokens to abut.
252 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
253 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
254 if (SpaceLoc.isInvalid())
255 SpaceLoc = FirstTokLoc;
256 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
257 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
258 << static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
259 return;
263 //===----------------------------------------------------------------------===//
264 // Error recovery.
265 //===----------------------------------------------------------------------===//
267 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
268 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
271 /// SkipUntil - Read tokens until we get to the specified token, then consume
272 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
273 /// token will ever occur, this skips to the next token, or to some likely
274 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
275 /// character.
277 /// If SkipUntil finds the specified token, it returns true, otherwise it
278 /// returns false.
279 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
280 // We always want this function to skip at least one token if the first token
281 // isn't T and if not at EOF.
282 bool isFirstTokenSkipped = true;
283 while (true) {
284 // If we found one of the tokens, stop and return true.
285 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
286 if (Tok.is(Toks[i])) {
287 if (HasFlagsSet(Flags, StopBeforeMatch)) {
288 // Noop, don't consume the token.
289 } else {
290 ConsumeAnyToken();
292 return true;
296 // Important special case: The caller has given up and just wants us to
297 // skip the rest of the file. Do this without recursing, since we can
298 // get here precisely because the caller detected too much recursion.
299 if (Toks.size() == 1 && Toks[0] == tok::eof &&
300 !HasFlagsSet(Flags, StopAtSemi) &&
301 !HasFlagsSet(Flags, StopAtCodeCompletion)) {
302 while (Tok.isNot(tok::eof))
303 ConsumeAnyToken();
304 return true;
307 switch (Tok.getKind()) {
308 case tok::eof:
309 // Ran out of tokens.
310 return false;
312 case tok::annot_pragma_openmp:
313 case tok::annot_attr_openmp:
314 case tok::annot_pragma_openmp_end:
315 // Stop before an OpenMP pragma boundary.
316 if (OpenMPDirectiveParsing)
317 return false;
318 ConsumeAnnotationToken();
319 break;
320 case tok::annot_module_begin:
321 case tok::annot_module_end:
322 case tok::annot_module_include:
323 // Stop before we change submodules. They generally indicate a "good"
324 // place to pick up parsing again (except in the special case where
325 // we're trying to skip to EOF).
326 return false;
328 case tok::code_completion:
329 if (!HasFlagsSet(Flags, StopAtCodeCompletion))
330 handleUnexpectedCodeCompletionToken();
331 return false;
333 case tok::l_paren:
334 // Recursively skip properly-nested parens.
335 ConsumeParen();
336 if (HasFlagsSet(Flags, StopAtCodeCompletion))
337 SkipUntil(tok::r_paren, StopAtCodeCompletion);
338 else
339 SkipUntil(tok::r_paren);
340 break;
341 case tok::l_square:
342 // Recursively skip properly-nested square brackets.
343 ConsumeBracket();
344 if (HasFlagsSet(Flags, StopAtCodeCompletion))
345 SkipUntil(tok::r_square, StopAtCodeCompletion);
346 else
347 SkipUntil(tok::r_square);
348 break;
349 case tok::l_brace:
350 // Recursively skip properly-nested braces.
351 ConsumeBrace();
352 if (HasFlagsSet(Flags, StopAtCodeCompletion))
353 SkipUntil(tok::r_brace, StopAtCodeCompletion);
354 else
355 SkipUntil(tok::r_brace);
356 break;
357 case tok::question:
358 // Recursively skip ? ... : pairs; these function as brackets. But
359 // still stop at a semicolon if requested.
360 ConsumeToken();
361 SkipUntil(tok::colon,
362 SkipUntilFlags(unsigned(Flags) &
363 unsigned(StopAtCodeCompletion | StopAtSemi)));
364 break;
366 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
367 // Since the user wasn't looking for this token (if they were, it would
368 // already be handled), this isn't balanced. If there is a LHS token at a
369 // higher level, we will assume that this matches the unbalanced token
370 // and return it. Otherwise, this is a spurious RHS token, which we skip.
371 case tok::r_paren:
372 if (ParenCount && !isFirstTokenSkipped)
373 return false; // Matches something.
374 ConsumeParen();
375 break;
376 case tok::r_square:
377 if (BracketCount && !isFirstTokenSkipped)
378 return false; // Matches something.
379 ConsumeBracket();
380 break;
381 case tok::r_brace:
382 if (BraceCount && !isFirstTokenSkipped)
383 return false; // Matches something.
384 ConsumeBrace();
385 break;
387 case tok::semi:
388 if (HasFlagsSet(Flags, StopAtSemi))
389 return false;
390 [[fallthrough]];
391 default:
392 // Skip this token.
393 ConsumeAnyToken();
394 break;
396 isFirstTokenSkipped = false;
400 //===----------------------------------------------------------------------===//
401 // Scope manipulation
402 //===----------------------------------------------------------------------===//
404 /// EnterScope - Start a new scope.
405 void Parser::EnterScope(unsigned ScopeFlags) {
406 if (NumCachedScopes) {
407 Scope *N = ScopeCache[--NumCachedScopes];
408 N->Init(getCurScope(), ScopeFlags);
409 Actions.CurScope = N;
410 } else {
411 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
415 /// ExitScope - Pop a scope off the scope stack.
416 void Parser::ExitScope() {
417 assert(getCurScope() && "Scope imbalance!");
419 // Inform the actions module that this scope is going away if there are any
420 // decls in it.
421 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
423 Scope *OldScope = getCurScope();
424 Actions.CurScope = OldScope->getParent();
426 if (NumCachedScopes == ScopeCacheSize)
427 delete OldScope;
428 else
429 ScopeCache[NumCachedScopes++] = OldScope;
432 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
433 /// this object does nothing.
434 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
435 bool ManageFlags)
436 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
437 if (CurScope) {
438 OldFlags = CurScope->getFlags();
439 CurScope->setFlags(ScopeFlags);
443 /// Restore the flags for the current scope to what they were before this
444 /// object overrode them.
445 Parser::ParseScopeFlags::~ParseScopeFlags() {
446 if (CurScope)
447 CurScope->setFlags(OldFlags);
451 //===----------------------------------------------------------------------===//
452 // C99 6.9: External Definitions.
453 //===----------------------------------------------------------------------===//
455 Parser::~Parser() {
456 // If we still have scopes active, delete the scope tree.
457 delete getCurScope();
458 Actions.CurScope = nullptr;
460 // Free the scope cache.
461 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
462 delete ScopeCache[i];
464 resetPragmaHandlers();
466 PP.removeCommentHandler(CommentSemaHandler.get());
468 PP.clearCodeCompletionHandler();
470 DestroyTemplateIds();
473 /// Initialize - Warm up the parser.
475 void Parser::Initialize() {
476 // Create the translation unit scope. Install it as the current scope.
477 assert(getCurScope() == nullptr && "A scope is already active?");
478 EnterScope(Scope::DeclScope);
479 Actions.ActOnTranslationUnitScope(getCurScope());
481 // Initialization for Objective-C context sensitive keywords recognition.
482 // Referenced in Parser::ParseObjCTypeQualifierList.
483 if (getLangOpts().ObjC) {
484 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
485 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
486 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
487 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
488 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
489 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
490 ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
491 ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
492 ObjCTypeQuals[objc_null_unspecified]
493 = &PP.getIdentifierTable().get("null_unspecified");
496 Ident_instancetype = nullptr;
497 Ident_final = nullptr;
498 Ident_sealed = nullptr;
499 Ident_abstract = nullptr;
500 Ident_override = nullptr;
501 Ident_GNU_final = nullptr;
502 Ident_import = nullptr;
503 Ident_module = nullptr;
505 Ident_super = &PP.getIdentifierTable().get("super");
507 Ident_vector = nullptr;
508 Ident_bool = nullptr;
509 Ident_Bool = nullptr;
510 Ident_pixel = nullptr;
511 if (getLangOpts().AltiVec || getLangOpts().ZVector) {
512 Ident_vector = &PP.getIdentifierTable().get("vector");
513 Ident_bool = &PP.getIdentifierTable().get("bool");
514 Ident_Bool = &PP.getIdentifierTable().get("_Bool");
516 if (getLangOpts().AltiVec)
517 Ident_pixel = &PP.getIdentifierTable().get("pixel");
519 Ident_introduced = nullptr;
520 Ident_deprecated = nullptr;
521 Ident_obsoleted = nullptr;
522 Ident_unavailable = nullptr;
523 Ident_strict = nullptr;
524 Ident_replacement = nullptr;
526 Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr;
528 Ident__except = nullptr;
530 Ident__exception_code = Ident__exception_info = nullptr;
531 Ident__abnormal_termination = Ident___exception_code = nullptr;
532 Ident___exception_info = Ident___abnormal_termination = nullptr;
533 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
534 Ident_AbnormalTermination = nullptr;
536 if(getLangOpts().Borland) {
537 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
538 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
539 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
540 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
541 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
542 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
543 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
544 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
545 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
547 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
548 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
549 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
550 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
551 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
552 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
553 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
554 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
555 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
558 if (getLangOpts().CPlusPlusModules) {
559 Ident_import = PP.getIdentifierInfo("import");
560 Ident_module = PP.getIdentifierInfo("module");
563 Actions.Initialize();
565 // Prime the lexer look-ahead.
566 ConsumeToken();
569 void Parser::DestroyTemplateIds() {
570 for (TemplateIdAnnotation *Id : TemplateIds)
571 Id->Destroy();
572 TemplateIds.clear();
575 /// Parse the first top-level declaration in a translation unit.
577 /// translation-unit:
578 /// [C] external-declaration
579 /// [C] translation-unit external-declaration
580 /// [C++] top-level-declaration-seq[opt]
581 /// [C++20] global-module-fragment[opt] module-declaration
582 /// top-level-declaration-seq[opt] private-module-fragment[opt]
584 /// Note that in C, it is an error if there is no first declaration.
585 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result,
586 Sema::ModuleImportState &ImportState) {
587 Actions.ActOnStartOfTranslationUnit();
589 // For C++20 modules, a module decl must be the first in the TU. We also
590 // need to track module imports.
591 ImportState = Sema::ModuleImportState::FirstDecl;
592 bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);
594 // C11 6.9p1 says translation units must have at least one top-level
595 // declaration. C++ doesn't have this restriction. We also don't want to
596 // complain if we have a precompiled header, although technically if the PCH
597 // is empty we should still emit the (pedantic) diagnostic.
598 // If the main file is a header, we're only pretending it's a TU; don't warn.
599 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
600 !getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)
601 Diag(diag::ext_empty_translation_unit);
603 return NoTopLevelDecls;
606 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
607 /// action tells us to. This returns true if the EOF was encountered.
609 /// top-level-declaration:
610 /// declaration
611 /// [C++20] module-import-declaration
612 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,
613 Sema::ModuleImportState &ImportState) {
614 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
616 // Skip over the EOF token, flagging end of previous input for incremental
617 // processing
618 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
619 ConsumeToken();
621 Result = nullptr;
622 switch (Tok.getKind()) {
623 case tok::annot_pragma_unused:
624 HandlePragmaUnused();
625 return false;
627 case tok::kw_export:
628 switch (NextToken().getKind()) {
629 case tok::kw_module:
630 goto module_decl;
632 // Note: no need to handle kw_import here. We only form kw_import under
633 // the Modules TS, and in that case 'export import' is parsed as an
634 // export-declaration containing an import-declaration.
636 // Recognize context-sensitive C++20 'export module' and 'export import'
637 // declarations.
638 case tok::identifier: {
639 IdentifierInfo *II = NextToken().getIdentifierInfo();
640 if ((II == Ident_module || II == Ident_import) &&
641 GetLookAheadToken(2).isNot(tok::coloncolon)) {
642 if (II == Ident_module)
643 goto module_decl;
644 else
645 goto import_decl;
647 break;
650 default:
651 break;
653 break;
655 case tok::kw_module:
656 module_decl:
657 Result = ParseModuleDecl(ImportState);
658 return false;
660 case tok::kw_import:
661 import_decl: {
662 Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);
663 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
664 return false;
667 case tok::annot_module_include: {
668 auto Loc = Tok.getLocation();
669 Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());
670 // FIXME: We need a better way to disambiguate C++ clang modules and
671 // standard C++ modules.
672 if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())
673 Actions.ActOnModuleInclude(Loc, Mod);
674 else {
675 DeclResult Import =
676 Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);
677 Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();
678 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
680 ConsumeAnnotationToken();
681 return false;
684 case tok::annot_module_begin:
685 Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
686 Tok.getAnnotationValue()));
687 ConsumeAnnotationToken();
688 ImportState = Sema::ModuleImportState::NotACXX20Module;
689 return false;
691 case tok::annot_module_end:
692 Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
693 Tok.getAnnotationValue()));
694 ConsumeAnnotationToken();
695 ImportState = Sema::ModuleImportState::NotACXX20Module;
696 return false;
698 case tok::eof:
699 // Check whether -fmax-tokens= was reached.
700 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
701 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
702 << PP.getTokenCount() << PP.getMaxTokens();
703 SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();
704 if (OverrideLoc.isValid()) {
705 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
709 // Late template parsing can begin.
710 Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);
711 Actions.ActOnEndOfTranslationUnit();
712 //else don't tell Sema that we ended parsing: more input might come.
713 return true;
715 case tok::identifier:
716 // C++2a [basic.link]p3:
717 // A token sequence beginning with 'export[opt] module' or
718 // 'export[opt] import' and not immediately followed by '::'
719 // is never interpreted as the declaration of a top-level-declaration.
720 if ((Tok.getIdentifierInfo() == Ident_module ||
721 Tok.getIdentifierInfo() == Ident_import) &&
722 NextToken().isNot(tok::coloncolon)) {
723 if (Tok.getIdentifierInfo() == Ident_module)
724 goto module_decl;
725 else
726 goto import_decl;
728 break;
730 default:
731 break;
734 ParsedAttributes DeclAttrs(AttrFactory);
735 ParsedAttributes DeclSpecAttrs(AttrFactory);
736 // GNU attributes are applied to the declaration specification while the
737 // standard attributes are applied to the declaration. We parse the two
738 // attribute sets into different containters so we can apply them during
739 // the regular parsing process.
740 while (MaybeParseCXX11Attributes(DeclAttrs) ||
741 MaybeParseGNUAttributes(DeclSpecAttrs))
744 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
745 // An empty Result might mean a line with ';' or some parsing error, ignore
746 // it.
747 if (Result) {
748 if (ImportState == Sema::ModuleImportState::FirstDecl)
749 // First decl was not modular.
750 ImportState = Sema::ModuleImportState::NotACXX20Module;
751 else if (ImportState == Sema::ModuleImportState::ImportAllowed)
752 // Non-imports disallow further imports.
753 ImportState = Sema::ModuleImportState::ImportFinished;
754 else if (ImportState ==
755 Sema::ModuleImportState::PrivateFragmentImportAllowed)
756 // Non-imports disallow further imports.
757 ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;
759 return false;
762 /// ParseExternalDeclaration:
764 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
765 /// declaration.
767 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
768 /// function-definition
769 /// declaration
770 /// [GNU] asm-definition
771 /// [GNU] __extension__ external-declaration
772 /// [OBJC] objc-class-definition
773 /// [OBJC] objc-class-declaration
774 /// [OBJC] objc-alias-declaration
775 /// [OBJC] objc-protocol-definition
776 /// [OBJC] objc-method-definition
777 /// [OBJC] @end
778 /// [C++] linkage-specification
779 /// [GNU] asm-definition:
780 /// simple-asm-expr ';'
781 /// [C++11] empty-declaration
782 /// [C++11] attribute-declaration
784 /// [C++11] empty-declaration:
785 /// ';'
787 /// [C++0x/GNU] 'extern' 'template' declaration
789 /// [Modules-TS] module-import-declaration
791 Parser::DeclGroupPtrTy
792 Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
793 ParsedAttributes &DeclSpecAttrs,
794 ParsingDeclSpec *DS) {
795 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
796 ParenBraceBracketBalancer BalancerRAIIObj(*this);
798 if (PP.isCodeCompletionReached()) {
799 cutOffParsing();
800 return nullptr;
803 Decl *SingleDecl = nullptr;
804 switch (Tok.getKind()) {
805 case tok::annot_pragma_vis:
806 HandlePragmaVisibility();
807 return nullptr;
808 case tok::annot_pragma_pack:
809 HandlePragmaPack();
810 return nullptr;
811 case tok::annot_pragma_msstruct:
812 HandlePragmaMSStruct();
813 return nullptr;
814 case tok::annot_pragma_align:
815 HandlePragmaAlign();
816 return nullptr;
817 case tok::annot_pragma_weak:
818 HandlePragmaWeak();
819 return nullptr;
820 case tok::annot_pragma_weakalias:
821 HandlePragmaWeakAlias();
822 return nullptr;
823 case tok::annot_pragma_redefine_extname:
824 HandlePragmaRedefineExtname();
825 return nullptr;
826 case tok::annot_pragma_fp_contract:
827 HandlePragmaFPContract();
828 return nullptr;
829 case tok::annot_pragma_fenv_access:
830 case tok::annot_pragma_fenv_access_ms:
831 HandlePragmaFEnvAccess();
832 return nullptr;
833 case tok::annot_pragma_fenv_round:
834 HandlePragmaFEnvRound();
835 return nullptr;
836 case tok::annot_pragma_float_control:
837 HandlePragmaFloatControl();
838 return nullptr;
839 case tok::annot_pragma_fp:
840 HandlePragmaFP();
841 break;
842 case tok::annot_pragma_opencl_extension:
843 HandlePragmaOpenCLExtension();
844 return nullptr;
845 case tok::annot_attr_openmp:
846 case tok::annot_pragma_openmp: {
847 AccessSpecifier AS = AS_none;
848 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
850 case tok::annot_pragma_ms_pointers_to_members:
851 HandlePragmaMSPointersToMembers();
852 return nullptr;
853 case tok::annot_pragma_ms_vtordisp:
854 HandlePragmaMSVtorDisp();
855 return nullptr;
856 case tok::annot_pragma_ms_pragma:
857 HandlePragmaMSPragma();
858 return nullptr;
859 case tok::annot_pragma_dump:
860 HandlePragmaDump();
861 return nullptr;
862 case tok::annot_pragma_attribute:
863 HandlePragmaAttribute();
864 return nullptr;
865 case tok::semi:
866 // Either a C++11 empty-declaration or attribute-declaration.
867 SingleDecl =
868 Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());
869 ConsumeExtraSemi(OutsideFunction);
870 break;
871 case tok::r_brace:
872 Diag(Tok, diag::err_extraneous_closing_brace);
873 ConsumeBrace();
874 return nullptr;
875 case tok::eof:
876 Diag(Tok, diag::err_expected_external_declaration);
877 return nullptr;
878 case tok::kw___extension__: {
879 // __extension__ silences extension warnings in the subexpression.
880 ExtensionRAIIObject O(Diags); // Use RAII to do this.
881 ConsumeToken();
882 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
884 case tok::kw_asm: {
885 ProhibitAttributes(Attrs);
887 SourceLocation StartLoc = Tok.getLocation();
888 SourceLocation EndLoc;
890 ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));
892 // Check if GNU-style InlineAsm is disabled.
893 // Empty asm string is allowed because it will not introduce
894 // any assembly code.
895 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
896 const auto *SL = cast<StringLiteral>(Result.get());
897 if (!SL->getString().trim().empty())
898 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
901 ExpectAndConsume(tok::semi, diag::err_expected_after,
902 "top-level asm block");
904 if (Result.isInvalid())
905 return nullptr;
906 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
907 break;
909 case tok::at:
910 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
911 case tok::minus:
912 case tok::plus:
913 if (!getLangOpts().ObjC) {
914 Diag(Tok, diag::err_expected_external_declaration);
915 ConsumeToken();
916 return nullptr;
918 SingleDecl = ParseObjCMethodDefinition();
919 break;
920 case tok::code_completion:
921 cutOffParsing();
922 if (CurParsedObjCImpl) {
923 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
924 Actions.CodeCompleteObjCMethodDecl(getCurScope(),
925 /*IsInstanceMethod=*/std::nullopt,
926 /*ReturnType=*/nullptr);
928 Actions.CodeCompleteOrdinaryName(
929 getCurScope(),
930 CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
931 return nullptr;
932 case tok::kw_import: {
933 Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;
934 if (getLangOpts().CPlusPlusModules) {
935 llvm_unreachable("not expecting a c++20 import here");
936 ProhibitAttributes(Attrs);
938 SingleDecl = ParseModuleImport(SourceLocation(), IS);
939 } break;
940 case tok::kw_export:
941 if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
942 ProhibitAttributes(Attrs);
943 SingleDecl = ParseExportDeclaration();
944 break;
946 // This must be 'export template'. Parse it so we can diagnose our lack
947 // of support.
948 [[fallthrough]];
949 case tok::kw_using:
950 case tok::kw_namespace:
951 case tok::kw_typedef:
952 case tok::kw_template:
953 case tok::kw_static_assert:
954 case tok::kw__Static_assert:
955 // A function definition cannot start with any of these keywords.
957 SourceLocation DeclEnd;
958 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
959 DeclSpecAttrs);
962 case tok::kw_cbuffer:
963 case tok::kw_tbuffer:
964 if (getLangOpts().HLSL) {
965 SourceLocation DeclEnd;
966 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
967 DeclSpecAttrs);
969 goto dont_know;
971 case tok::kw_static:
972 // Parse (then ignore) 'static' prior to a template instantiation. This is
973 // a GCC extension that we intentionally do not support.
974 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
975 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
976 << 0;
977 SourceLocation DeclEnd;
978 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
979 DeclSpecAttrs);
981 goto dont_know;
983 case tok::kw_inline:
984 if (getLangOpts().CPlusPlus) {
985 tok::TokenKind NextKind = NextToken().getKind();
987 // Inline namespaces. Allowed as an extension even in C++03.
988 if (NextKind == tok::kw_namespace) {
989 SourceLocation DeclEnd;
990 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
991 DeclSpecAttrs);
994 // Parse (then ignore) 'inline' prior to a template instantiation. This is
995 // a GCC extension that we intentionally do not support.
996 if (NextKind == tok::kw_template) {
997 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
998 << 1;
999 SourceLocation DeclEnd;
1000 return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,
1001 DeclSpecAttrs);
1004 goto dont_know;
1006 case tok::kw_extern:
1007 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
1008 // Extern templates
1009 SourceLocation ExternLoc = ConsumeToken();
1010 SourceLocation TemplateLoc = ConsumeToken();
1011 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
1012 diag::warn_cxx98_compat_extern_template :
1013 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1014 SourceLocation DeclEnd;
1015 return Actions.ConvertDeclToDeclGroup(ParseExplicitInstantiation(
1016 DeclaratorContext::File, ExternLoc, TemplateLoc, DeclEnd, Attrs));
1018 goto dont_know;
1020 case tok::kw___if_exists:
1021 case tok::kw___if_not_exists:
1022 ParseMicrosoftIfExistsExternalDeclaration();
1023 return nullptr;
1025 case tok::kw_module:
1026 Diag(Tok, diag::err_unexpected_module_decl);
1027 SkipUntil(tok::semi);
1028 return nullptr;
1030 default:
1031 dont_know:
1032 if (Tok.isEditorPlaceholder()) {
1033 ConsumeToken();
1034 return nullptr;
1036 if (PP.isIncrementalProcessingEnabled() &&
1037 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1038 return ParseTopLevelStmtDecl();
1040 // We can't tell whether this is a function-definition or declaration yet.
1041 if (!SingleDecl)
1042 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1045 // This routine returns a DeclGroup, if the thing we parsed only contains a
1046 // single decl, convert it now.
1047 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1050 /// Determine whether the current token, if it occurs after a
1051 /// declarator, continues a declaration or declaration list.
1052 bool Parser::isDeclarationAfterDeclarator() {
1053 // Check for '= delete' or '= default'
1054 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1055 const Token &KW = NextToken();
1056 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
1057 return false;
1060 return Tok.is(tok::equal) || // int X()= -> not a function def
1061 Tok.is(tok::comma) || // int X(), -> not a function def
1062 Tok.is(tok::semi) || // int X(); -> not a function def
1063 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
1064 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
1065 (getLangOpts().CPlusPlus &&
1066 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
1069 /// Determine whether the current token, if it occurs after a
1070 /// declarator, indicates the start of a function definition.
1071 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
1072 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
1073 if (Tok.is(tok::l_brace)) // int X() {}
1074 return true;
1076 // Handle K&R C argument lists: int X(f) int f; {}
1077 if (!getLangOpts().CPlusPlus &&
1078 Declarator.getFunctionTypeInfo().isKNRPrototype())
1079 return isDeclarationSpecifier(ImplicitTypenameContext::No);
1081 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
1082 const Token &KW = NextToken();
1083 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
1086 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
1087 Tok.is(tok::kw_try); // X() try { ... }
1090 /// Parse either a function-definition or a declaration. We can't tell which
1091 /// we have until we read up to the compound-statement in function-definition.
1092 /// TemplateParams, if non-NULL, provides the template parameters when we're
1093 /// parsing a C++ template-declaration.
1095 /// function-definition: [C99 6.9.1]
1096 /// decl-specs declarator declaration-list[opt] compound-statement
1097 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1098 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1100 /// declaration: [C99 6.7]
1101 /// declaration-specifiers init-declarator-list[opt] ';'
1102 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1103 /// [OMP] threadprivate-directive
1104 /// [OMP] allocate-directive [TODO]
1106 Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(
1107 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1108 ParsingDeclSpec &DS, AccessSpecifier AS) {
1109 // Because we assume that the DeclSpec has not yet been initialised, we simply
1110 // overwrite the source range and attribute the provided leading declspec
1111 // attributes.
1112 assert(DS.getSourceRange().isInvalid() &&
1113 "expected uninitialised source range");
1114 DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());
1115 DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());
1116 DS.takeAttributesFrom(DeclSpecAttrs);
1118 MaybeParseMicrosoftAttributes(DS.getAttributes());
1119 // Parse the common declaration-specifiers piece.
1120 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1121 DeclSpecContext::DSC_top_level);
1123 // If we had a free-standing type definition with a missing semicolon, we
1124 // may get this far before the problem becomes obvious.
1125 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1126 DS, AS, DeclSpecContext::DSC_top_level))
1127 return nullptr;
1129 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1130 // declaration-specifiers init-declarator-list[opt] ';'
1131 if (Tok.is(tok::semi)) {
1132 auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1133 assert(DeclSpec::isDeclRep(TKind));
1134 switch(TKind) {
1135 case DeclSpec::TST_class:
1136 return 5;
1137 case DeclSpec::TST_struct:
1138 return 6;
1139 case DeclSpec::TST_union:
1140 return 5;
1141 case DeclSpec::TST_enum:
1142 return 4;
1143 case DeclSpec::TST_interface:
1144 return 9;
1145 default:
1146 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1150 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1151 SourceLocation CorrectLocationForAttributes =
1152 DeclSpec::isDeclRep(DS.getTypeSpecType())
1153 ? DS.getTypeSpecTypeLoc().getLocWithOffset(
1154 LengthOfTSTToken(DS.getTypeSpecType()))
1155 : SourceLocation();
1156 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1157 ConsumeToken();
1158 RecordDecl *AnonRecord = nullptr;
1159 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1160 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1161 DS.complete(TheDecl);
1162 if (AnonRecord) {
1163 Decl* decls[] = {AnonRecord, TheDecl};
1164 return Actions.BuildDeclaratorGroup(decls);
1166 return Actions.ConvertDeclToDeclGroup(TheDecl);
1169 // ObjC2 allows prefix attributes on class interfaces and protocols.
1170 // FIXME: This still needs better diagnostics. We should only accept
1171 // attributes here, no types, etc.
1172 if (getLangOpts().ObjC && Tok.is(tok::at)) {
1173 SourceLocation AtLoc = ConsumeToken(); // the "@"
1174 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1175 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1176 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1177 Diag(Tok, diag::err_objc_unexpected_attr);
1178 SkipUntil(tok::semi);
1179 return nullptr;
1182 DS.abort();
1183 DS.takeAttributesFrom(Attrs);
1185 const char *PrevSpec = nullptr;
1186 unsigned DiagID;
1187 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1188 Actions.getASTContext().getPrintingPolicy()))
1189 Diag(AtLoc, DiagID) << PrevSpec;
1191 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1192 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1194 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1195 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1197 return Actions.ConvertDeclToDeclGroup(
1198 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1201 // If the declspec consisted only of 'extern' and we have a string
1202 // literal following it, this must be a C++ linkage specifier like
1203 // 'extern "C"'.
1204 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1205 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1206 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1207 ProhibitAttributes(Attrs);
1208 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);
1209 return Actions.ConvertDeclToDeclGroup(TheDecl);
1212 return ParseDeclGroup(DS, DeclaratorContext::File, Attrs);
1215 Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(
1216 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1217 ParsingDeclSpec *DS, AccessSpecifier AS) {
1218 if (DS) {
1219 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1220 } else {
1221 ParsingDeclSpec PDS(*this);
1222 // Must temporarily exit the objective-c container scope for
1223 // parsing c constructs and re-enter objc container scope
1224 // afterwards.
1225 ObjCDeclContextSwitch ObjCDC(*this);
1227 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1231 /// ParseFunctionDefinition - We parsed and verified that the specified
1232 /// Declarator is well formed. If this is a K&R-style function, read the
1233 /// parameters declaration-list, then start the compound-statement.
1235 /// function-definition: [C99 6.9.1]
1236 /// decl-specs declarator declaration-list[opt] compound-statement
1237 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1238 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1239 /// [C++] function-definition: [C++ 8.4]
1240 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1241 /// function-body
1242 /// [C++] function-definition: [C++ 8.4]
1243 /// decl-specifier-seq[opt] declarator function-try-block
1245 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1246 const ParsedTemplateInfo &TemplateInfo,
1247 LateParsedAttrList *LateParsedAttrs) {
1248 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1249 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1250 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1251 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1253 // If this is C89 and the declspecs were completely missing, fudge in an
1254 // implicit int. We do this here because this is the only place where
1255 // declaration-specifiers are completely optional in the grammar.
1256 if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {
1257 Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)
1258 << D.getDeclSpec().getSourceRange();
1259 const char *PrevSpec;
1260 unsigned DiagID;
1261 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1262 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1263 D.getIdentifierLoc(),
1264 PrevSpec, DiagID,
1265 Policy);
1266 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1269 // If this declaration was formed with a K&R-style identifier list for the
1270 // arguments, parse declarations for all of the args next.
1271 // int foo(a,b) int a; float b; {}
1272 if (FTI.isKNRPrototype())
1273 ParseKNRParamDeclarations(D);
1275 // We should have either an opening brace or, in a C++ constructor,
1276 // we may have a colon.
1277 if (Tok.isNot(tok::l_brace) &&
1278 (!getLangOpts().CPlusPlus ||
1279 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1280 Tok.isNot(tok::equal)))) {
1281 Diag(Tok, diag::err_expected_fn_body);
1283 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1284 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1286 // If we didn't find the '{', bail out.
1287 if (Tok.isNot(tok::l_brace))
1288 return nullptr;
1291 // Check to make sure that any normal attributes are allowed to be on
1292 // a definition. Late parsed attributes are checked at the end.
1293 if (Tok.isNot(tok::equal)) {
1294 for (const ParsedAttr &AL : D.getAttributes())
1295 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1296 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1299 // In delayed template parsing mode, for function template we consume the
1300 // tokens and store them for late parsing at the end of the translation unit.
1301 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1302 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1303 Actions.canDelayFunctionBody(D)) {
1304 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1306 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1307 Scope::CompoundStmtScope);
1308 Scope *ParentScope = getCurScope()->getParent();
1310 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1311 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1312 TemplateParameterLists);
1313 D.complete(DP);
1314 D.getMutableDeclSpec().abort();
1316 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1317 trySkippingFunctionBody()) {
1318 BodyScope.Exit();
1319 return Actions.ActOnSkippedFunctionBody(DP);
1322 CachedTokens Toks;
1323 LexTemplateFunctionForLateParsing(Toks);
1325 if (DP) {
1326 FunctionDecl *FnD = DP->getAsFunction();
1327 Actions.CheckForFunctionRedefinition(FnD);
1328 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1330 return DP;
1332 else if (CurParsedObjCImpl &&
1333 !TemplateInfo.TemplateParams &&
1334 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1335 Tok.is(tok::colon)) &&
1336 Actions.CurContext->isTranslationUnit()) {
1337 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1338 Scope::CompoundStmtScope);
1339 Scope *ParentScope = getCurScope()->getParent();
1341 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
1342 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1343 MultiTemplateParamsArg());
1344 D.complete(FuncDecl);
1345 D.getMutableDeclSpec().abort();
1346 if (FuncDecl) {
1347 // Consume the tokens and store them for later parsing.
1348 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1349 CurParsedObjCImpl->HasCFunction = true;
1350 return FuncDecl;
1352 // FIXME: Should we really fall through here?
1355 // Enter a scope for the function body.
1356 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1357 Scope::CompoundStmtScope);
1359 // Parse function body eagerly if it is either '= delete;' or '= default;' as
1360 // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1361 Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;
1362 SourceLocation KWLoc;
1363 if (TryConsumeToken(tok::equal)) {
1364 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1366 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1367 Diag(KWLoc, getLangOpts().CPlusPlus11
1368 ? diag::warn_cxx98_compat_defaulted_deleted_function
1369 : diag::ext_defaulted_deleted_function)
1370 << 1 /* deleted */;
1371 BodyKind = Sema::FnBodyKind::Delete;
1372 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1373 Diag(KWLoc, getLangOpts().CPlusPlus11
1374 ? diag::warn_cxx98_compat_defaulted_deleted_function
1375 : diag::ext_defaulted_deleted_function)
1376 << 0 /* defaulted */;
1377 BodyKind = Sema::FnBodyKind::Default;
1378 } else {
1379 llvm_unreachable("function definition after = not 'delete' or 'default'");
1382 if (Tok.is(tok::comma)) {
1383 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1384 << (BodyKind == Sema::FnBodyKind::Delete);
1385 SkipUntil(tok::semi);
1386 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1387 BodyKind == Sema::FnBodyKind::Delete
1388 ? "delete"
1389 : "default")) {
1390 SkipUntil(tok::semi);
1394 // Tell the actions module that we have entered a function definition with the
1395 // specified Declarator for the function.
1396 Sema::SkipBodyInfo SkipBody;
1397 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1398 TemplateInfo.TemplateParams
1399 ? *TemplateInfo.TemplateParams
1400 : MultiTemplateParamsArg(),
1401 &SkipBody, BodyKind);
1403 if (SkipBody.ShouldSkip) {
1404 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1405 if (BodyKind == Sema::FnBodyKind::Other)
1406 SkipFunctionBody();
1408 // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1409 // and it would be popped in ActOnFinishFunctionBody.
1410 // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1412 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1413 // one is already popped when finishing the lambda in BuildLambdaExpr().
1415 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1416 // and PopExpressionEvaluationContext().
1417 if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))
1418 Actions.PopExpressionEvaluationContext();
1419 return Res;
1422 // Break out of the ParsingDeclarator context before we parse the body.
1423 D.complete(Res);
1425 // Break out of the ParsingDeclSpec context, too. This const_cast is
1426 // safe because we're always the sole owner.
1427 D.getMutableDeclSpec().abort();
1429 if (BodyKind != Sema::FnBodyKind::Other) {
1430 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind);
1431 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1432 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1433 return Res;
1436 // With abbreviated function templates - we need to explicitly add depth to
1437 // account for the implicit template parameter list induced by the template.
1438 if (auto *Template = dyn_cast_or_null<FunctionTemplateDecl>(Res))
1439 if (Template->isAbbreviated() &&
1440 Template->getTemplateParameters()->getParam(0)->isImplicit())
1441 // First template parameter is implicit - meaning no explicit template
1442 // parameter list was specified.
1443 CurTemplateDepthTracker.addDepth(1);
1445 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1446 trySkippingFunctionBody()) {
1447 BodyScope.Exit();
1448 Actions.ActOnSkippedFunctionBody(Res);
1449 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1452 if (Tok.is(tok::kw_try))
1453 return ParseFunctionTryBlock(Res, BodyScope);
1455 // If we have a colon, then we're probably parsing a C++
1456 // ctor-initializer.
1457 if (Tok.is(tok::colon)) {
1458 ParseConstructorInitializer(Res);
1460 // Recover from error.
1461 if (!Tok.is(tok::l_brace)) {
1462 BodyScope.Exit();
1463 Actions.ActOnFinishFunctionBody(Res, nullptr);
1464 return Res;
1466 } else
1467 Actions.ActOnDefaultCtorInitializers(Res);
1469 // Late attributes are parsed in the same scope as the function body.
1470 if (LateParsedAttrs)
1471 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1473 return ParseFunctionStatementBody(Res, BodyScope);
1476 void Parser::SkipFunctionBody() {
1477 if (Tok.is(tok::equal)) {
1478 SkipUntil(tok::semi);
1479 return;
1482 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1483 if (IsFunctionTryBlock)
1484 ConsumeToken();
1486 CachedTokens Skipped;
1487 if (ConsumeAndStoreFunctionPrologue(Skipped))
1488 SkipMalformedDecl();
1489 else {
1490 SkipUntil(tok::r_brace);
1491 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1492 SkipUntil(tok::l_brace);
1493 SkipUntil(tok::r_brace);
1498 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1499 /// types for a function with a K&R-style identifier list for arguments.
1500 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1501 // We know that the top-level of this declarator is a function.
1502 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1504 // Enter function-declaration scope, limiting any declarators to the
1505 // function prototype scope, including parameter declarators.
1506 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1507 Scope::FunctionDeclarationScope | Scope::DeclScope);
1509 // Read all the argument declarations.
1510 while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
1511 SourceLocation DSStart = Tok.getLocation();
1513 // Parse the common declaration-specifiers piece.
1514 DeclSpec DS(AttrFactory);
1515 ParseDeclarationSpecifiers(DS);
1517 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1518 // least one declarator'.
1519 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1520 // the declarations though. It's trivial to ignore them, really hard to do
1521 // anything else with them.
1522 if (TryConsumeToken(tok::semi)) {
1523 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1524 continue;
1527 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1528 // than register.
1529 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1530 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1531 Diag(DS.getStorageClassSpecLoc(),
1532 diag::err_invalid_storage_class_in_func_decl);
1533 DS.ClearStorageClassSpecs();
1535 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1536 Diag(DS.getThreadStorageClassSpecLoc(),
1537 diag::err_invalid_storage_class_in_func_decl);
1538 DS.ClearStorageClassSpecs();
1541 // Parse the first declarator attached to this declspec.
1542 Declarator ParmDeclarator(DS, ParsedAttributesView::none(),
1543 DeclaratorContext::KNRTypeList);
1544 ParseDeclarator(ParmDeclarator);
1546 // Handle the full declarator list.
1547 while (true) {
1548 // If attributes are present, parse them.
1549 MaybeParseGNUAttributes(ParmDeclarator);
1551 // Ask the actions module to compute the type for this declarator.
1552 Decl *Param =
1553 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1555 if (Param &&
1556 // A missing identifier has already been diagnosed.
1557 ParmDeclarator.getIdentifier()) {
1559 // Scan the argument list looking for the correct param to apply this
1560 // type.
1561 for (unsigned i = 0; ; ++i) {
1562 // C99 6.9.1p6: those declarators shall declare only identifiers from
1563 // the identifier list.
1564 if (i == FTI.NumParams) {
1565 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1566 << ParmDeclarator.getIdentifier();
1567 break;
1570 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1571 // Reject redefinitions of parameters.
1572 if (FTI.Params[i].Param) {
1573 Diag(ParmDeclarator.getIdentifierLoc(),
1574 diag::err_param_redefinition)
1575 << ParmDeclarator.getIdentifier();
1576 } else {
1577 FTI.Params[i].Param = Param;
1579 break;
1584 // If we don't have a comma, it is either the end of the list (a ';') or
1585 // an error, bail out.
1586 if (Tok.isNot(tok::comma))
1587 break;
1589 ParmDeclarator.clear();
1591 // Consume the comma.
1592 ParmDeclarator.setCommaLoc(ConsumeToken());
1594 // Parse the next declarator.
1595 ParseDeclarator(ParmDeclarator);
1598 // Consume ';' and continue parsing.
1599 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1600 continue;
1602 // Otherwise recover by skipping to next semi or mandatory function body.
1603 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1604 break;
1605 TryConsumeToken(tok::semi);
1608 // The actions module must verify that all arguments were declared.
1609 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1613 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1614 /// allowed to be a wide string, and is not subject to character translation.
1615 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1616 /// asm label as opposed to an asm statement, because such a construct does not
1617 /// behave well.
1619 /// [GNU] asm-string-literal:
1620 /// string-literal
1622 ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {
1623 if (!isTokenStringLiteral()) {
1624 Diag(Tok, diag::err_expected_string_literal)
1625 << /*Source='in...'*/0 << "'asm'";
1626 return ExprError();
1629 ExprResult AsmString(ParseStringLiteralExpression());
1630 if (!AsmString.isInvalid()) {
1631 const auto *SL = cast<StringLiteral>(AsmString.get());
1632 if (!SL->isOrdinary()) {
1633 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1634 << SL->isWide()
1635 << SL->getSourceRange();
1636 return ExprError();
1638 if (ForAsmLabel && SL->getString().empty()) {
1639 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1640 << 2 /* an empty */ << SL->getSourceRange();
1641 return ExprError();
1644 return AsmString;
1647 /// ParseSimpleAsm
1649 /// [GNU] simple-asm-expr:
1650 /// 'asm' '(' asm-string-literal ')'
1652 ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {
1653 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1654 SourceLocation Loc = ConsumeToken();
1656 if (isGNUAsmQualifier(Tok)) {
1657 // Remove from the end of 'asm' to the end of the asm qualifier.
1658 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1659 PP.getLocForEndOfToken(Tok.getLocation()));
1660 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1661 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1662 << FixItHint::CreateRemoval(RemovalRange);
1663 ConsumeToken();
1666 BalancedDelimiterTracker T(*this, tok::l_paren);
1667 if (T.consumeOpen()) {
1668 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1669 return ExprError();
1672 ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));
1674 if (!Result.isInvalid()) {
1675 // Close the paren and get the location of the end bracket
1676 T.consumeClose();
1677 if (EndLoc)
1678 *EndLoc = T.getCloseLocation();
1679 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1680 if (EndLoc)
1681 *EndLoc = Tok.getLocation();
1682 ConsumeParen();
1685 return Result;
1688 /// Get the TemplateIdAnnotation from the token and put it in the
1689 /// cleanup pool so that it gets destroyed when parsing the current top level
1690 /// declaration is finished.
1691 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1692 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1693 TemplateIdAnnotation *
1694 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1695 return Id;
1698 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1699 // Push the current token back into the token stream (or revert it if it is
1700 // cached) and use an annotation scope token for current token.
1701 if (PP.isBacktrackEnabled())
1702 PP.RevertCachedTokens(1);
1703 else
1704 PP.EnterToken(Tok, /*IsReinject=*/true);
1705 Tok.setKind(tok::annot_cxxscope);
1706 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1707 Tok.setAnnotationRange(SS.getRange());
1709 // In case the tokens were cached, have Preprocessor replace them
1710 // with the annotation token. We don't need to do this if we've
1711 // just reverted back to a prior state.
1712 if (IsNewAnnotation)
1713 PP.AnnotateCachedTokens(Tok);
1716 /// Attempt to classify the name at the current token position. This may
1717 /// form a type, scope or primary expression annotation, or replace the token
1718 /// with a typo-corrected keyword. This is only appropriate when the current
1719 /// name must refer to an entity which has already been declared.
1721 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1722 /// no typo correction will be performed.
1723 /// \param AllowImplicitTypename Whether we are in a context where a dependent
1724 /// nested-name-specifier without typename is treated as a type (e.g.
1725 /// T::type).
1726 Parser::AnnotatedNameKind
1727 Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1728 ImplicitTypenameContext AllowImplicitTypename) {
1729 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1731 const bool EnteringContext = false;
1732 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1734 CXXScopeSpec SS;
1735 if (getLangOpts().CPlusPlus &&
1736 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1737 /*ObjectHasErrors=*/false,
1738 EnteringContext))
1739 return ANK_Error;
1741 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1742 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1743 AllowImplicitTypename))
1744 return ANK_Error;
1745 return ANK_Unresolved;
1748 IdentifierInfo *Name = Tok.getIdentifierInfo();
1749 SourceLocation NameLoc = Tok.getLocation();
1751 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1752 // typo-correct to tentatively-declared identifiers.
1753 if (isTentativelyDeclared(Name) && SS.isEmpty()) {
1754 // Identifier has been tentatively declared, and thus cannot be resolved as
1755 // an expression. Fall back to annotating it as a type.
1756 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
1757 AllowImplicitTypename))
1758 return ANK_Error;
1759 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1762 Token Next = NextToken();
1764 // Look up and classify the identifier. We don't perform any typo-correction
1765 // after a scope specifier, because in general we can't recover from typos
1766 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1767 // jump back into scope specifier parsing).
1768 Sema::NameClassification Classification = Actions.ClassifyName(
1769 getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);
1771 // If name lookup found nothing and we guessed that this was a template name,
1772 // double-check before committing to that interpretation. C++20 requires that
1773 // we interpret this as a template-id if it can be, but if it can't be, then
1774 // this is an error recovery case.
1775 if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1776 isTemplateArgumentList(1) == TPResult::False) {
1777 // It's not a template-id; re-classify without the '<' as a hint.
1778 Token FakeNext = Next;
1779 FakeNext.setKind(tok::unknown);
1780 Classification =
1781 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1782 SS.isEmpty() ? CCC : nullptr);
1785 switch (Classification.getKind()) {
1786 case Sema::NC_Error:
1787 return ANK_Error;
1789 case Sema::NC_Keyword:
1790 // The identifier was typo-corrected to a keyword.
1791 Tok.setIdentifierInfo(Name);
1792 Tok.setKind(Name->getTokenID());
1793 PP.TypoCorrectToken(Tok);
1794 if (SS.isNotEmpty())
1795 AnnotateScopeToken(SS, !WasScopeAnnotation);
1796 // We've "annotated" this as a keyword.
1797 return ANK_Success;
1799 case Sema::NC_Unknown:
1800 // It's not something we know about. Leave it unannotated.
1801 break;
1803 case Sema::NC_Type: {
1804 if (TryAltiVecVectorToken())
1805 // vector has been found as a type id when altivec is enabled but
1806 // this is followed by a declaration specifier so this is really the
1807 // altivec vector token. Leave it unannotated.
1808 break;
1809 SourceLocation BeginLoc = NameLoc;
1810 if (SS.isNotEmpty())
1811 BeginLoc = SS.getBeginLoc();
1813 /// An Objective-C object type followed by '<' is a specialization of
1814 /// a parameterized class type or a protocol-qualified type.
1815 ParsedType Ty = Classification.getType();
1816 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1817 (Ty.get()->isObjCObjectType() ||
1818 Ty.get()->isObjCObjectPointerType())) {
1819 // Consume the name.
1820 SourceLocation IdentifierLoc = ConsumeToken();
1821 SourceLocation NewEndLoc;
1822 TypeResult NewType
1823 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1824 /*consumeLastToken=*/false,
1825 NewEndLoc);
1826 if (NewType.isUsable())
1827 Ty = NewType.get();
1828 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1829 return ANK_Error;
1832 Tok.setKind(tok::annot_typename);
1833 setTypeAnnotation(Tok, Ty);
1834 Tok.setAnnotationEndLoc(Tok.getLocation());
1835 Tok.setLocation(BeginLoc);
1836 PP.AnnotateCachedTokens(Tok);
1837 return ANK_Success;
1840 case Sema::NC_OverloadSet:
1841 Tok.setKind(tok::annot_overload_set);
1842 setExprAnnotation(Tok, Classification.getExpression());
1843 Tok.setAnnotationEndLoc(NameLoc);
1844 if (SS.isNotEmpty())
1845 Tok.setLocation(SS.getBeginLoc());
1846 PP.AnnotateCachedTokens(Tok);
1847 return ANK_Success;
1849 case Sema::NC_NonType:
1850 if (TryAltiVecVectorToken())
1851 // vector has been found as a non-type id when altivec is enabled but
1852 // this is followed by a declaration specifier so this is really the
1853 // altivec vector token. Leave it unannotated.
1854 break;
1855 Tok.setKind(tok::annot_non_type);
1856 setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());
1857 Tok.setLocation(NameLoc);
1858 Tok.setAnnotationEndLoc(NameLoc);
1859 PP.AnnotateCachedTokens(Tok);
1860 if (SS.isNotEmpty())
1861 AnnotateScopeToken(SS, !WasScopeAnnotation);
1862 return ANK_Success;
1864 case Sema::NC_UndeclaredNonType:
1865 case Sema::NC_DependentNonType:
1866 Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType
1867 ? tok::annot_non_type_undeclared
1868 : tok::annot_non_type_dependent);
1869 setIdentifierAnnotation(Tok, Name);
1870 Tok.setLocation(NameLoc);
1871 Tok.setAnnotationEndLoc(NameLoc);
1872 PP.AnnotateCachedTokens(Tok);
1873 if (SS.isNotEmpty())
1874 AnnotateScopeToken(SS, !WasScopeAnnotation);
1875 return ANK_Success;
1877 case Sema::NC_TypeTemplate:
1878 if (Next.isNot(tok::less)) {
1879 // This may be a type template being used as a template template argument.
1880 if (SS.isNotEmpty())
1881 AnnotateScopeToken(SS, !WasScopeAnnotation);
1882 return ANK_TemplateName;
1884 [[fallthrough]];
1885 case Sema::NC_VarTemplate:
1886 case Sema::NC_FunctionTemplate:
1887 case Sema::NC_UndeclaredTemplate: {
1888 // We have a type, variable or function template followed by '<'.
1889 ConsumeToken();
1890 UnqualifiedId Id;
1891 Id.setIdentifier(Name, NameLoc);
1892 if (AnnotateTemplateIdToken(
1893 TemplateTy::make(Classification.getTemplateName()),
1894 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1895 return ANK_Error;
1896 return ANK_Success;
1898 case Sema::NC_Concept: {
1899 UnqualifiedId Id;
1900 Id.setIdentifier(Name, NameLoc);
1901 if (Next.is(tok::less))
1902 // We have a concept name followed by '<'. Consume the identifier token so
1903 // we reach the '<' and annotate it.
1904 ConsumeToken();
1905 if (AnnotateTemplateIdToken(
1906 TemplateTy::make(Classification.getTemplateName()),
1907 Classification.getTemplateNameKind(), SS, SourceLocation(), Id,
1908 /*AllowTypeAnnotation=*/false, /*TypeConstraint=*/true))
1909 return ANK_Error;
1910 return ANK_Success;
1914 // Unable to classify the name, but maybe we can annotate a scope specifier.
1915 if (SS.isNotEmpty())
1916 AnnotateScopeToken(SS, !WasScopeAnnotation);
1917 return ANK_Unresolved;
1920 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1921 assert(Tok.isNot(tok::identifier));
1922 Diag(Tok, diag::ext_keyword_as_ident)
1923 << PP.getSpelling(Tok)
1924 << DisableKeyword;
1925 if (DisableKeyword)
1926 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1927 Tok.setKind(tok::identifier);
1928 return true;
1931 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1932 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1933 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1934 /// with a single annotation token representing the typename or C++ scope
1935 /// respectively.
1936 /// This simplifies handling of C++ scope specifiers and allows efficient
1937 /// backtracking without the need to re-parse and resolve nested-names and
1938 /// typenames.
1939 /// It will mainly be called when we expect to treat identifiers as typenames
1940 /// (if they are typenames). For example, in C we do not expect identifiers
1941 /// inside expressions to be treated as typenames so it will not be called
1942 /// for expressions in C.
1943 /// The benefit for C/ObjC is that a typename will be annotated and
1944 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1945 /// will not be called twice, once to check whether we have a declaration
1946 /// specifier, and another one to get the actual type inside
1947 /// ParseDeclarationSpecifiers).
1949 /// This returns true if an error occurred.
1951 /// Note that this routine emits an error if you call it with ::new or ::delete
1952 /// as the current tokens, so only call it in contexts where these are invalid.
1953 bool Parser::TryAnnotateTypeOrScopeToken(
1954 ImplicitTypenameContext AllowImplicitTypename) {
1955 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1956 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1957 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1958 Tok.is(tok::kw___super)) &&
1959 "Cannot be a type or scope token!");
1961 if (Tok.is(tok::kw_typename)) {
1962 // MSVC lets you do stuff like:
1963 // typename typedef T_::D D;
1965 // We will consume the typedef token here and put it back after we have
1966 // parsed the first identifier, transforming it into something more like:
1967 // typename T_::D typedef D;
1968 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1969 Token TypedefToken;
1970 PP.Lex(TypedefToken);
1971 bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);
1972 PP.EnterToken(Tok, /*IsReinject=*/true);
1973 Tok = TypedefToken;
1974 if (!Result)
1975 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1976 return Result;
1979 // Parse a C++ typename-specifier, e.g., "typename T::type".
1981 // typename-specifier:
1982 // 'typename' '::' [opt] nested-name-specifier identifier
1983 // 'typename' '::' [opt] nested-name-specifier template [opt]
1984 // simple-template-id
1985 SourceLocation TypenameLoc = ConsumeToken();
1986 CXXScopeSpec SS;
1987 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1988 /*ObjectHasErrors=*/false,
1989 /*EnteringContext=*/false, nullptr,
1990 /*IsTypename*/ true))
1991 return true;
1992 if (SS.isEmpty()) {
1993 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1994 Tok.is(tok::annot_decltype)) {
1995 // Attempt to recover by skipping the invalid 'typename'
1996 if (Tok.is(tok::annot_decltype) ||
1997 (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&
1998 Tok.isAnnotation())) {
1999 unsigned DiagID = diag::err_expected_qualified_after_typename;
2000 // MS compatibility: MSVC permits using known types with typename.
2001 // e.g. "typedef typename T* pointer_type"
2002 if (getLangOpts().MicrosoftExt)
2003 DiagID = diag::warn_expected_qualified_after_typename;
2004 Diag(Tok.getLocation(), DiagID);
2005 return false;
2008 if (Tok.isEditorPlaceholder())
2009 return true;
2011 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
2012 return true;
2015 TypeResult Ty;
2016 if (Tok.is(tok::identifier)) {
2017 // FIXME: check whether the next token is '<', first!
2018 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
2019 *Tok.getIdentifierInfo(),
2020 Tok.getLocation());
2021 } else if (Tok.is(tok::annot_template_id)) {
2022 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2023 if (!TemplateId->mightBeType()) {
2024 Diag(Tok, diag::err_typename_refers_to_non_type_template)
2025 << Tok.getAnnotationRange();
2026 return true;
2029 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2030 TemplateId->NumArgs);
2032 Ty = TemplateId->isInvalid()
2033 ? TypeError()
2034 : Actions.ActOnTypenameType(
2035 getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,
2036 TemplateId->Template, TemplateId->Name,
2037 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
2038 TemplateArgsPtr, TemplateId->RAngleLoc);
2039 } else {
2040 Diag(Tok, diag::err_expected_type_name_after_typename)
2041 << SS.getRange();
2042 return true;
2045 SourceLocation EndLoc = Tok.getLastLoc();
2046 Tok.setKind(tok::annot_typename);
2047 setTypeAnnotation(Tok, Ty);
2048 Tok.setAnnotationEndLoc(EndLoc);
2049 Tok.setLocation(TypenameLoc);
2050 PP.AnnotateCachedTokens(Tok);
2051 return false;
2054 // Remembers whether the token was originally a scope annotation.
2055 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2057 CXXScopeSpec SS;
2058 if (getLangOpts().CPlusPlus)
2059 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2060 /*ObjectHasErrors=*/false,
2061 /*EnteringContext*/ false))
2062 return true;
2064 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,
2065 AllowImplicitTypename);
2068 /// Try to annotate a type or scope token, having already parsed an
2069 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
2070 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
2071 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
2072 CXXScopeSpec &SS, bool IsNewScope,
2073 ImplicitTypenameContext AllowImplicitTypename) {
2074 if (Tok.is(tok::identifier)) {
2075 // Determine whether the identifier is a type name.
2076 if (ParsedType Ty = Actions.getTypeName(
2077 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
2078 false, NextToken().is(tok::period), nullptr,
2079 /*IsCtorOrDtorName=*/false,
2080 /*NonTrivialTypeSourceInfo=*/true,
2081 /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {
2082 SourceLocation BeginLoc = Tok.getLocation();
2083 if (SS.isNotEmpty()) // it was a C++ qualified type name.
2084 BeginLoc = SS.getBeginLoc();
2086 /// An Objective-C object type followed by '<' is a specialization of
2087 /// a parameterized class type or a protocol-qualified type.
2088 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
2089 (Ty.get()->isObjCObjectType() ||
2090 Ty.get()->isObjCObjectPointerType())) {
2091 // Consume the name.
2092 SourceLocation IdentifierLoc = ConsumeToken();
2093 SourceLocation NewEndLoc;
2094 TypeResult NewType
2095 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
2096 /*consumeLastToken=*/false,
2097 NewEndLoc);
2098 if (NewType.isUsable())
2099 Ty = NewType.get();
2100 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
2101 return false;
2104 // This is a typename. Replace the current token in-place with an
2105 // annotation type token.
2106 Tok.setKind(tok::annot_typename);
2107 setTypeAnnotation(Tok, Ty);
2108 Tok.setAnnotationEndLoc(Tok.getLocation());
2109 Tok.setLocation(BeginLoc);
2111 // In case the tokens were cached, have Preprocessor replace
2112 // them with the annotation token.
2113 PP.AnnotateCachedTokens(Tok);
2114 return false;
2117 if (!getLangOpts().CPlusPlus) {
2118 // If we're in C, the only place we can have :: tokens is C2x
2119 // attribute which is parsed elsewhere. If the identifier is not a type,
2120 // then it can't be scope either, just early exit.
2121 return false;
2124 // If this is a template-id, annotate with a template-id or type token.
2125 // FIXME: This appears to be dead code. We already have formed template-id
2126 // tokens when parsing the scope specifier; this can never form a new one.
2127 if (NextToken().is(tok::less)) {
2128 TemplateTy Template;
2129 UnqualifiedId TemplateName;
2130 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2131 bool MemberOfUnknownSpecialization;
2132 if (TemplateNameKind TNK = Actions.isTemplateName(
2133 getCurScope(), SS,
2134 /*hasTemplateKeyword=*/false, TemplateName,
2135 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
2136 MemberOfUnknownSpecialization)) {
2137 // Only annotate an undeclared template name as a template-id if the
2138 // following tokens have the form of a template argument list.
2139 if (TNK != TNK_Undeclared_template ||
2140 isTemplateArgumentList(1) != TPResult::False) {
2141 // Consume the identifier.
2142 ConsumeToken();
2143 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
2144 TemplateName)) {
2145 // If an unrecoverable error occurred, we need to return true here,
2146 // because the token stream is in a damaged state. We may not
2147 // return a valid identifier.
2148 return true;
2154 // The current token, which is either an identifier or a
2155 // template-id, is not part of the annotation. Fall through to
2156 // push that token back into the stream and complete the C++ scope
2157 // specifier annotation.
2160 if (Tok.is(tok::annot_template_id)) {
2161 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2162 if (TemplateId->Kind == TNK_Type_template) {
2163 // A template-id that refers to a type was parsed into a
2164 // template-id annotation in a context where we weren't allowed
2165 // to produce a type annotation token. Update the template-id
2166 // annotation token to a type annotation token now.
2167 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2168 return false;
2172 if (SS.isEmpty())
2173 return false;
2175 // A C++ scope specifier that isn't followed by a typename.
2176 AnnotateScopeToken(SS, IsNewScope);
2177 return false;
2180 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2181 /// annotates C++ scope specifiers and template-ids. This returns
2182 /// true if there was an error that could not be recovered from.
2184 /// Note that this routine emits an error if you call it with ::new or ::delete
2185 /// as the current tokens, so only call it in contexts where these are invalid.
2186 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
2187 assert(getLangOpts().CPlusPlus &&
2188 "Call sites of this function should be guarded by checking for C++");
2189 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2191 CXXScopeSpec SS;
2192 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
2193 /*ObjectHasErrors=*/false,
2194 EnteringContext))
2195 return true;
2196 if (SS.isEmpty())
2197 return false;
2199 AnnotateScopeToken(SS, true);
2200 return false;
2203 bool Parser::isTokenEqualOrEqualTypo() {
2204 tok::TokenKind Kind = Tok.getKind();
2205 switch (Kind) {
2206 default:
2207 return false;
2208 case tok::ampequal: // &=
2209 case tok::starequal: // *=
2210 case tok::plusequal: // +=
2211 case tok::minusequal: // -=
2212 case tok::exclaimequal: // !=
2213 case tok::slashequal: // /=
2214 case tok::percentequal: // %=
2215 case tok::lessequal: // <=
2216 case tok::lesslessequal: // <<=
2217 case tok::greaterequal: // >=
2218 case tok::greatergreaterequal: // >>=
2219 case tok::caretequal: // ^=
2220 case tok::pipeequal: // |=
2221 case tok::equalequal: // ==
2222 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2223 << Kind
2224 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2225 [[fallthrough]];
2226 case tok::equal:
2227 return true;
2231 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2232 assert(Tok.is(tok::code_completion));
2233 PrevTokLocation = Tok.getLocation();
2235 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2236 if (S->isFunctionScope()) {
2237 cutOffParsing();
2238 Actions.CodeCompleteOrdinaryName(getCurScope(),
2239 Sema::PCC_RecoveryInFunction);
2240 return PrevTokLocation;
2243 if (S->isClassScope()) {
2244 cutOffParsing();
2245 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2246 return PrevTokLocation;
2250 cutOffParsing();
2251 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2252 return PrevTokLocation;
2255 // Code-completion pass-through functions
2257 void Parser::CodeCompleteDirective(bool InConditional) {
2258 Actions.CodeCompletePreprocessorDirective(InConditional);
2261 void Parser::CodeCompleteInConditionalExclusion() {
2262 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2265 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2266 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2269 void Parser::CodeCompletePreprocessorExpression() {
2270 Actions.CodeCompletePreprocessorExpression();
2273 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2274 MacroInfo *MacroInfo,
2275 unsigned ArgumentIndex) {
2276 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2277 ArgumentIndex);
2280 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2281 Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2284 void Parser::CodeCompleteNaturalLanguage() {
2285 Actions.CodeCompleteNaturalLanguage();
2288 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2289 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2290 "Expected '__if_exists' or '__if_not_exists'");
2291 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2292 Result.KeywordLoc = ConsumeToken();
2294 BalancedDelimiterTracker T(*this, tok::l_paren);
2295 if (T.consumeOpen()) {
2296 Diag(Tok, diag::err_expected_lparen_after)
2297 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2298 return true;
2301 // Parse nested-name-specifier.
2302 if (getLangOpts().CPlusPlus)
2303 ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,
2304 /*ObjectHasErrors=*/false,
2305 /*EnteringContext=*/false);
2307 // Check nested-name specifier.
2308 if (Result.SS.isInvalid()) {
2309 T.skipToEnd();
2310 return true;
2313 // Parse the unqualified-id.
2314 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2315 if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,
2316 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2317 /*AllowDestructorName*/ true,
2318 /*AllowConstructorName*/ true,
2319 /*AllowDeductionGuide*/ false, &TemplateKWLoc,
2320 Result.Name)) {
2321 T.skipToEnd();
2322 return true;
2325 if (T.consumeClose())
2326 return true;
2328 // Check if the symbol exists.
2329 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2330 Result.IsIfExists, Result.SS,
2331 Result.Name)) {
2332 case Sema::IER_Exists:
2333 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2334 break;
2336 case Sema::IER_DoesNotExist:
2337 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2338 break;
2340 case Sema::IER_Dependent:
2341 Result.Behavior = IEB_Dependent;
2342 break;
2344 case Sema::IER_Error:
2345 return true;
2348 return false;
2351 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2352 IfExistsCondition Result;
2353 if (ParseMicrosoftIfExistsCondition(Result))
2354 return;
2356 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2357 if (Braces.consumeOpen()) {
2358 Diag(Tok, diag::err_expected) << tok::l_brace;
2359 return;
2362 switch (Result.Behavior) {
2363 case IEB_Parse:
2364 // Parse declarations below.
2365 break;
2367 case IEB_Dependent:
2368 llvm_unreachable("Cannot have a dependent external declaration");
2370 case IEB_Skip:
2371 Braces.skipToEnd();
2372 return;
2375 // Parse the declarations.
2376 // FIXME: Support module import within __if_exists?
2377 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2378 ParsedAttributes Attrs(AttrFactory);
2379 MaybeParseCXX11Attributes(Attrs);
2380 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2381 DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);
2382 if (Result && !getCurScope()->getParent())
2383 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2385 Braces.consumeClose();
2388 /// Parse a declaration beginning with the 'module' keyword or C++20
2389 /// context-sensitive keyword (optionally preceded by 'export').
2391 /// module-declaration: [Modules TS + P0629R0]
2392 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2394 /// global-module-fragment: [C++2a]
2395 /// 'module' ';' top-level-declaration-seq[opt]
2396 /// module-declaration: [C++2a]
2397 /// 'export'[opt] 'module' module-name module-partition[opt]
2398 /// attribute-specifier-seq[opt] ';'
2399 /// private-module-fragment: [C++2a]
2400 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2401 Parser::DeclGroupPtrTy
2402 Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {
2403 SourceLocation StartLoc = Tok.getLocation();
2405 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2406 ? Sema::ModuleDeclKind::Interface
2407 : Sema::ModuleDeclKind::Implementation;
2409 assert(
2410 (Tok.is(tok::kw_module) ||
2411 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2412 "not a module declaration");
2413 SourceLocation ModuleLoc = ConsumeToken();
2415 // Attributes appear after the module name, not before.
2416 // FIXME: Suggest moving the attributes later with a fixit.
2417 DiagnoseAndSkipCXX11Attributes();
2419 // Parse a global-module-fragment, if present.
2420 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2421 SourceLocation SemiLoc = ConsumeToken();
2422 if (ImportState != Sema::ModuleImportState::FirstDecl) {
2423 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2424 << SourceRange(StartLoc, SemiLoc);
2425 return nullptr;
2427 if (MDK == Sema::ModuleDeclKind::Interface) {
2428 Diag(StartLoc, diag::err_module_fragment_exported)
2429 << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2431 ImportState = Sema::ModuleImportState::GlobalFragment;
2432 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2435 // Parse a private-module-fragment, if present.
2436 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2437 NextToken().is(tok::kw_private)) {
2438 if (MDK == Sema::ModuleDeclKind::Interface) {
2439 Diag(StartLoc, diag::err_module_fragment_exported)
2440 << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2442 ConsumeToken();
2443 SourceLocation PrivateLoc = ConsumeToken();
2444 DiagnoseAndSkipCXX11Attributes();
2445 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2446 ImportState = ImportState == Sema::ModuleImportState::ImportAllowed
2447 ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2448 : Sema::ModuleImportState::PrivateFragmentImportFinished;
2449 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2452 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2453 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))
2454 return nullptr;
2456 // Parse the optional module-partition.
2457 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2458 if (Tok.is(tok::colon)) {
2459 SourceLocation ColonLoc = ConsumeToken();
2460 if (!getLangOpts().CPlusPlusModules)
2461 Diag(ColonLoc, diag::err_unsupported_module_partition)
2462 << SourceRange(ColonLoc, Partition.back().second);
2463 // Recover by ignoring the partition name.
2464 else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))
2465 return nullptr;
2468 // We don't support any module attributes yet; just parse them and diagnose.
2469 ParsedAttributes Attrs(AttrFactory);
2470 MaybeParseCXX11Attributes(Attrs);
2471 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2472 /*DiagnoseEmptyAttrs=*/false,
2473 /*WarnOnUnknownAttrs=*/true);
2475 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2477 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2478 ImportState);
2481 /// Parse a module import declaration. This is essentially the same for
2482 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2483 /// trailing optional attributes (in C++).
2485 /// [ObjC] @import declaration:
2486 /// '@' 'import' module-name ';'
2487 /// [ModTS] module-import-declaration:
2488 /// 'import' module-name attribute-specifier-seq[opt] ';'
2489 /// [C++20] module-import-declaration:
2490 /// 'export'[opt] 'import' module-name
2491 /// attribute-specifier-seq[opt] ';'
2492 /// 'export'[opt] 'import' module-partition
2493 /// attribute-specifier-seq[opt] ';'
2494 /// 'export'[opt] 'import' header-name
2495 /// attribute-specifier-seq[opt] ';'
2496 Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2497 Sema::ModuleImportState &ImportState) {
2498 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2500 SourceLocation ExportLoc;
2501 TryConsumeToken(tok::kw_export, ExportLoc);
2503 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2504 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2505 "Improper start to module import");
2506 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2507 SourceLocation ImportLoc = ConsumeToken();
2509 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2510 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2511 bool IsPartition = false;
2512 Module *HeaderUnit = nullptr;
2513 if (Tok.is(tok::header_name)) {
2514 // This is a header import that the preprocessor decided we should skip
2515 // because it was malformed in some way. Parse and ignore it; it's already
2516 // been diagnosed.
2517 ConsumeToken();
2518 } else if (Tok.is(tok::annot_header_unit)) {
2519 // This is a header import that the preprocessor mapped to a module import.
2520 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2521 ConsumeAnnotationToken();
2522 } else if (Tok.is(tok::colon)) {
2523 SourceLocation ColonLoc = ConsumeToken();
2524 if (!getLangOpts().CPlusPlusModules)
2525 Diag(ColonLoc, diag::err_unsupported_module_partition)
2526 << SourceRange(ColonLoc, Path.back().second);
2527 // Recover by leaving partition empty.
2528 else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
2529 return nullptr;
2530 else
2531 IsPartition = true;
2532 } else {
2533 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
2534 return nullptr;
2537 ParsedAttributes Attrs(AttrFactory);
2538 MaybeParseCXX11Attributes(Attrs);
2539 // We don't support any module import attributes yet.
2540 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2541 /*DiagnoseEmptyAttrs=*/false,
2542 /*WarnOnUnknownAttrs=*/true);
2544 if (PP.hadModuleLoaderFatalFailure()) {
2545 // With a fatal failure in the module loader, we abort parsing.
2546 cutOffParsing();
2547 return nullptr;
2550 // Diagnose mis-imports.
2551 bool SeenError = true;
2552 switch (ImportState) {
2553 case Sema::ModuleImportState::ImportAllowed:
2554 SeenError = false;
2555 break;
2556 case Sema::ModuleImportState::FirstDecl:
2557 case Sema::ModuleImportState::NotACXX20Module:
2558 // We can only import a partition within a module purview.
2559 if (IsPartition)
2560 Diag(ImportLoc, diag::err_partition_import_outside_module);
2561 else
2562 SeenError = false;
2563 break;
2564 case Sema::ModuleImportState::GlobalFragment:
2565 case Sema::ModuleImportState::PrivateFragmentImportAllowed:
2566 // We can only have pre-processor directives in the global module fragment
2567 // which allows pp-import, but not of a partition (since the global module
2568 // does not have partitions).
2569 // We cannot import a partition into a private module fragment, since
2570 // [module.private.frag]/1 disallows private module fragments in a multi-
2571 // TU module.
2572 if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=
2573 Module::ModuleKind::ModuleHeaderUnit))
2574 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2575 << IsPartition
2576 << (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);
2577 else
2578 SeenError = false;
2579 break;
2580 case Sema::ModuleImportState::ImportFinished:
2581 case Sema::ModuleImportState::PrivateFragmentImportFinished:
2582 if (getLangOpts().CPlusPlusModules)
2583 Diag(ImportLoc, diag::err_import_not_allowed_here);
2584 else
2585 SeenError = false;
2586 break;
2588 if (SeenError) {
2589 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2590 return nullptr;
2593 DeclResult Import;
2594 if (HeaderUnit)
2595 Import =
2596 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2597 else if (!Path.empty())
2598 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2599 IsPartition);
2600 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2601 if (Import.isInvalid())
2602 return nullptr;
2604 // Using '@import' in framework headers requires modules to be enabled so that
2605 // the header is parseable. Emit a warning to make the user aware.
2606 if (IsObjCAtImport && AtLoc.isValid()) {
2607 auto &SrcMgr = PP.getSourceManager();
2608 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2609 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2610 .endswith(".framework"))
2611 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2614 return Import.get();
2617 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2618 /// grammar).
2620 /// module-name:
2621 /// module-name-qualifier[opt] identifier
2622 /// module-name-qualifier:
2623 /// module-name-qualifier[opt] identifier '.'
2624 bool Parser::ParseModuleName(
2625 SourceLocation UseLoc,
2626 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2627 bool IsImport) {
2628 // Parse the module path.
2629 while (true) {
2630 if (!Tok.is(tok::identifier)) {
2631 if (Tok.is(tok::code_completion)) {
2632 cutOffParsing();
2633 Actions.CodeCompleteModuleImport(UseLoc, Path);
2634 return true;
2637 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2638 SkipUntil(tok::semi);
2639 return true;
2642 // Record this part of the module path.
2643 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2644 ConsumeToken();
2646 if (Tok.isNot(tok::period))
2647 return false;
2649 ConsumeToken();
2653 /// Try recover parser when module annotation appears where it must not
2654 /// be found.
2655 /// \returns false if the recover was successful and parsing may be continued, or
2656 /// true if parser must bail out to top level and handle the token there.
2657 bool Parser::parseMisplacedModuleImport() {
2658 while (true) {
2659 switch (Tok.getKind()) {
2660 case tok::annot_module_end:
2661 // If we recovered from a misplaced module begin, we expect to hit a
2662 // misplaced module end too. Stay in the current context when this
2663 // happens.
2664 if (MisplacedModuleBeginCount) {
2665 --MisplacedModuleBeginCount;
2666 Actions.ActOnModuleEnd(Tok.getLocation(),
2667 reinterpret_cast<Module *>(
2668 Tok.getAnnotationValue()));
2669 ConsumeAnnotationToken();
2670 continue;
2672 // Inform caller that recovery failed, the error must be handled at upper
2673 // level. This will generate the desired "missing '}' at end of module"
2674 // diagnostics on the way out.
2675 return true;
2676 case tok::annot_module_begin:
2677 // Recover by entering the module (Sema will diagnose).
2678 Actions.ActOnModuleBegin(Tok.getLocation(),
2679 reinterpret_cast<Module *>(
2680 Tok.getAnnotationValue()));
2681 ConsumeAnnotationToken();
2682 ++MisplacedModuleBeginCount;
2683 continue;
2684 case tok::annot_module_include:
2685 // Module import found where it should not be, for instance, inside a
2686 // namespace. Recover by importing the module.
2687 Actions.ActOnModuleInclude(Tok.getLocation(),
2688 reinterpret_cast<Module *>(
2689 Tok.getAnnotationValue()));
2690 ConsumeAnnotationToken();
2691 // If there is another module import, process it.
2692 continue;
2693 default:
2694 return false;
2697 return false;
2700 bool BalancedDelimiterTracker::diagnoseOverflow() {
2701 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2702 << P.getLangOpts().BracketDepth;
2703 P.Diag(P.Tok, diag::note_bracket_depth);
2704 P.cutOffParsing();
2705 return true;
2708 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2709 const char *Msg,
2710 tok::TokenKind SkipToTok) {
2711 LOpen = P.Tok.getLocation();
2712 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2713 if (SkipToTok != tok::unknown)
2714 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2715 return true;
2718 if (getDepth() < P.getLangOpts().BracketDepth)
2719 return false;
2721 return diagnoseOverflow();
2724 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2725 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2727 if (P.Tok.is(tok::annot_module_end))
2728 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2729 else
2730 P.Diag(P.Tok, diag::err_expected) << Close;
2731 P.Diag(LOpen, diag::note_matching) << Kind;
2733 // If we're not already at some kind of closing bracket, skip to our closing
2734 // token.
2735 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2736 P.Tok.isNot(tok::r_square) &&
2737 P.SkipUntil(Close, FinalToken,
2738 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2739 P.Tok.is(Close))
2740 LClose = P.ConsumeAnyToken();
2741 return true;
2744 void BalancedDelimiterTracker::skipToEnd() {
2745 P.SkipUntil(Close, Parser::StopBeforeMatch);
2746 consumeClose();