1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/DiagnosticParse.h"
19 #include "clang/Basic/FileManager.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 "clang/Sema/SemaCodeCompletion.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/TimeProfiler.h"
27 using namespace clang
;
31 /// A comment handler that passes comments found by the preprocessor
32 /// to the parser action.
33 class ActionCommentHandler
: public CommentHandler
{
37 explicit ActionCommentHandler(Sema
&S
) : S(S
) { }
39 bool HandleComment(Preprocessor
&PP
, SourceRange Comment
) override
{
40 S
.ActOnComment(Comment
);
44 } // end anonymous namespace
46 IdentifierInfo
*Parser::getSEHExceptKeyword() {
47 // __except is accepted as a (contextual) keyword
48 if (!Ident__except
&& (getLangOpts().MicrosoftExt
|| getLangOpts().Borland
))
49 Ident__except
= PP
.getIdentifierInfo("__except");
54 Parser::Parser(Preprocessor
&pp
, Sema
&actions
, bool skipFunctionBodies
)
55 : PP(pp
), PreferredType(pp
.isCodeCompletionEnabled()), Actions(actions
),
56 Diags(PP
.getDiagnostics()), GreaterThanIsOperator(true),
57 ColonIsSacred(false), InMessageExpression(false),
58 TemplateParameterDepth(0), ParsingInObjCContainer(false) {
59 SkipFunctionBodies
= pp
.isCodeCompletionEnabled() || skipFunctionBodies
;
61 Tok
.setKind(tok::eof
);
62 Actions
.CurScope
= nullptr;
64 CurParsedObjCImpl
= nullptr;
66 // Add #pragma handlers. These are removed and destroyed in the
68 initializePragmaHandlers();
70 CommentSemaHandler
.reset(new ActionCommentHandler(actions
));
71 PP
.addCommentHandler(CommentSemaHandler
.get());
73 PP
.setCodeCompletionHandler(*this);
75 Actions
.ParseTypeFromStringCallback
=
76 [this](StringRef TypeStr
, StringRef Context
, SourceLocation IncludeLoc
) {
77 return this->ParseTypeFromString(TypeStr
, Context
, IncludeLoc
);
81 DiagnosticBuilder
Parser::Diag(SourceLocation Loc
, unsigned DiagID
) {
82 return Diags
.Report(Loc
, DiagID
);
85 DiagnosticBuilder
Parser::Diag(const Token
&Tok
, unsigned DiagID
) {
86 return Diag(Tok
.getLocation(), DiagID
);
89 /// Emits a diagnostic suggesting parentheses surrounding a
92 /// \param Loc The location where we'll emit the diagnostic.
93 /// \param DK The kind of diagnostic to emit.
94 /// \param ParenRange Source range enclosing code that should be parenthesized.
95 void Parser::SuggestParentheses(SourceLocation Loc
, unsigned DK
,
96 SourceRange ParenRange
) {
97 SourceLocation EndLoc
= PP
.getLocForEndOfToken(ParenRange
.getEnd());
98 if (!ParenRange
.getEnd().isFileID() || EndLoc
.isInvalid()) {
99 // We can't display the parentheses, so just dig the
100 // warning/error and return.
106 << FixItHint::CreateInsertion(ParenRange
.getBegin(), "(")
107 << FixItHint::CreateInsertion(EndLoc
, ")");
110 static bool IsCommonTypo(tok::TokenKind ExpectedTok
, const Token
&Tok
) {
111 switch (ExpectedTok
) {
113 return Tok
.is(tok::colon
) || Tok
.is(tok::comma
); // : or , for ;
114 default: return false;
118 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok
, unsigned DiagID
,
120 if (Tok
.is(ExpectedTok
) || Tok
.is(tok::code_completion
)) {
125 // Detect common single-character typos and resume.
126 if (IsCommonTypo(ExpectedTok
, Tok
)) {
127 SourceLocation Loc
= Tok
.getLocation();
129 DiagnosticBuilder DB
= Diag(Loc
, DiagID
);
130 DB
<< FixItHint::CreateReplacement(
131 SourceRange(Loc
), tok::getPunctuatorSpelling(ExpectedTok
));
132 if (DiagID
== diag::err_expected
)
134 else if (DiagID
== diag::err_expected_after
)
135 DB
<< Msg
<< ExpectedTok
;
140 // Pretend there wasn't a problem.
145 SourceLocation EndLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
146 const char *Spelling
= nullptr;
147 if (EndLoc
.isValid())
148 Spelling
= tok::getPunctuatorSpelling(ExpectedTok
);
150 DiagnosticBuilder DB
=
152 ? Diag(EndLoc
, DiagID
) << FixItHint::CreateInsertion(EndLoc
, Spelling
)
154 if (DiagID
== diag::err_expected
)
156 else if (DiagID
== diag::err_expected_after
)
157 DB
<< Msg
<< ExpectedTok
;
164 bool Parser::ExpectAndConsumeSemi(unsigned DiagID
, StringRef TokenUsed
) {
165 if (TryConsumeToken(tok::semi
))
168 if (Tok
.is(tok::code_completion
)) {
169 handleUnexpectedCodeCompletionToken();
173 if ((Tok
.is(tok::r_paren
) || Tok
.is(tok::r_square
)) &&
174 NextToken().is(tok::semi
)) {
175 Diag(Tok
, diag::err_extraneous_token_before_semi
)
176 << PP
.getSpelling(Tok
)
177 << FixItHint::CreateRemoval(Tok
.getLocation());
178 ConsumeAnyToken(); // The ')' or ']'.
179 ConsumeToken(); // The ';'.
183 return ExpectAndConsume(tok::semi
, DiagID
, TokenUsed
);
186 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind
, DeclSpec::TST TST
) {
187 if (!Tok
.is(tok::semi
)) return;
189 bool HadMultipleSemis
= false;
190 SourceLocation StartLoc
= Tok
.getLocation();
191 SourceLocation EndLoc
= Tok
.getLocation();
194 while ((Tok
.is(tok::semi
) && !Tok
.isAtStartOfLine())) {
195 HadMultipleSemis
= true;
196 EndLoc
= Tok
.getLocation();
200 // C++11 allows extra semicolons at namespace scope, but not in any of the
202 if (Kind
== OutsideFunction
&& getLangOpts().CPlusPlus
) {
203 if (getLangOpts().CPlusPlus11
)
204 Diag(StartLoc
, diag::warn_cxx98_compat_top_level_semi
)
205 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
207 Diag(StartLoc
, diag::ext_extra_semi_cxx11
)
208 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
212 if (Kind
!= AfterMemberFunctionDefinition
|| HadMultipleSemis
)
213 Diag(StartLoc
, diag::ext_extra_semi
)
214 << Kind
<< DeclSpec::getSpecifierName(TST
,
215 Actions
.getASTContext().getPrintingPolicy())
216 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
218 // A single semicolon is valid after a member function definition.
219 Diag(StartLoc
, diag::warn_extra_semi_after_mem_fn_def
)
220 << FixItHint::CreateRemoval(SourceRange(StartLoc
, EndLoc
));
223 bool Parser::expectIdentifier() {
224 if (Tok
.is(tok::identifier
))
226 if (const auto *II
= Tok
.getIdentifierInfo()) {
227 if (II
->isCPlusPlusKeyword(getLangOpts())) {
228 Diag(Tok
, diag::err_expected_token_instead_of_objcxx_keyword
)
229 << tok::identifier
<< Tok
.getIdentifierInfo();
230 // Objective-C++: Recover by treating this keyword as a valid identifier.
234 Diag(Tok
, diag::err_expected
) << tok::identifier
;
238 void Parser::checkCompoundToken(SourceLocation FirstTokLoc
,
239 tok::TokenKind FirstTokKind
, CompoundToken Op
) {
240 if (FirstTokLoc
.isInvalid())
242 SourceLocation SecondTokLoc
= Tok
.getLocation();
244 // If either token is in a macro, we expect both tokens to come from the same
246 if ((FirstTokLoc
.isMacroID() || SecondTokLoc
.isMacroID()) &&
247 PP
.getSourceManager().getFileID(FirstTokLoc
) !=
248 PP
.getSourceManager().getFileID(SecondTokLoc
)) {
249 Diag(FirstTokLoc
, diag::warn_compound_token_split_by_macro
)
250 << (FirstTokKind
== Tok
.getKind()) << FirstTokKind
<< Tok
.getKind()
251 << static_cast<int>(Op
) << SourceRange(FirstTokLoc
);
252 Diag(SecondTokLoc
, diag::note_compound_token_split_second_token_here
)
253 << (FirstTokKind
== Tok
.getKind()) << Tok
.getKind()
254 << SourceRange(SecondTokLoc
);
258 // We expect the tokens to abut.
259 if (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()) {
260 SourceLocation SpaceLoc
= PP
.getLocForEndOfToken(FirstTokLoc
);
261 if (SpaceLoc
.isInvalid())
262 SpaceLoc
= FirstTokLoc
;
263 Diag(SpaceLoc
, diag::warn_compound_token_split_by_whitespace
)
264 << (FirstTokKind
== Tok
.getKind()) << FirstTokKind
<< Tok
.getKind()
265 << static_cast<int>(Op
) << SourceRange(FirstTokLoc
, SecondTokLoc
);
270 //===----------------------------------------------------------------------===//
272 //===----------------------------------------------------------------------===//
274 static bool HasFlagsSet(Parser::SkipUntilFlags L
, Parser::SkipUntilFlags R
) {
275 return (static_cast<unsigned>(L
) & static_cast<unsigned>(R
)) != 0;
278 /// SkipUntil - Read tokens until we get to the specified token, then consume
279 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
280 /// token will ever occur, this skips to the next token, or to some likely
281 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
284 /// If SkipUntil finds the specified token, it returns true, otherwise it
286 bool Parser::SkipUntil(ArrayRef
<tok::TokenKind
> Toks
, SkipUntilFlags Flags
) {
287 // We always want this function to skip at least one token if the first token
288 // isn't T and if not at EOF.
289 bool isFirstTokenSkipped
= true;
291 // If we found one of the tokens, stop and return true.
292 for (unsigned i
= 0, NumToks
= Toks
.size(); i
!= NumToks
; ++i
) {
293 if (Tok
.is(Toks
[i
])) {
294 if (HasFlagsSet(Flags
, StopBeforeMatch
)) {
295 // Noop, don't consume the token.
303 // Important special case: The caller has given up and just wants us to
304 // skip the rest of the file. Do this without recursing, since we can
305 // get here precisely because the caller detected too much recursion.
306 if (Toks
.size() == 1 && Toks
[0] == tok::eof
&&
307 !HasFlagsSet(Flags
, StopAtSemi
) &&
308 !HasFlagsSet(Flags
, StopAtCodeCompletion
)) {
309 while (Tok
.isNot(tok::eof
))
314 switch (Tok
.getKind()) {
316 // Ran out of tokens.
319 case tok::annot_pragma_openmp
:
320 case tok::annot_attr_openmp
:
321 case tok::annot_pragma_openmp_end
:
322 // Stop before an OpenMP pragma boundary.
323 if (OpenMPDirectiveParsing
)
325 ConsumeAnnotationToken();
327 case tok::annot_pragma_openacc
:
328 case tok::annot_pragma_openacc_end
:
329 // Stop before an OpenACC pragma boundary.
330 if (OpenACCDirectiveParsing
)
332 ConsumeAnnotationToken();
334 case tok::annot_module_begin
:
335 case tok::annot_module_end
:
336 case tok::annot_module_include
:
337 case tok::annot_repl_input_end
:
338 // Stop before we change submodules. They generally indicate a "good"
339 // place to pick up parsing again (except in the special case where
340 // we're trying to skip to EOF).
343 case tok::code_completion
:
344 if (!HasFlagsSet(Flags
, StopAtCodeCompletion
))
345 handleUnexpectedCodeCompletionToken();
349 // Recursively skip properly-nested parens.
351 if (HasFlagsSet(Flags
, StopAtCodeCompletion
))
352 SkipUntil(tok::r_paren
, StopAtCodeCompletion
);
354 SkipUntil(tok::r_paren
);
357 // Recursively skip properly-nested square brackets.
359 if (HasFlagsSet(Flags
, StopAtCodeCompletion
))
360 SkipUntil(tok::r_square
, StopAtCodeCompletion
);
362 SkipUntil(tok::r_square
);
365 // Recursively skip properly-nested braces.
367 if (HasFlagsSet(Flags
, StopAtCodeCompletion
))
368 SkipUntil(tok::r_brace
, StopAtCodeCompletion
);
370 SkipUntil(tok::r_brace
);
373 // Recursively skip ? ... : pairs; these function as brackets. But
374 // still stop at a semicolon if requested.
376 SkipUntil(tok::colon
,
377 SkipUntilFlags(unsigned(Flags
) &
378 unsigned(StopAtCodeCompletion
| StopAtSemi
)));
381 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
382 // Since the user wasn't looking for this token (if they were, it would
383 // already be handled), this isn't balanced. If there is a LHS token at a
384 // higher level, we will assume that this matches the unbalanced token
385 // and return it. Otherwise, this is a spurious RHS token, which we skip.
387 if (ParenCount
&& !isFirstTokenSkipped
)
388 return false; // Matches something.
392 if (BracketCount
&& !isFirstTokenSkipped
)
393 return false; // Matches something.
397 if (BraceCount
&& !isFirstTokenSkipped
)
398 return false; // Matches something.
403 if (HasFlagsSet(Flags
, StopAtSemi
))
411 isFirstTokenSkipped
= false;
415 //===----------------------------------------------------------------------===//
416 // Scope manipulation
417 //===----------------------------------------------------------------------===//
419 /// EnterScope - Start a new scope.
420 void Parser::EnterScope(unsigned ScopeFlags
) {
421 if (NumCachedScopes
) {
422 Scope
*N
= ScopeCache
[--NumCachedScopes
];
423 N
->Init(getCurScope(), ScopeFlags
);
424 Actions
.CurScope
= N
;
426 Actions
.CurScope
= new Scope(getCurScope(), ScopeFlags
, Diags
);
430 /// ExitScope - Pop a scope off the scope stack.
431 void Parser::ExitScope() {
432 assert(getCurScope() && "Scope imbalance!");
434 // Inform the actions module that this scope is going away if there are any
436 Actions
.ActOnPopScope(Tok
.getLocation(), getCurScope());
438 Scope
*OldScope
= getCurScope();
439 Actions
.CurScope
= OldScope
->getParent();
441 if (NumCachedScopes
== ScopeCacheSize
)
444 ScopeCache
[NumCachedScopes
++] = OldScope
;
447 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
448 /// this object does nothing.
449 Parser::ParseScopeFlags::ParseScopeFlags(Parser
*Self
, unsigned ScopeFlags
,
451 : CurScope(ManageFlags
? Self
->getCurScope() : nullptr) {
453 OldFlags
= CurScope
->getFlags();
454 CurScope
->setFlags(ScopeFlags
);
458 /// Restore the flags for the current scope to what they were before this
459 /// object overrode them.
460 Parser::ParseScopeFlags::~ParseScopeFlags() {
462 CurScope
->setFlags(OldFlags
);
466 //===----------------------------------------------------------------------===//
467 // C99 6.9: External Definitions.
468 //===----------------------------------------------------------------------===//
471 // If we still have scopes active, delete the scope tree.
472 delete getCurScope();
473 Actions
.CurScope
= nullptr;
475 // Free the scope cache.
476 for (unsigned i
= 0, e
= NumCachedScopes
; i
!= e
; ++i
)
477 delete ScopeCache
[i
];
479 resetPragmaHandlers();
481 PP
.removeCommentHandler(CommentSemaHandler
.get());
483 PP
.clearCodeCompletionHandler();
485 DestroyTemplateIds();
488 /// Initialize - Warm up the parser.
490 void Parser::Initialize() {
491 // Create the translation unit scope. Install it as the current scope.
492 assert(getCurScope() == nullptr && "A scope is already active?");
493 EnterScope(Scope::DeclScope
);
494 Actions
.ActOnTranslationUnitScope(getCurScope());
496 // Initialization for Objective-C context sensitive keywords recognition.
497 // Referenced in Parser::ParseObjCTypeQualifierList.
498 if (getLangOpts().ObjC
) {
499 ObjCTypeQuals
[objc_in
] = &PP
.getIdentifierTable().get("in");
500 ObjCTypeQuals
[objc_out
] = &PP
.getIdentifierTable().get("out");
501 ObjCTypeQuals
[objc_inout
] = &PP
.getIdentifierTable().get("inout");
502 ObjCTypeQuals
[objc_oneway
] = &PP
.getIdentifierTable().get("oneway");
503 ObjCTypeQuals
[objc_bycopy
] = &PP
.getIdentifierTable().get("bycopy");
504 ObjCTypeQuals
[objc_byref
] = &PP
.getIdentifierTable().get("byref");
505 ObjCTypeQuals
[objc_nonnull
] = &PP
.getIdentifierTable().get("nonnull");
506 ObjCTypeQuals
[objc_nullable
] = &PP
.getIdentifierTable().get("nullable");
507 ObjCTypeQuals
[objc_null_unspecified
]
508 = &PP
.getIdentifierTable().get("null_unspecified");
511 Ident_instancetype
= nullptr;
512 Ident_final
= nullptr;
513 Ident_sealed
= nullptr;
514 Ident_abstract
= nullptr;
515 Ident_override
= nullptr;
516 Ident_GNU_final
= nullptr;
517 Ident_import
= nullptr;
518 Ident_module
= nullptr;
520 Ident_super
= &PP
.getIdentifierTable().get("super");
522 Ident_vector
= nullptr;
523 Ident_bool
= nullptr;
524 Ident_Bool
= nullptr;
525 Ident_pixel
= nullptr;
526 if (getLangOpts().AltiVec
|| getLangOpts().ZVector
) {
527 Ident_vector
= &PP
.getIdentifierTable().get("vector");
528 Ident_bool
= &PP
.getIdentifierTable().get("bool");
529 Ident_Bool
= &PP
.getIdentifierTable().get("_Bool");
531 if (getLangOpts().AltiVec
)
532 Ident_pixel
= &PP
.getIdentifierTable().get("pixel");
534 Ident_introduced
= nullptr;
535 Ident_deprecated
= nullptr;
536 Ident_obsoleted
= nullptr;
537 Ident_unavailable
= nullptr;
538 Ident_strict
= nullptr;
539 Ident_replacement
= nullptr;
541 Ident_language
= Ident_defined_in
= Ident_generated_declaration
= Ident_USR
=
544 Ident__except
= nullptr;
546 Ident__exception_code
= Ident__exception_info
= nullptr;
547 Ident__abnormal_termination
= Ident___exception_code
= nullptr;
548 Ident___exception_info
= Ident___abnormal_termination
= nullptr;
549 Ident_GetExceptionCode
= Ident_GetExceptionInfo
= nullptr;
550 Ident_AbnormalTermination
= nullptr;
552 if(getLangOpts().Borland
) {
553 Ident__exception_info
= PP
.getIdentifierInfo("_exception_info");
554 Ident___exception_info
= PP
.getIdentifierInfo("__exception_info");
555 Ident_GetExceptionInfo
= PP
.getIdentifierInfo("GetExceptionInformation");
556 Ident__exception_code
= PP
.getIdentifierInfo("_exception_code");
557 Ident___exception_code
= PP
.getIdentifierInfo("__exception_code");
558 Ident_GetExceptionCode
= PP
.getIdentifierInfo("GetExceptionCode");
559 Ident__abnormal_termination
= PP
.getIdentifierInfo("_abnormal_termination");
560 Ident___abnormal_termination
= PP
.getIdentifierInfo("__abnormal_termination");
561 Ident_AbnormalTermination
= PP
.getIdentifierInfo("AbnormalTermination");
563 PP
.SetPoisonReason(Ident__exception_code
,diag::err_seh___except_block
);
564 PP
.SetPoisonReason(Ident___exception_code
,diag::err_seh___except_block
);
565 PP
.SetPoisonReason(Ident_GetExceptionCode
,diag::err_seh___except_block
);
566 PP
.SetPoisonReason(Ident__exception_info
,diag::err_seh___except_filter
);
567 PP
.SetPoisonReason(Ident___exception_info
,diag::err_seh___except_filter
);
568 PP
.SetPoisonReason(Ident_GetExceptionInfo
,diag::err_seh___except_filter
);
569 PP
.SetPoisonReason(Ident__abnormal_termination
,diag::err_seh___finally_block
);
570 PP
.SetPoisonReason(Ident___abnormal_termination
,diag::err_seh___finally_block
);
571 PP
.SetPoisonReason(Ident_AbnormalTermination
,diag::err_seh___finally_block
);
574 if (getLangOpts().CPlusPlusModules
) {
575 Ident_import
= PP
.getIdentifierInfo("import");
576 Ident_module
= PP
.getIdentifierInfo("module");
579 Actions
.Initialize();
581 // Prime the lexer look-ahead.
585 void Parser::DestroyTemplateIds() {
586 for (TemplateIdAnnotation
*Id
: TemplateIds
)
591 /// Parse the first top-level declaration in a translation unit.
593 /// translation-unit:
594 /// [C] external-declaration
595 /// [C] translation-unit external-declaration
596 /// [C++] top-level-declaration-seq[opt]
597 /// [C++20] global-module-fragment[opt] module-declaration
598 /// top-level-declaration-seq[opt] private-module-fragment[opt]
600 /// Note that in C, it is an error if there is no first declaration.
601 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy
&Result
,
602 Sema::ModuleImportState
&ImportState
) {
603 Actions
.ActOnStartOfTranslationUnit();
605 // For C++20 modules, a module decl must be the first in the TU. We also
606 // need to track module imports.
607 ImportState
= Sema::ModuleImportState::FirstDecl
;
608 bool NoTopLevelDecls
= ParseTopLevelDecl(Result
, ImportState
);
610 // C11 6.9p1 says translation units must have at least one top-level
611 // declaration. C++ doesn't have this restriction. We also don't want to
612 // complain if we have a precompiled header, although technically if the PCH
613 // is empty we should still emit the (pedantic) diagnostic.
614 // If the main file is a header, we're only pretending it's a TU; don't warn.
615 if (NoTopLevelDecls
&& !Actions
.getASTContext().getExternalSource() &&
616 !getLangOpts().CPlusPlus
&& !getLangOpts().IsHeaderFile
)
617 Diag(diag::ext_empty_translation_unit
);
619 return NoTopLevelDecls
;
622 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
623 /// action tells us to. This returns true if the EOF was encountered.
625 /// top-level-declaration:
627 /// [C++20] module-import-declaration
628 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy
&Result
,
629 Sema::ModuleImportState
&ImportState
) {
630 DestroyTemplateIdAnnotationsRAIIObj
CleanupRAII(*this);
633 switch (Tok
.getKind()) {
634 case tok::annot_pragma_unused
:
635 HandlePragmaUnused();
639 switch (NextToken().getKind()) {
643 // Note: no need to handle kw_import here. We only form kw_import under
644 // the Standard C++ Modules, and in that case 'export import' is parsed as
645 // an export-declaration containing an import-declaration.
647 // Recognize context-sensitive C++20 'export module' and 'export import'
649 case tok::identifier
: {
650 IdentifierInfo
*II
= NextToken().getIdentifierInfo();
651 if ((II
== Ident_module
|| II
== Ident_import
) &&
652 GetLookAheadToken(2).isNot(tok::coloncolon
)) {
653 if (II
== Ident_module
)
668 Result
= ParseModuleDecl(ImportState
);
673 Decl
*ImportDecl
= ParseModuleImport(SourceLocation(), ImportState
);
674 Result
= Actions
.ConvertDeclToDeclGroup(ImportDecl
);
678 case tok::annot_module_include
: {
679 auto Loc
= Tok
.getLocation();
680 Module
*Mod
= reinterpret_cast<Module
*>(Tok
.getAnnotationValue());
681 // FIXME: We need a better way to disambiguate C++ clang modules and
682 // standard C++ modules.
683 if (!getLangOpts().CPlusPlusModules
|| !Mod
->isHeaderUnit())
684 Actions
.ActOnAnnotModuleInclude(Loc
, Mod
);
687 Actions
.ActOnModuleImport(Loc
, SourceLocation(), Loc
, Mod
);
688 Decl
*ImportDecl
= Import
.isInvalid() ? nullptr : Import
.get();
689 Result
= Actions
.ConvertDeclToDeclGroup(ImportDecl
);
691 ConsumeAnnotationToken();
695 case tok::annot_module_begin
:
696 Actions
.ActOnAnnotModuleBegin(
698 reinterpret_cast<Module
*>(Tok
.getAnnotationValue()));
699 ConsumeAnnotationToken();
700 ImportState
= Sema::ModuleImportState::NotACXX20Module
;
703 case tok::annot_module_end
:
704 Actions
.ActOnAnnotModuleEnd(
706 reinterpret_cast<Module
*>(Tok
.getAnnotationValue()));
707 ConsumeAnnotationToken();
708 ImportState
= Sema::ModuleImportState::NotACXX20Module
;
712 case tok::annot_repl_input_end
:
713 // Check whether -fmax-tokens= was reached.
714 if (PP
.getMaxTokens() != 0 && PP
.getTokenCount() > PP
.getMaxTokens()) {
715 PP
.Diag(Tok
.getLocation(), diag::warn_max_tokens_total
)
716 << PP
.getTokenCount() << PP
.getMaxTokens();
717 SourceLocation OverrideLoc
= PP
.getMaxTokensOverrideLoc();
718 if (OverrideLoc
.isValid()) {
719 PP
.Diag(OverrideLoc
, diag::note_max_tokens_total_override
);
723 // Late template parsing can begin.
724 Actions
.SetLateTemplateParser(LateTemplateParserCallback
, nullptr, this);
725 Actions
.ActOnEndOfTranslationUnit();
726 //else don't tell Sema that we ended parsing: more input might come.
729 case tok::identifier
:
730 // C++2a [basic.link]p3:
731 // A token sequence beginning with 'export[opt] module' or
732 // 'export[opt] import' and not immediately followed by '::'
733 // is never interpreted as the declaration of a top-level-declaration.
734 if ((Tok
.getIdentifierInfo() == Ident_module
||
735 Tok
.getIdentifierInfo() == Ident_import
) &&
736 NextToken().isNot(tok::coloncolon
)) {
737 if (Tok
.getIdentifierInfo() == Ident_module
)
748 ParsedAttributes
DeclAttrs(AttrFactory
);
749 ParsedAttributes
DeclSpecAttrs(AttrFactory
);
750 // GNU attributes are applied to the declaration specification while the
751 // standard attributes are applied to the declaration. We parse the two
752 // attribute sets into different containters so we can apply them during
753 // the regular parsing process.
754 while (MaybeParseCXX11Attributes(DeclAttrs
) ||
755 MaybeParseGNUAttributes(DeclSpecAttrs
))
758 Result
= ParseExternalDeclaration(DeclAttrs
, DeclSpecAttrs
);
759 // An empty Result might mean a line with ';' or some parsing error, ignore
762 if (ImportState
== Sema::ModuleImportState::FirstDecl
)
763 // First decl was not modular.
764 ImportState
= Sema::ModuleImportState::NotACXX20Module
;
765 else if (ImportState
== Sema::ModuleImportState::ImportAllowed
)
766 // Non-imports disallow further imports.
767 ImportState
= Sema::ModuleImportState::ImportFinished
;
768 else if (ImportState
==
769 Sema::ModuleImportState::PrivateFragmentImportAllowed
)
770 // Non-imports disallow further imports.
771 ImportState
= Sema::ModuleImportState::PrivateFragmentImportFinished
;
776 /// ParseExternalDeclaration:
778 /// The `Attrs` that are passed in are C++11 attributes and appertain to the
781 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
782 /// function-definition
784 /// [GNU] asm-definition
785 /// [GNU] __extension__ external-declaration
786 /// [OBJC] objc-class-definition
787 /// [OBJC] objc-class-declaration
788 /// [OBJC] objc-alias-declaration
789 /// [OBJC] objc-protocol-definition
790 /// [OBJC] objc-method-definition
792 /// [C++] linkage-specification
793 /// [GNU] asm-definition:
794 /// simple-asm-expr ';'
795 /// [C++11] empty-declaration
796 /// [C++11] attribute-declaration
798 /// [C++11] empty-declaration:
801 /// [C++0x/GNU] 'extern' 'template' declaration
803 /// [C++20] module-import-declaration
805 Parser::DeclGroupPtrTy
806 Parser::ParseExternalDeclaration(ParsedAttributes
&Attrs
,
807 ParsedAttributes
&DeclSpecAttrs
,
808 ParsingDeclSpec
*DS
) {
809 DestroyTemplateIdAnnotationsRAIIObj
CleanupRAII(*this);
810 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
812 if (PP
.isCodeCompletionReached()) {
817 Decl
*SingleDecl
= nullptr;
818 switch (Tok
.getKind()) {
819 case tok::annot_pragma_vis
:
820 HandlePragmaVisibility();
822 case tok::annot_pragma_pack
:
825 case tok::annot_pragma_msstruct
:
826 HandlePragmaMSStruct();
828 case tok::annot_pragma_align
:
831 case tok::annot_pragma_weak
:
834 case tok::annot_pragma_weakalias
:
835 HandlePragmaWeakAlias();
837 case tok::annot_pragma_redefine_extname
:
838 HandlePragmaRedefineExtname();
840 case tok::annot_pragma_fp_contract
:
841 HandlePragmaFPContract();
843 case tok::annot_pragma_fenv_access
:
844 case tok::annot_pragma_fenv_access_ms
:
845 HandlePragmaFEnvAccess();
847 case tok::annot_pragma_fenv_round
:
848 HandlePragmaFEnvRound();
850 case tok::annot_pragma_cx_limited_range
:
851 HandlePragmaCXLimitedRange();
853 case tok::annot_pragma_float_control
:
854 HandlePragmaFloatControl();
856 case tok::annot_pragma_fp
:
859 case tok::annot_pragma_opencl_extension
:
860 HandlePragmaOpenCLExtension();
862 case tok::annot_attr_openmp
:
863 case tok::annot_pragma_openmp
: {
864 AccessSpecifier AS
= AS_none
;
865 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS
, Attrs
);
867 case tok::annot_pragma_openacc
:
868 return ParseOpenACCDirectiveDecl();
869 case tok::annot_pragma_ms_pointers_to_members
:
870 HandlePragmaMSPointersToMembers();
872 case tok::annot_pragma_ms_vtordisp
:
873 HandlePragmaMSVtorDisp();
875 case tok::annot_pragma_ms_pragma
:
876 HandlePragmaMSPragma();
878 case tok::annot_pragma_dump
:
881 case tok::annot_pragma_attribute
:
882 HandlePragmaAttribute();
885 // Either a C++11 empty-declaration or attribute-declaration.
887 Actions
.ActOnEmptyDeclaration(getCurScope(), Attrs
, Tok
.getLocation());
888 ConsumeExtraSemi(OutsideFunction
);
891 Diag(Tok
, diag::err_extraneous_closing_brace
);
895 Diag(Tok
, diag::err_expected_external_declaration
);
897 case tok::kw___extension__
: {
898 // __extension__ silences extension warnings in the subexpression.
899 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
901 return ParseExternalDeclaration(Attrs
, DeclSpecAttrs
);
904 ProhibitAttributes(Attrs
);
906 SourceLocation StartLoc
= Tok
.getLocation();
907 SourceLocation EndLoc
;
909 ExprResult
Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc
));
911 // Check if GNU-style InlineAsm is disabled.
912 // Empty asm string is allowed because it will not introduce
913 // any assembly code.
914 if (!(getLangOpts().GNUAsm
|| Result
.isInvalid())) {
915 const auto *SL
= cast
<StringLiteral
>(Result
.get());
916 if (!SL
->getString().trim().empty())
917 Diag(StartLoc
, diag::err_gnu_inline_asm_disabled
);
920 ExpectAndConsume(tok::semi
, diag::err_expected_after
,
921 "top-level asm block");
923 if (Result
.isInvalid())
925 SingleDecl
= Actions
.ActOnFileScopeAsmDecl(Result
.get(), StartLoc
, EndLoc
);
929 return ParseObjCAtDirectives(Attrs
, DeclSpecAttrs
);
932 if (!getLangOpts().ObjC
) {
933 Diag(Tok
, diag::err_expected_external_declaration
);
937 SingleDecl
= ParseObjCMethodDefinition();
939 case tok::code_completion
:
941 if (CurParsedObjCImpl
) {
942 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
943 Actions
.CodeCompletion().CodeCompleteObjCMethodDecl(
945 /*IsInstanceMethod=*/std::nullopt
,
946 /*ReturnType=*/nullptr);
949 SemaCodeCompletion::ParserCompletionContext PCC
;
950 if (CurParsedObjCImpl
) {
951 PCC
= SemaCodeCompletion::PCC_ObjCImplementation
;
952 } else if (PP
.isIncrementalProcessingEnabled()) {
953 PCC
= SemaCodeCompletion::PCC_TopLevelOrExpression
;
955 PCC
= SemaCodeCompletion::PCC_Namespace
;
957 Actions
.CodeCompletion().CodeCompleteOrdinaryName(getCurScope(), PCC
);
959 case tok::kw_import
: {
960 Sema::ModuleImportState IS
= Sema::ModuleImportState::NotACXX20Module
;
961 if (getLangOpts().CPlusPlusModules
) {
962 llvm_unreachable("not expecting a c++20 import here");
963 ProhibitAttributes(Attrs
);
965 SingleDecl
= ParseModuleImport(SourceLocation(), IS
);
968 if (getLangOpts().CPlusPlusModules
|| getLangOpts().HLSL
) {
969 ProhibitAttributes(Attrs
);
970 SingleDecl
= ParseExportDeclaration();
973 // This must be 'export template'. Parse it so we can diagnose our lack
977 case tok::kw_namespace
:
978 case tok::kw_typedef
:
979 case tok::kw_template
:
980 case tok::kw_static_assert
:
981 case tok::kw__Static_assert
:
982 // A function definition cannot start with any of these keywords.
984 SourceLocation DeclEnd
;
985 return ParseDeclaration(DeclaratorContext::File
, DeclEnd
, Attrs
,
989 case tok::kw_cbuffer
:
990 case tok::kw_tbuffer
:
991 if (getLangOpts().HLSL
) {
992 SourceLocation DeclEnd
;
993 return ParseDeclaration(DeclaratorContext::File
, DeclEnd
, Attrs
,
999 // Parse (then ignore) 'static' prior to a template instantiation. This is
1000 // a GCC extension that we intentionally do not support.
1001 if (getLangOpts().CPlusPlus
&& NextToken().is(tok::kw_template
)) {
1002 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored
)
1004 SourceLocation DeclEnd
;
1005 return ParseDeclaration(DeclaratorContext::File
, DeclEnd
, Attrs
,
1010 case tok::kw_inline
:
1011 if (getLangOpts().CPlusPlus
) {
1012 tok::TokenKind NextKind
= NextToken().getKind();
1014 // Inline namespaces. Allowed as an extension even in C++03.
1015 if (NextKind
== tok::kw_namespace
) {
1016 SourceLocation DeclEnd
;
1017 return ParseDeclaration(DeclaratorContext::File
, DeclEnd
, Attrs
,
1021 // Parse (then ignore) 'inline' prior to a template instantiation. This is
1022 // a GCC extension that we intentionally do not support.
1023 if (NextKind
== tok::kw_template
) {
1024 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored
)
1026 SourceLocation DeclEnd
;
1027 return ParseDeclaration(DeclaratorContext::File
, DeclEnd
, Attrs
,
1033 case tok::kw_extern
:
1034 if (getLangOpts().CPlusPlus
&& NextToken().is(tok::kw_template
)) {
1036 SourceLocation ExternLoc
= ConsumeToken();
1037 SourceLocation TemplateLoc
= ConsumeToken();
1038 Diag(ExternLoc
, getLangOpts().CPlusPlus11
?
1039 diag::warn_cxx98_compat_extern_template
:
1040 diag::ext_extern_template
) << SourceRange(ExternLoc
, TemplateLoc
);
1041 SourceLocation DeclEnd
;
1042 return ParseExplicitInstantiation(DeclaratorContext::File
, ExternLoc
,
1043 TemplateLoc
, DeclEnd
, Attrs
);
1047 case tok::kw___if_exists
:
1048 case tok::kw___if_not_exists
:
1049 ParseMicrosoftIfExistsExternalDeclaration();
1052 case tok::kw_module
:
1053 Diag(Tok
, diag::err_unexpected_module_decl
);
1054 SkipUntil(tok::semi
);
1059 if (Tok
.isEditorPlaceholder()) {
1063 if (getLangOpts().IncrementalExtensions
&&
1064 !isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
1065 return ParseTopLevelStmtDecl();
1067 // We can't tell whether this is a function-definition or declaration yet.
1069 return ParseDeclarationOrFunctionDefinition(Attrs
, DeclSpecAttrs
, DS
);
1072 // This routine returns a DeclGroup, if the thing we parsed only contains a
1073 // single decl, convert it now.
1074 return Actions
.ConvertDeclToDeclGroup(SingleDecl
);
1077 /// Determine whether the current token, if it occurs after a
1078 /// declarator, continues a declaration or declaration list.
1079 bool Parser::isDeclarationAfterDeclarator() {
1080 // Check for '= delete' or '= default'
1081 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::equal
)) {
1082 const Token
&KW
= NextToken();
1083 if (KW
.is(tok::kw_default
) || KW
.is(tok::kw_delete
))
1087 return Tok
.is(tok::equal
) || // int X()= -> not a function def
1088 Tok
.is(tok::comma
) || // int X(), -> not a function def
1089 Tok
.is(tok::semi
) || // int X(); -> not a function def
1090 Tok
.is(tok::kw_asm
) || // int X() __asm__ -> not a function def
1091 Tok
.is(tok::kw___attribute
) || // int X() __attr__ -> not a function def
1092 (getLangOpts().CPlusPlus
&&
1093 Tok
.is(tok::l_paren
)); // int X(0) -> not a function def [C++]
1096 /// Determine whether the current token, if it occurs after a
1097 /// declarator, indicates the start of a function definition.
1098 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator
&Declarator
) {
1099 assert(Declarator
.isFunctionDeclarator() && "Isn't a function declarator");
1100 if (Tok
.is(tok::l_brace
)) // int X() {}
1103 // Handle K&R C argument lists: int X(f) int f; {}
1104 if (!getLangOpts().CPlusPlus
&&
1105 Declarator
.getFunctionTypeInfo().isKNRPrototype())
1106 return isDeclarationSpecifier(ImplicitTypenameContext::No
);
1108 if (getLangOpts().CPlusPlus
&& Tok
.is(tok::equal
)) {
1109 const Token
&KW
= NextToken();
1110 return KW
.is(tok::kw_default
) || KW
.is(tok::kw_delete
);
1113 return Tok
.is(tok::colon
) || // X() : Base() {} (used for ctors)
1114 Tok
.is(tok::kw_try
); // X() try { ... }
1117 /// Parse either a function-definition or a declaration. We can't tell which
1118 /// we have until we read up to the compound-statement in function-definition.
1119 /// TemplateParams, if non-NULL, provides the template parameters when we're
1120 /// parsing a C++ template-declaration.
1122 /// function-definition: [C99 6.9.1]
1123 /// decl-specs declarator declaration-list[opt] compound-statement
1124 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1125 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1127 /// declaration: [C99 6.7]
1128 /// declaration-specifiers init-declarator-list[opt] ';'
1129 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
1130 /// [OMP] threadprivate-directive
1131 /// [OMP] allocate-directive [TODO]
1133 Parser::DeclGroupPtrTy
Parser::ParseDeclOrFunctionDefInternal(
1134 ParsedAttributes
&Attrs
, ParsedAttributes
&DeclSpecAttrs
,
1135 ParsingDeclSpec
&DS
, AccessSpecifier AS
) {
1136 // Because we assume that the DeclSpec has not yet been initialised, we simply
1137 // overwrite the source range and attribute the provided leading declspec
1139 assert(DS
.getSourceRange().isInvalid() &&
1140 "expected uninitialised source range");
1141 DS
.SetRangeStart(DeclSpecAttrs
.Range
.getBegin());
1142 DS
.SetRangeEnd(DeclSpecAttrs
.Range
.getEnd());
1143 DS
.takeAttributesFrom(DeclSpecAttrs
);
1145 ParsedTemplateInfo TemplateInfo
;
1146 MaybeParseMicrosoftAttributes(DS
.getAttributes());
1147 // Parse the common declaration-specifiers piece.
1148 ParseDeclarationSpecifiers(DS
, TemplateInfo
, AS
,
1149 DeclSpecContext::DSC_top_level
);
1151 // If we had a free-standing type definition with a missing semicolon, we
1152 // may get this far before the problem becomes obvious.
1153 if (DS
.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1154 DS
, AS
, DeclSpecContext::DSC_top_level
))
1157 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1158 // declaration-specifiers init-declarator-list[opt] ';'
1159 if (Tok
.is(tok::semi
)) {
1160 auto LengthOfTSTToken
= [](DeclSpec::TST TKind
) {
1161 assert(DeclSpec::isDeclRep(TKind
));
1163 case DeclSpec::TST_class
:
1165 case DeclSpec::TST_struct
:
1167 case DeclSpec::TST_union
:
1169 case DeclSpec::TST_enum
:
1171 case DeclSpec::TST_interface
:
1174 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1178 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1179 SourceLocation CorrectLocationForAttributes
=
1180 DeclSpec::isDeclRep(DS
.getTypeSpecType())
1181 ? DS
.getTypeSpecTypeLoc().getLocWithOffset(
1182 LengthOfTSTToken(DS
.getTypeSpecType()))
1184 ProhibitAttributes(Attrs
, CorrectLocationForAttributes
);
1186 RecordDecl
*AnonRecord
= nullptr;
1187 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(
1188 getCurScope(), AS_none
, DS
, ParsedAttributesView::none(), AnonRecord
);
1189 DS
.complete(TheDecl
);
1190 Actions
.ActOnDefinedDeclarationSpecifier(TheDecl
);
1192 Decl
* decls
[] = {AnonRecord
, TheDecl
};
1193 return Actions
.BuildDeclaratorGroup(decls
);
1195 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
1198 if (DS
.hasTagDefinition())
1199 Actions
.ActOnDefinedDeclarationSpecifier(DS
.getRepAsDecl());
1201 // ObjC2 allows prefix attributes on class interfaces and protocols.
1202 // FIXME: This still needs better diagnostics. We should only accept
1203 // attributes here, no types, etc.
1204 if (getLangOpts().ObjC
&& Tok
.is(tok::at
)) {
1205 SourceLocation AtLoc
= ConsumeToken(); // the "@"
1206 if (!Tok
.isObjCAtKeyword(tok::objc_interface
) &&
1207 !Tok
.isObjCAtKeyword(tok::objc_protocol
) &&
1208 !Tok
.isObjCAtKeyword(tok::objc_implementation
)) {
1209 Diag(Tok
, diag::err_objc_unexpected_attr
);
1210 SkipUntil(tok::semi
);
1215 DS
.takeAttributesFrom(Attrs
);
1217 const char *PrevSpec
= nullptr;
1219 if (DS
.SetTypeSpecType(DeclSpec::TST_unspecified
, AtLoc
, PrevSpec
, DiagID
,
1220 Actions
.getASTContext().getPrintingPolicy()))
1221 Diag(AtLoc
, DiagID
) << PrevSpec
;
1223 if (Tok
.isObjCAtKeyword(tok::objc_protocol
))
1224 return ParseObjCAtProtocolDeclaration(AtLoc
, DS
.getAttributes());
1226 if (Tok
.isObjCAtKeyword(tok::objc_implementation
))
1227 return ParseObjCAtImplementationDeclaration(AtLoc
, DS
.getAttributes());
1229 return Actions
.ConvertDeclToDeclGroup(
1230 ParseObjCAtInterfaceDeclaration(AtLoc
, DS
.getAttributes()));
1233 // If the declspec consisted only of 'extern' and we have a string
1234 // literal following it, this must be a C++ linkage specifier like
1236 if (getLangOpts().CPlusPlus
&& isTokenStringLiteral() &&
1237 DS
.getStorageClassSpec() == DeclSpec::SCS_extern
&&
1238 DS
.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier
) {
1239 ProhibitAttributes(Attrs
);
1240 Decl
*TheDecl
= ParseLinkage(DS
, DeclaratorContext::File
);
1241 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
1244 return ParseDeclGroup(DS
, DeclaratorContext::File
, Attrs
, TemplateInfo
);
1247 Parser::DeclGroupPtrTy
Parser::ParseDeclarationOrFunctionDefinition(
1248 ParsedAttributes
&Attrs
, ParsedAttributes
&DeclSpecAttrs
,
1249 ParsingDeclSpec
*DS
, AccessSpecifier AS
) {
1250 // Add an enclosing time trace scope for a bunch of small scopes with
1251 // "EvaluateAsConstExpr".
1252 llvm::TimeTraceScope
TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {
1253 return Tok
.getLocation().printToString(
1254 Actions
.getASTContext().getSourceManager());
1258 return ParseDeclOrFunctionDefInternal(Attrs
, DeclSpecAttrs
, *DS
, AS
);
1260 ParsingDeclSpec
PDS(*this);
1261 // Must temporarily exit the objective-c container scope for
1262 // parsing c constructs and re-enter objc container scope
1264 ObjCDeclContextSwitch
ObjCDC(*this);
1266 return ParseDeclOrFunctionDefInternal(Attrs
, DeclSpecAttrs
, PDS
, AS
);
1270 /// ParseFunctionDefinition - We parsed and verified that the specified
1271 /// Declarator is well formed. If this is a K&R-style function, read the
1272 /// parameters declaration-list, then start the compound-statement.
1274 /// function-definition: [C99 6.9.1]
1275 /// decl-specs declarator declaration-list[opt] compound-statement
1276 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1277 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1278 /// [C++] function-definition: [C++ 8.4]
1279 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1281 /// [C++] function-definition: [C++ 8.4]
1282 /// decl-specifier-seq[opt] declarator function-try-block
1284 Decl
*Parser::ParseFunctionDefinition(ParsingDeclarator
&D
,
1285 const ParsedTemplateInfo
&TemplateInfo
,
1286 LateParsedAttrList
*LateParsedAttrs
) {
1287 llvm::TimeTraceScope
TimeScope("ParseFunctionDefinition", [&]() {
1288 return Actions
.GetNameForDeclarator(D
).getName().getAsString();
1291 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1292 PoisonSEHIdentifiersRAIIObject
PoisonSEHIdentifiers(*this, true);
1293 const DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
1294 TemplateParameterDepthRAII
CurTemplateDepthTracker(TemplateParameterDepth
);
1296 // If this is C89 and the declspecs were completely missing, fudge in an
1297 // implicit int. We do this here because this is the only place where
1298 // declaration-specifiers are completely optional in the grammar.
1299 if (getLangOpts().isImplicitIntRequired() && D
.getDeclSpec().isEmpty()) {
1300 Diag(D
.getIdentifierLoc(), diag::warn_missing_type_specifier
)
1301 << D
.getDeclSpec().getSourceRange();
1302 const char *PrevSpec
;
1304 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
1305 D
.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int
,
1306 D
.getIdentifierLoc(),
1309 D
.SetRangeBegin(D
.getDeclSpec().getSourceRange().getBegin());
1312 // If this declaration was formed with a K&R-style identifier list for the
1313 // arguments, parse declarations for all of the args next.
1314 // int foo(a,b) int a; float b; {}
1315 if (FTI
.isKNRPrototype())
1316 ParseKNRParamDeclarations(D
);
1318 // We should have either an opening brace or, in a C++ constructor,
1319 // we may have a colon.
1320 if (Tok
.isNot(tok::l_brace
) &&
1321 (!getLangOpts().CPlusPlus
||
1322 (Tok
.isNot(tok::colon
) && Tok
.isNot(tok::kw_try
) &&
1323 Tok
.isNot(tok::equal
)))) {
1324 Diag(Tok
, diag::err_expected_fn_body
);
1326 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1327 SkipUntil(tok::l_brace
, StopAtSemi
| StopBeforeMatch
);
1329 // If we didn't find the '{', bail out.
1330 if (Tok
.isNot(tok::l_brace
))
1334 // Check to make sure that any normal attributes are allowed to be on
1335 // a definition. Late parsed attributes are checked at the end.
1336 if (Tok
.isNot(tok::equal
)) {
1337 for (const ParsedAttr
&AL
: D
.getAttributes())
1338 if (AL
.isKnownToGCC() && !AL
.isStandardAttributeSyntax())
1339 Diag(AL
.getLoc(), diag::warn_attribute_on_function_definition
) << AL
;
1342 // In delayed template parsing mode, for function template we consume the
1343 // tokens and store them for late parsing at the end of the translation unit.
1344 if (getLangOpts().DelayedTemplateParsing
&& Tok
.isNot(tok::equal
) &&
1345 TemplateInfo
.Kind
== ParsedTemplateInfo::Template
&&
1346 Actions
.canDelayFunctionBody(D
)) {
1347 MultiTemplateParamsArg
TemplateParameterLists(*TemplateInfo
.TemplateParams
);
1349 ParseScope
BodyScope(this, Scope::FnScope
| Scope::DeclScope
|
1350 Scope::CompoundStmtScope
);
1351 Scope
*ParentScope
= getCurScope()->getParent();
1353 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
1354 Decl
*DP
= Actions
.HandleDeclarator(ParentScope
, D
,
1355 TemplateParameterLists
);
1357 D
.getMutableDeclSpec().abort();
1359 if (SkipFunctionBodies
&& (!DP
|| Actions
.canSkipFunctionBody(DP
)) &&
1360 trySkippingFunctionBody()) {
1362 return Actions
.ActOnSkippedFunctionBody(DP
);
1366 LexTemplateFunctionForLateParsing(Toks
);
1369 FunctionDecl
*FnD
= DP
->getAsFunction();
1370 Actions
.CheckForFunctionRedefinition(FnD
);
1371 Actions
.MarkAsLateParsedTemplate(FnD
, DP
, Toks
);
1375 else if (CurParsedObjCImpl
&&
1376 !TemplateInfo
.TemplateParams
&&
1377 (Tok
.is(tok::l_brace
) || Tok
.is(tok::kw_try
) ||
1378 Tok
.is(tok::colon
)) &&
1379 Actions
.CurContext
->isTranslationUnit()) {
1380 ParseScope
BodyScope(this, Scope::FnScope
| Scope::DeclScope
|
1381 Scope::CompoundStmtScope
);
1382 Scope
*ParentScope
= getCurScope()->getParent();
1384 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
1385 Decl
*FuncDecl
= Actions
.HandleDeclarator(ParentScope
, D
,
1386 MultiTemplateParamsArg());
1387 D
.complete(FuncDecl
);
1388 D
.getMutableDeclSpec().abort();
1390 // Consume the tokens and store them for later parsing.
1391 StashAwayMethodOrFunctionBodyTokens(FuncDecl
);
1392 CurParsedObjCImpl
->HasCFunction
= true;
1395 // FIXME: Should we really fall through here?
1398 // Enter a scope for the function body.
1399 ParseScope
BodyScope(this, Scope::FnScope
| Scope::DeclScope
|
1400 Scope::CompoundStmtScope
);
1402 // Parse function body eagerly if it is either '= delete;' or '= default;' as
1403 // ActOnStartOfFunctionDef needs to know whether the function is deleted.
1404 StringLiteral
*DeletedMessage
= nullptr;
1405 Sema::FnBodyKind BodyKind
= Sema::FnBodyKind::Other
;
1406 SourceLocation KWLoc
;
1407 if (TryConsumeToken(tok::equal
)) {
1408 assert(getLangOpts().CPlusPlus
&& "Only C++ function definitions have '='");
1410 if (TryConsumeToken(tok::kw_delete
, KWLoc
)) {
1411 Diag(KWLoc
, getLangOpts().CPlusPlus11
1412 ? diag::warn_cxx98_compat_defaulted_deleted_function
1413 : diag::ext_defaulted_deleted_function
)
1415 BodyKind
= Sema::FnBodyKind::Delete
;
1416 DeletedMessage
= ParseCXXDeletedFunctionMessage();
1417 } else if (TryConsumeToken(tok::kw_default
, KWLoc
)) {
1418 Diag(KWLoc
, getLangOpts().CPlusPlus11
1419 ? diag::warn_cxx98_compat_defaulted_deleted_function
1420 : diag::ext_defaulted_deleted_function
)
1421 << 0 /* defaulted */;
1422 BodyKind
= Sema::FnBodyKind::Default
;
1424 llvm_unreachable("function definition after = not 'delete' or 'default'");
1427 if (Tok
.is(tok::comma
)) {
1428 Diag(KWLoc
, diag::err_default_delete_in_multiple_declaration
)
1429 << (BodyKind
== Sema::FnBodyKind::Delete
);
1430 SkipUntil(tok::semi
);
1431 } else if (ExpectAndConsume(tok::semi
, diag::err_expected_after
,
1432 BodyKind
== Sema::FnBodyKind::Delete
1435 SkipUntil(tok::semi
);
1439 Sema::FPFeaturesStateRAII
SaveFPFeatures(Actions
);
1441 // Tell the actions module that we have entered a function definition with the
1442 // specified Declarator for the function.
1443 SkipBodyInfo SkipBody
;
1444 Decl
*Res
= Actions
.ActOnStartOfFunctionDef(getCurScope(), D
,
1445 TemplateInfo
.TemplateParams
1446 ? *TemplateInfo
.TemplateParams
1447 : MultiTemplateParamsArg(),
1448 &SkipBody
, BodyKind
);
1450 if (SkipBody
.ShouldSkip
) {
1451 // Do NOT enter SkipFunctionBody if we already consumed the tokens.
1452 if (BodyKind
== Sema::FnBodyKind::Other
)
1455 // ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef
1456 // and it would be popped in ActOnFinishFunctionBody.
1457 // We pop it explcitly here since ActOnFinishFunctionBody won't get called.
1459 // Do not call PopExpressionEvaluationContext() if it is a lambda because
1460 // one is already popped when finishing the lambda in BuildLambdaExpr().
1462 // FIXME: It looks not easy to balance PushExpressionEvaluationContext()
1463 // and PopExpressionEvaluationContext().
1464 if (!isLambdaCallOperator(dyn_cast_if_present
<FunctionDecl
>(Res
)))
1465 Actions
.PopExpressionEvaluationContext();
1469 // Break out of the ParsingDeclarator context before we parse the body.
1472 // Break out of the ParsingDeclSpec context, too. This const_cast is
1473 // safe because we're always the sole owner.
1474 D
.getMutableDeclSpec().abort();
1476 if (BodyKind
!= Sema::FnBodyKind::Other
) {
1477 Actions
.SetFunctionBodyKind(Res
, KWLoc
, BodyKind
, DeletedMessage
);
1478 Stmt
*GeneratedBody
= Res
? Res
->getBody() : nullptr;
1479 Actions
.ActOnFinishFunctionBody(Res
, GeneratedBody
, false);
1483 // With abbreviated function templates - we need to explicitly add depth to
1484 // account for the implicit template parameter list induced by the template.
1485 if (const auto *Template
= dyn_cast_if_present
<FunctionTemplateDecl
>(Res
);
1486 Template
&& Template
->isAbbreviated() &&
1487 Template
->getTemplateParameters()->getParam(0)->isImplicit())
1488 // First template parameter is implicit - meaning no explicit template
1489 // parameter list was specified.
1490 CurTemplateDepthTracker
.addDepth(1);
1492 if (SkipFunctionBodies
&& (!Res
|| Actions
.canSkipFunctionBody(Res
)) &&
1493 trySkippingFunctionBody()) {
1495 Actions
.ActOnSkippedFunctionBody(Res
);
1496 return Actions
.ActOnFinishFunctionBody(Res
, nullptr, false);
1499 if (Tok
.is(tok::kw_try
))
1500 return ParseFunctionTryBlock(Res
, BodyScope
);
1502 // If we have a colon, then we're probably parsing a C++
1503 // ctor-initializer.
1504 if (Tok
.is(tok::colon
)) {
1505 ParseConstructorInitializer(Res
);
1507 // Recover from error.
1508 if (!Tok
.is(tok::l_brace
)) {
1510 Actions
.ActOnFinishFunctionBody(Res
, nullptr);
1514 Actions
.ActOnDefaultCtorInitializers(Res
);
1516 // Late attributes are parsed in the same scope as the function body.
1517 if (LateParsedAttrs
)
1518 ParseLexedAttributeList(*LateParsedAttrs
, Res
, false, true);
1520 return ParseFunctionStatementBody(Res
, BodyScope
);
1523 void Parser::SkipFunctionBody() {
1524 if (Tok
.is(tok::equal
)) {
1525 SkipUntil(tok::semi
);
1529 bool IsFunctionTryBlock
= Tok
.is(tok::kw_try
);
1530 if (IsFunctionTryBlock
)
1533 CachedTokens Skipped
;
1534 if (ConsumeAndStoreFunctionPrologue(Skipped
))
1535 SkipMalformedDecl();
1537 SkipUntil(tok::r_brace
);
1538 while (IsFunctionTryBlock
&& Tok
.is(tok::kw_catch
)) {
1539 SkipUntil(tok::l_brace
);
1540 SkipUntil(tok::r_brace
);
1545 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1546 /// types for a function with a K&R-style identifier list for arguments.
1547 void Parser::ParseKNRParamDeclarations(Declarator
&D
) {
1548 // We know that the top-level of this declarator is a function.
1549 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
1551 // Enter function-declaration scope, limiting any declarators to the
1552 // function prototype scope, including parameter declarators.
1553 ParseScope
PrototypeScope(this, Scope::FunctionPrototypeScope
|
1554 Scope::FunctionDeclarationScope
| Scope::DeclScope
);
1556 // Read all the argument declarations.
1557 while (isDeclarationSpecifier(ImplicitTypenameContext::No
)) {
1558 SourceLocation DSStart
= Tok
.getLocation();
1560 // Parse the common declaration-specifiers piece.
1561 DeclSpec
DS(AttrFactory
);
1562 ParsedTemplateInfo TemplateInfo
;
1563 ParseDeclarationSpecifiers(DS
, TemplateInfo
);
1565 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1566 // least one declarator'.
1567 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1568 // the declarations though. It's trivial to ignore them, really hard to do
1569 // anything else with them.
1570 if (TryConsumeToken(tok::semi
)) {
1571 Diag(DSStart
, diag::err_declaration_does_not_declare_param
);
1575 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1577 if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
&&
1578 DS
.getStorageClassSpec() != DeclSpec::SCS_register
) {
1579 Diag(DS
.getStorageClassSpecLoc(),
1580 diag::err_invalid_storage_class_in_func_decl
);
1581 DS
.ClearStorageClassSpecs();
1583 if (DS
.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified
) {
1584 Diag(DS
.getThreadStorageClassSpecLoc(),
1585 diag::err_invalid_storage_class_in_func_decl
);
1586 DS
.ClearStorageClassSpecs();
1589 // Parse the first declarator attached to this declspec.
1590 Declarator
ParmDeclarator(DS
, ParsedAttributesView::none(),
1591 DeclaratorContext::KNRTypeList
);
1592 ParseDeclarator(ParmDeclarator
);
1594 // Handle the full declarator list.
1596 // If attributes are present, parse them.
1597 MaybeParseGNUAttributes(ParmDeclarator
);
1599 // Ask the actions module to compute the type for this declarator.
1601 Actions
.ActOnParamDeclarator(getCurScope(), ParmDeclarator
);
1604 // A missing identifier has already been diagnosed.
1605 ParmDeclarator
.getIdentifier()) {
1607 // Scan the argument list looking for the correct param to apply this
1609 for (unsigned i
= 0; ; ++i
) {
1610 // C99 6.9.1p6: those declarators shall declare only identifiers from
1611 // the identifier list.
1612 if (i
== FTI
.NumParams
) {
1613 Diag(ParmDeclarator
.getIdentifierLoc(), diag::err_no_matching_param
)
1614 << ParmDeclarator
.getIdentifier();
1618 if (FTI
.Params
[i
].Ident
== ParmDeclarator
.getIdentifier()) {
1619 // Reject redefinitions of parameters.
1620 if (FTI
.Params
[i
].Param
) {
1621 Diag(ParmDeclarator
.getIdentifierLoc(),
1622 diag::err_param_redefinition
)
1623 << ParmDeclarator
.getIdentifier();
1625 FTI
.Params
[i
].Param
= Param
;
1632 // If we don't have a comma, it is either the end of the list (a ';') or
1633 // an error, bail out.
1634 if (Tok
.isNot(tok::comma
))
1637 ParmDeclarator
.clear();
1639 // Consume the comma.
1640 ParmDeclarator
.setCommaLoc(ConsumeToken());
1642 // Parse the next declarator.
1643 ParseDeclarator(ParmDeclarator
);
1646 // Consume ';' and continue parsing.
1647 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration
))
1650 // Otherwise recover by skipping to next semi or mandatory function body.
1651 if (SkipUntil(tok::l_brace
, StopAtSemi
| StopBeforeMatch
))
1653 TryConsumeToken(tok::semi
);
1656 // The actions module must verify that all arguments were declared.
1657 Actions
.ActOnFinishKNRParamDeclarations(getCurScope(), D
, Tok
.getLocation());
1661 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1662 /// allowed to be a wide string, and is not subject to character translation.
1663 /// Unlike GCC, we also diagnose an empty string literal when parsing for an
1664 /// asm label as opposed to an asm statement, because such a construct does not
1667 /// [GNU] asm-string-literal:
1670 ExprResult
Parser::ParseAsmStringLiteral(bool ForAsmLabel
) {
1671 if (!isTokenStringLiteral()) {
1672 Diag(Tok
, diag::err_expected_string_literal
)
1673 << /*Source='in...'*/0 << "'asm'";
1677 ExprResult
AsmString(ParseStringLiteralExpression());
1678 if (!AsmString
.isInvalid()) {
1679 const auto *SL
= cast
<StringLiteral
>(AsmString
.get());
1680 if (!SL
->isOrdinary()) {
1681 Diag(Tok
, diag::err_asm_operand_wide_string_literal
)
1683 << SL
->getSourceRange();
1686 if (ForAsmLabel
&& SL
->getString().empty()) {
1687 Diag(Tok
, diag::err_asm_operand_wide_string_literal
)
1688 << 2 /* an empty */ << SL
->getSourceRange();
1697 /// [GNU] simple-asm-expr:
1698 /// 'asm' '(' asm-string-literal ')'
1700 ExprResult
Parser::ParseSimpleAsm(bool ForAsmLabel
, SourceLocation
*EndLoc
) {
1701 assert(Tok
.is(tok::kw_asm
) && "Not an asm!");
1702 SourceLocation Loc
= ConsumeToken();
1704 if (isGNUAsmQualifier(Tok
)) {
1705 // Remove from the end of 'asm' to the end of the asm qualifier.
1706 SourceRange
RemovalRange(PP
.getLocForEndOfToken(Loc
),
1707 PP
.getLocForEndOfToken(Tok
.getLocation()));
1708 Diag(Tok
, diag::err_global_asm_qualifier_ignored
)
1709 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok
))
1710 << FixItHint::CreateRemoval(RemovalRange
);
1714 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1715 if (T
.consumeOpen()) {
1716 Diag(Tok
, diag::err_expected_lparen_after
) << "asm";
1720 ExprResult
Result(ParseAsmStringLiteral(ForAsmLabel
));
1722 if (!Result
.isInvalid()) {
1723 // Close the paren and get the location of the end bracket
1726 *EndLoc
= T
.getCloseLocation();
1727 } else if (SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
)) {
1729 *EndLoc
= Tok
.getLocation();
1736 /// Get the TemplateIdAnnotation from the token and put it in the
1737 /// cleanup pool so that it gets destroyed when parsing the current top level
1738 /// declaration is finished.
1739 TemplateIdAnnotation
*Parser::takeTemplateIdAnnotation(const Token
&tok
) {
1740 assert(tok
.is(tok::annot_template_id
) && "Expected template-id token");
1741 TemplateIdAnnotation
*
1742 Id
= static_cast<TemplateIdAnnotation
*>(tok
.getAnnotationValue());
1746 void Parser::AnnotateScopeToken(CXXScopeSpec
&SS
, bool IsNewAnnotation
) {
1747 // Push the current token back into the token stream (or revert it if it is
1748 // cached) and use an annotation scope token for current token.
1749 if (PP
.isBacktrackEnabled())
1750 PP
.RevertCachedTokens(1);
1752 PP
.EnterToken(Tok
, /*IsReinject=*/true);
1753 Tok
.setKind(tok::annot_cxxscope
);
1754 Tok
.setAnnotationValue(Actions
.SaveNestedNameSpecifierAnnotation(SS
));
1755 Tok
.setAnnotationRange(SS
.getRange());
1757 // In case the tokens were cached, have Preprocessor replace them
1758 // with the annotation token. We don't need to do this if we've
1759 // just reverted back to a prior state.
1760 if (IsNewAnnotation
)
1761 PP
.AnnotateCachedTokens(Tok
);
1764 /// Attempt to classify the name at the current token position. This may
1765 /// form a type, scope or primary expression annotation, or replace the token
1766 /// with a typo-corrected keyword. This is only appropriate when the current
1767 /// name must refer to an entity which has already been declared.
1769 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1770 /// no typo correction will be performed.
1771 /// \param AllowImplicitTypename Whether we are in a context where a dependent
1772 /// nested-name-specifier without typename is treated as a type (e.g.
1774 Parser::AnnotatedNameKind
1775 Parser::TryAnnotateName(CorrectionCandidateCallback
*CCC
,
1776 ImplicitTypenameContext AllowImplicitTypename
) {
1777 assert(Tok
.is(tok::identifier
) || Tok
.is(tok::annot_cxxscope
));
1779 const bool EnteringContext
= false;
1780 const bool WasScopeAnnotation
= Tok
.is(tok::annot_cxxscope
);
1783 if (getLangOpts().CPlusPlus
&&
1784 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
1785 /*ObjectHasErrors=*/false,
1789 if (Tok
.isNot(tok::identifier
) || SS
.isInvalid()) {
1790 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS
, !WasScopeAnnotation
,
1791 AllowImplicitTypename
))
1793 return ANK_Unresolved
;
1796 IdentifierInfo
*Name
= Tok
.getIdentifierInfo();
1797 SourceLocation NameLoc
= Tok
.getLocation();
1799 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1800 // typo-correct to tentatively-declared identifiers.
1801 if (isTentativelyDeclared(Name
) && SS
.isEmpty()) {
1802 // Identifier has been tentatively declared, and thus cannot be resolved as
1803 // an expression. Fall back to annotating it as a type.
1804 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS
, !WasScopeAnnotation
,
1805 AllowImplicitTypename
))
1807 return Tok
.is(tok::annot_typename
) ? ANK_Success
: ANK_TentativeDecl
;
1810 Token Next
= NextToken();
1812 // Look up and classify the identifier. We don't perform any typo-correction
1813 // after a scope specifier, because in general we can't recover from typos
1814 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1815 // jump back into scope specifier parsing).
1816 Sema::NameClassification Classification
= Actions
.ClassifyName(
1817 getCurScope(), SS
, Name
, NameLoc
, Next
, SS
.isEmpty() ? CCC
: nullptr);
1819 // If name lookup found nothing and we guessed that this was a template name,
1820 // double-check before committing to that interpretation. C++20 requires that
1821 // we interpret this as a template-id if it can be, but if it can't be, then
1822 // this is an error recovery case.
1823 if (Classification
.getKind() == Sema::NC_UndeclaredTemplate
&&
1824 isTemplateArgumentList(1) == TPResult::False
) {
1825 // It's not a template-id; re-classify without the '<' as a hint.
1826 Token FakeNext
= Next
;
1827 FakeNext
.setKind(tok::unknown
);
1829 Actions
.ClassifyName(getCurScope(), SS
, Name
, NameLoc
, FakeNext
,
1830 SS
.isEmpty() ? CCC
: nullptr);
1833 switch (Classification
.getKind()) {
1834 case Sema::NC_Error
:
1837 case Sema::NC_Keyword
:
1838 // The identifier was typo-corrected to a keyword.
1839 Tok
.setIdentifierInfo(Name
);
1840 Tok
.setKind(Name
->getTokenID());
1841 PP
.TypoCorrectToken(Tok
);
1842 if (SS
.isNotEmpty())
1843 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1844 // We've "annotated" this as a keyword.
1847 case Sema::NC_Unknown
:
1848 // It's not something we know about. Leave it unannotated.
1851 case Sema::NC_Type
: {
1852 if (TryAltiVecVectorToken())
1853 // vector has been found as a type id when altivec is enabled but
1854 // this is followed by a declaration specifier so this is really the
1855 // altivec vector token. Leave it unannotated.
1857 SourceLocation BeginLoc
= NameLoc
;
1858 if (SS
.isNotEmpty())
1859 BeginLoc
= SS
.getBeginLoc();
1861 /// An Objective-C object type followed by '<' is a specialization of
1862 /// a parameterized class type or a protocol-qualified type.
1863 ParsedType Ty
= Classification
.getType();
1864 if (getLangOpts().ObjC
&& NextToken().is(tok::less
) &&
1865 (Ty
.get()->isObjCObjectType() ||
1866 Ty
.get()->isObjCObjectPointerType())) {
1867 // Consume the name.
1868 SourceLocation IdentifierLoc
= ConsumeToken();
1869 SourceLocation NewEndLoc
;
1871 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc
, Ty
,
1872 /*consumeLastToken=*/false,
1874 if (NewType
.isUsable())
1876 else if (Tok
.is(tok::eof
)) // Nothing to do here, bail out...
1880 Tok
.setKind(tok::annot_typename
);
1881 setTypeAnnotation(Tok
, Ty
);
1882 Tok
.setAnnotationEndLoc(Tok
.getLocation());
1883 Tok
.setLocation(BeginLoc
);
1884 PP
.AnnotateCachedTokens(Tok
);
1888 case Sema::NC_OverloadSet
:
1889 Tok
.setKind(tok::annot_overload_set
);
1890 setExprAnnotation(Tok
, Classification
.getExpression());
1891 Tok
.setAnnotationEndLoc(NameLoc
);
1892 if (SS
.isNotEmpty())
1893 Tok
.setLocation(SS
.getBeginLoc());
1894 PP
.AnnotateCachedTokens(Tok
);
1897 case Sema::NC_NonType
:
1898 if (TryAltiVecVectorToken())
1899 // vector has been found as a non-type id when altivec is enabled but
1900 // this is followed by a declaration specifier so this is really the
1901 // altivec vector token. Leave it unannotated.
1903 Tok
.setKind(tok::annot_non_type
);
1904 setNonTypeAnnotation(Tok
, Classification
.getNonTypeDecl());
1905 Tok
.setLocation(NameLoc
);
1906 Tok
.setAnnotationEndLoc(NameLoc
);
1907 PP
.AnnotateCachedTokens(Tok
);
1908 if (SS
.isNotEmpty())
1909 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1912 case Sema::NC_UndeclaredNonType
:
1913 case Sema::NC_DependentNonType
:
1914 Tok
.setKind(Classification
.getKind() == Sema::NC_UndeclaredNonType
1915 ? tok::annot_non_type_undeclared
1916 : tok::annot_non_type_dependent
);
1917 setIdentifierAnnotation(Tok
, Name
);
1918 Tok
.setLocation(NameLoc
);
1919 Tok
.setAnnotationEndLoc(NameLoc
);
1920 PP
.AnnotateCachedTokens(Tok
);
1921 if (SS
.isNotEmpty())
1922 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1925 case Sema::NC_TypeTemplate
:
1926 if (Next
.isNot(tok::less
)) {
1927 // This may be a type template being used as a template template argument.
1928 if (SS
.isNotEmpty())
1929 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1930 return ANK_TemplateName
;
1933 case Sema::NC_Concept
:
1934 case Sema::NC_VarTemplate
:
1935 case Sema::NC_FunctionTemplate
:
1936 case Sema::NC_UndeclaredTemplate
: {
1937 bool IsConceptName
= Classification
.getKind() == Sema::NC_Concept
;
1938 // We have a template name followed by '<'. Consume the identifier token so
1939 // we reach the '<' and annotate it.
1940 if (Next
.is(tok::less
))
1943 Id
.setIdentifier(Name
, NameLoc
);
1944 if (AnnotateTemplateIdToken(
1945 TemplateTy::make(Classification
.getTemplateName()),
1946 Classification
.getTemplateNameKind(), SS
, SourceLocation(), Id
,
1947 /*AllowTypeAnnotation=*/!IsConceptName
,
1948 /*TypeConstraint=*/IsConceptName
))
1950 if (SS
.isNotEmpty())
1951 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1956 // Unable to classify the name, but maybe we can annotate a scope specifier.
1957 if (SS
.isNotEmpty())
1958 AnnotateScopeToken(SS
, !WasScopeAnnotation
);
1959 return ANK_Unresolved
;
1962 bool Parser::TryKeywordIdentFallback(bool DisableKeyword
) {
1963 assert(Tok
.isNot(tok::identifier
));
1964 Diag(Tok
, diag::ext_keyword_as_ident
)
1965 << PP
.getSpelling(Tok
)
1968 Tok
.getIdentifierInfo()->revertTokenIDToIdentifier();
1969 Tok
.setKind(tok::identifier
);
1973 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1974 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1975 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1976 /// with a single annotation token representing the typename or C++ scope
1978 /// This simplifies handling of C++ scope specifiers and allows efficient
1979 /// backtracking without the need to re-parse and resolve nested-names and
1981 /// It will mainly be called when we expect to treat identifiers as typenames
1982 /// (if they are typenames). For example, in C we do not expect identifiers
1983 /// inside expressions to be treated as typenames so it will not be called
1984 /// for expressions in C.
1985 /// The benefit for C/ObjC is that a typename will be annotated and
1986 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1987 /// will not be called twice, once to check whether we have a declaration
1988 /// specifier, and another one to get the actual type inside
1989 /// ParseDeclarationSpecifiers).
1991 /// This returns true if an error occurred.
1993 /// Note that this routine emits an error if you call it with ::new or ::delete
1994 /// as the current tokens, so only call it in contexts where these are invalid.
1995 bool Parser::TryAnnotateTypeOrScopeToken(
1996 ImplicitTypenameContext AllowImplicitTypename
) {
1997 assert((Tok
.is(tok::identifier
) || Tok
.is(tok::coloncolon
) ||
1998 Tok
.is(tok::kw_typename
) || Tok
.is(tok::annot_cxxscope
) ||
1999 Tok
.is(tok::kw_decltype
) || Tok
.is(tok::annot_template_id
) ||
2000 Tok
.is(tok::kw___super
) || Tok
.is(tok::kw_auto
) ||
2001 Tok
.is(tok::annot_pack_indexing_type
)) &&
2002 "Cannot be a type or scope token!");
2004 if (Tok
.is(tok::kw_typename
)) {
2005 // MSVC lets you do stuff like:
2006 // typename typedef T_::D D;
2008 // We will consume the typedef token here and put it back after we have
2009 // parsed the first identifier, transforming it into something more like:
2010 // typename T_::D typedef D;
2011 if (getLangOpts().MSVCCompat
&& NextToken().is(tok::kw_typedef
)) {
2013 PP
.Lex(TypedefToken
);
2014 bool Result
= TryAnnotateTypeOrScopeToken(AllowImplicitTypename
);
2015 PP
.EnterToken(Tok
, /*IsReinject=*/true);
2018 Diag(Tok
.getLocation(), diag::warn_expected_qualified_after_typename
);
2022 // Parse a C++ typename-specifier, e.g., "typename T::type".
2024 // typename-specifier:
2025 // 'typename' '::' [opt] nested-name-specifier identifier
2026 // 'typename' '::' [opt] nested-name-specifier template [opt]
2027 // simple-template-id
2028 SourceLocation TypenameLoc
= ConsumeToken();
2030 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
2031 /*ObjectHasErrors=*/false,
2032 /*EnteringContext=*/false, nullptr,
2033 /*IsTypename*/ true))
2036 if (Tok
.is(tok::identifier
) || Tok
.is(tok::annot_template_id
) ||
2037 Tok
.is(tok::annot_decltype
)) {
2038 // Attempt to recover by skipping the invalid 'typename'
2039 if (Tok
.is(tok::annot_decltype
) ||
2040 (!TryAnnotateTypeOrScopeToken(AllowImplicitTypename
) &&
2041 Tok
.isAnnotation())) {
2042 unsigned DiagID
= diag::err_expected_qualified_after_typename
;
2043 // MS compatibility: MSVC permits using known types with typename.
2044 // e.g. "typedef typename T* pointer_type"
2045 if (getLangOpts().MicrosoftExt
)
2046 DiagID
= diag::warn_expected_qualified_after_typename
;
2047 Diag(Tok
.getLocation(), DiagID
);
2051 if (Tok
.isEditorPlaceholder())
2054 Diag(Tok
.getLocation(), diag::err_expected_qualified_after_typename
);
2058 bool TemplateKWPresent
= false;
2059 if (Tok
.is(tok::kw_template
)) {
2061 TemplateKWPresent
= true;
2065 if (Tok
.is(tok::identifier
)) {
2066 if (TemplateKWPresent
&& NextToken().isNot(tok::less
)) {
2067 Diag(Tok
.getLocation(),
2068 diag::missing_template_arg_list_after_template_kw
);
2071 Ty
= Actions
.ActOnTypenameType(getCurScope(), TypenameLoc
, SS
,
2072 *Tok
.getIdentifierInfo(),
2074 } else if (Tok
.is(tok::annot_template_id
)) {
2075 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
2076 if (!TemplateId
->mightBeType()) {
2077 Diag(Tok
, diag::err_typename_refers_to_non_type_template
)
2078 << Tok
.getAnnotationRange();
2082 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
2083 TemplateId
->NumArgs
);
2085 Ty
= TemplateId
->isInvalid()
2087 : Actions
.ActOnTypenameType(
2088 getCurScope(), TypenameLoc
, SS
, TemplateId
->TemplateKWLoc
,
2089 TemplateId
->Template
, TemplateId
->Name
,
2090 TemplateId
->TemplateNameLoc
, TemplateId
->LAngleLoc
,
2091 TemplateArgsPtr
, TemplateId
->RAngleLoc
);
2093 Diag(Tok
, diag::err_expected_type_name_after_typename
)
2098 SourceLocation EndLoc
= Tok
.getLastLoc();
2099 Tok
.setKind(tok::annot_typename
);
2100 setTypeAnnotation(Tok
, Ty
);
2101 Tok
.setAnnotationEndLoc(EndLoc
);
2102 Tok
.setLocation(TypenameLoc
);
2103 PP
.AnnotateCachedTokens(Tok
);
2107 // Remembers whether the token was originally a scope annotation.
2108 bool WasScopeAnnotation
= Tok
.is(tok::annot_cxxscope
);
2111 if (getLangOpts().CPlusPlus
)
2112 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
2113 /*ObjectHasErrors=*/false,
2114 /*EnteringContext*/ false))
2117 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS
, !WasScopeAnnotation
,
2118 AllowImplicitTypename
);
2121 /// Try to annotate a type or scope token, having already parsed an
2122 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
2123 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
2124 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(
2125 CXXScopeSpec
&SS
, bool IsNewScope
,
2126 ImplicitTypenameContext AllowImplicitTypename
) {
2127 if (Tok
.is(tok::identifier
)) {
2128 // Determine whether the identifier is a type name.
2129 if (ParsedType Ty
= Actions
.getTypeName(
2130 *Tok
.getIdentifierInfo(), Tok
.getLocation(), getCurScope(), &SS
,
2131 false, NextToken().is(tok::period
), nullptr,
2132 /*IsCtorOrDtorName=*/false,
2133 /*NonTrivialTypeSourceInfo=*/true,
2134 /*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename
)) {
2135 SourceLocation BeginLoc
= Tok
.getLocation();
2136 if (SS
.isNotEmpty()) // it was a C++ qualified type name.
2137 BeginLoc
= SS
.getBeginLoc();
2139 /// An Objective-C object type followed by '<' is a specialization of
2140 /// a parameterized class type or a protocol-qualified type.
2141 if (getLangOpts().ObjC
&& NextToken().is(tok::less
) &&
2142 (Ty
.get()->isObjCObjectType() ||
2143 Ty
.get()->isObjCObjectPointerType())) {
2144 // Consume the name.
2145 SourceLocation IdentifierLoc
= ConsumeToken();
2146 SourceLocation NewEndLoc
;
2148 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc
, Ty
,
2149 /*consumeLastToken=*/false,
2151 if (NewType
.isUsable())
2153 else if (Tok
.is(tok::eof
)) // Nothing to do here, bail out...
2157 // This is a typename. Replace the current token in-place with an
2158 // annotation type token.
2159 Tok
.setKind(tok::annot_typename
);
2160 setTypeAnnotation(Tok
, Ty
);
2161 Tok
.setAnnotationEndLoc(Tok
.getLocation());
2162 Tok
.setLocation(BeginLoc
);
2164 // In case the tokens were cached, have Preprocessor replace
2165 // them with the annotation token.
2166 PP
.AnnotateCachedTokens(Tok
);
2170 if (!getLangOpts().CPlusPlus
) {
2171 // If we're in C, the only place we can have :: tokens is C23
2172 // attribute which is parsed elsewhere. If the identifier is not a type,
2173 // then it can't be scope either, just early exit.
2177 // If this is a template-id, annotate with a template-id or type token.
2178 // FIXME: This appears to be dead code. We already have formed template-id
2179 // tokens when parsing the scope specifier; this can never form a new one.
2180 if (NextToken().is(tok::less
)) {
2181 TemplateTy Template
;
2182 UnqualifiedId TemplateName
;
2183 TemplateName
.setIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
2184 bool MemberOfUnknownSpecialization
;
2185 if (TemplateNameKind TNK
= Actions
.isTemplateName(
2187 /*hasTemplateKeyword=*/false, TemplateName
,
2188 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template
,
2189 MemberOfUnknownSpecialization
)) {
2190 // Only annotate an undeclared template name as a template-id if the
2191 // following tokens have the form of a template argument list.
2192 if (TNK
!= TNK_Undeclared_template
||
2193 isTemplateArgumentList(1) != TPResult::False
) {
2194 // Consume the identifier.
2196 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, SourceLocation(),
2198 // If an unrecoverable error occurred, we need to return true here,
2199 // because the token stream is in a damaged state. We may not
2200 // return a valid identifier.
2207 // The current token, which is either an identifier or a
2208 // template-id, is not part of the annotation. Fall through to
2209 // push that token back into the stream and complete the C++ scope
2210 // specifier annotation.
2213 if (Tok
.is(tok::annot_template_id
)) {
2214 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
2215 if (TemplateId
->Kind
== TNK_Type_template
) {
2216 // A template-id that refers to a type was parsed into a
2217 // template-id annotation in a context where we weren't allowed
2218 // to produce a type annotation token. Update the template-id
2219 // annotation token to a type annotation token now.
2220 AnnotateTemplateIdTokenAsType(SS
, AllowImplicitTypename
);
2228 // A C++ scope specifier that isn't followed by a typename.
2229 AnnotateScopeToken(SS
, IsNewScope
);
2233 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
2234 /// annotates C++ scope specifiers and template-ids. This returns
2235 /// true if there was an error that could not be recovered from.
2237 /// Note that this routine emits an error if you call it with ::new or ::delete
2238 /// as the current tokens, so only call it in contexts where these are invalid.
2239 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext
) {
2240 assert(getLangOpts().CPlusPlus
&&
2241 "Call sites of this function should be guarded by checking for C++");
2242 assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");
2245 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
2246 /*ObjectHasErrors=*/false,
2252 AnnotateScopeToken(SS
, true);
2256 bool Parser::isTokenEqualOrEqualTypo() {
2257 tok::TokenKind Kind
= Tok
.getKind();
2261 case tok::ampequal
: // &=
2262 case tok::starequal
: // *=
2263 case tok::plusequal
: // +=
2264 case tok::minusequal
: // -=
2265 case tok::exclaimequal
: // !=
2266 case tok::slashequal
: // /=
2267 case tok::percentequal
: // %=
2268 case tok::lessequal
: // <=
2269 case tok::lesslessequal
: // <<=
2270 case tok::greaterequal
: // >=
2271 case tok::greatergreaterequal
: // >>=
2272 case tok::caretequal
: // ^=
2273 case tok::pipeequal
: // |=
2274 case tok::equalequal
: // ==
2275 Diag(Tok
, diag::err_invalid_token_after_declarator_suggest_equal
)
2277 << FixItHint::CreateReplacement(SourceRange(Tok
.getLocation()), "=");
2284 SourceLocation
Parser::handleUnexpectedCodeCompletionToken() {
2285 assert(Tok
.is(tok::code_completion
));
2286 PrevTokLocation
= Tok
.getLocation();
2288 for (Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
2289 if (S
->isFunctionScope()) {
2291 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
2292 getCurScope(), SemaCodeCompletion::PCC_RecoveryInFunction
);
2293 return PrevTokLocation
;
2296 if (S
->isClassScope()) {
2298 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
2299 getCurScope(), SemaCodeCompletion::PCC_Class
);
2300 return PrevTokLocation
;
2305 Actions
.CodeCompletion().CodeCompleteOrdinaryName(
2306 getCurScope(), SemaCodeCompletion::PCC_Namespace
);
2307 return PrevTokLocation
;
2310 // Code-completion pass-through functions
2312 void Parser::CodeCompleteDirective(bool InConditional
) {
2313 Actions
.CodeCompletion().CodeCompletePreprocessorDirective(InConditional
);
2316 void Parser::CodeCompleteInConditionalExclusion() {
2317 Actions
.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2321 void Parser::CodeCompleteMacroName(bool IsDefinition
) {
2322 Actions
.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition
);
2325 void Parser::CodeCompletePreprocessorExpression() {
2326 Actions
.CodeCompletion().CodeCompletePreprocessorExpression();
2329 void Parser::CodeCompleteMacroArgument(IdentifierInfo
*Macro
,
2330 MacroInfo
*MacroInfo
,
2331 unsigned ArgumentIndex
) {
2332 Actions
.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2333 getCurScope(), Macro
, MacroInfo
, ArgumentIndex
);
2336 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir
, bool IsAngled
) {
2337 Actions
.CodeCompletion().CodeCompleteIncludedFile(Dir
, IsAngled
);
2340 void Parser::CodeCompleteNaturalLanguage() {
2341 Actions
.CodeCompletion().CodeCompleteNaturalLanguage();
2344 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition
& Result
) {
2345 assert((Tok
.is(tok::kw___if_exists
) || Tok
.is(tok::kw___if_not_exists
)) &&
2346 "Expected '__if_exists' or '__if_not_exists'");
2347 Result
.IsIfExists
= Tok
.is(tok::kw___if_exists
);
2348 Result
.KeywordLoc
= ConsumeToken();
2350 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2351 if (T
.consumeOpen()) {
2352 Diag(Tok
, diag::err_expected_lparen_after
)
2353 << (Result
.IsIfExists
? "__if_exists" : "__if_not_exists");
2357 // Parse nested-name-specifier.
2358 if (getLangOpts().CPlusPlus
)
2359 ParseOptionalCXXScopeSpecifier(Result
.SS
, /*ObjectType=*/nullptr,
2360 /*ObjectHasErrors=*/false,
2361 /*EnteringContext=*/false);
2363 // Check nested-name specifier.
2364 if (Result
.SS
.isInvalid()) {
2369 // Parse the unqualified-id.
2370 SourceLocation TemplateKWLoc
; // FIXME: parsed, but unused.
2371 if (ParseUnqualifiedId(Result
.SS
, /*ObjectType=*/nullptr,
2372 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
2373 /*AllowDestructorName*/ true,
2374 /*AllowConstructorName*/ true,
2375 /*AllowDeductionGuide*/ false, &TemplateKWLoc
,
2381 if (T
.consumeClose())
2384 // Check if the symbol exists.
2385 switch (Actions
.CheckMicrosoftIfExistsSymbol(getCurScope(), Result
.KeywordLoc
,
2386 Result
.IsIfExists
, Result
.SS
,
2388 case Sema::IER_Exists
:
2389 Result
.Behavior
= Result
.IsIfExists
? IEB_Parse
: IEB_Skip
;
2392 case Sema::IER_DoesNotExist
:
2393 Result
.Behavior
= !Result
.IsIfExists
? IEB_Parse
: IEB_Skip
;
2396 case Sema::IER_Dependent
:
2397 Result
.Behavior
= IEB_Dependent
;
2400 case Sema::IER_Error
:
2407 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2408 IfExistsCondition Result
;
2409 if (ParseMicrosoftIfExistsCondition(Result
))
2412 BalancedDelimiterTracker
Braces(*this, tok::l_brace
);
2413 if (Braces
.consumeOpen()) {
2414 Diag(Tok
, diag::err_expected
) << tok::l_brace
;
2418 switch (Result
.Behavior
) {
2420 // Parse declarations below.
2424 llvm_unreachable("Cannot have a dependent external declaration");
2431 // Parse the declarations.
2432 // FIXME: Support module import within __if_exists?
2433 while (Tok
.isNot(tok::r_brace
) && !isEofOrEom()) {
2434 ParsedAttributes
Attrs(AttrFactory
);
2435 MaybeParseCXX11Attributes(Attrs
);
2436 ParsedAttributes
EmptyDeclSpecAttrs(AttrFactory
);
2437 DeclGroupPtrTy Result
= ParseExternalDeclaration(Attrs
, EmptyDeclSpecAttrs
);
2438 if (Result
&& !getCurScope()->getParent())
2439 Actions
.getASTConsumer().HandleTopLevelDecl(Result
.get());
2441 Braces
.consumeClose();
2444 /// Parse a declaration beginning with the 'module' keyword or C++20
2445 /// context-sensitive keyword (optionally preceded by 'export').
2447 /// module-declaration: [C++20]
2448 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2450 /// global-module-fragment: [C++2a]
2451 /// 'module' ';' top-level-declaration-seq[opt]
2452 /// module-declaration: [C++2a]
2453 /// 'export'[opt] 'module' module-name module-partition[opt]
2454 /// attribute-specifier-seq[opt] ';'
2455 /// private-module-fragment: [C++2a]
2456 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2457 Parser::DeclGroupPtrTy
2458 Parser::ParseModuleDecl(Sema::ModuleImportState
&ImportState
) {
2459 SourceLocation StartLoc
= Tok
.getLocation();
2461 Sema::ModuleDeclKind MDK
= TryConsumeToken(tok::kw_export
)
2462 ? Sema::ModuleDeclKind::Interface
2463 : Sema::ModuleDeclKind::Implementation
;
2466 (Tok
.is(tok::kw_module
) ||
2467 (Tok
.is(tok::identifier
) && Tok
.getIdentifierInfo() == Ident_module
)) &&
2468 "not a module declaration");
2469 SourceLocation ModuleLoc
= ConsumeToken();
2471 // Attributes appear after the module name, not before.
2472 // FIXME: Suggest moving the attributes later with a fixit.
2473 DiagnoseAndSkipCXX11Attributes();
2475 // Parse a global-module-fragment, if present.
2476 if (getLangOpts().CPlusPlusModules
&& Tok
.is(tok::semi
)) {
2477 SourceLocation SemiLoc
= ConsumeToken();
2478 if (ImportState
!= Sema::ModuleImportState::FirstDecl
) {
2479 Diag(StartLoc
, diag::err_global_module_introducer_not_at_start
)
2480 << SourceRange(StartLoc
, SemiLoc
);
2483 if (MDK
== Sema::ModuleDeclKind::Interface
) {
2484 Diag(StartLoc
, diag::err_module_fragment_exported
)
2485 << /*global*/0 << FixItHint::CreateRemoval(StartLoc
);
2487 ImportState
= Sema::ModuleImportState::GlobalFragment
;
2488 return Actions
.ActOnGlobalModuleFragmentDecl(ModuleLoc
);
2491 // Parse a private-module-fragment, if present.
2492 if (getLangOpts().CPlusPlusModules
&& Tok
.is(tok::colon
) &&
2493 NextToken().is(tok::kw_private
)) {
2494 if (MDK
== Sema::ModuleDeclKind::Interface
) {
2495 Diag(StartLoc
, diag::err_module_fragment_exported
)
2496 << /*private*/1 << FixItHint::CreateRemoval(StartLoc
);
2499 SourceLocation PrivateLoc
= ConsumeToken();
2500 DiagnoseAndSkipCXX11Attributes();
2501 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi
);
2502 ImportState
= ImportState
== Sema::ModuleImportState::ImportAllowed
2503 ? Sema::ModuleImportState::PrivateFragmentImportAllowed
2504 : Sema::ModuleImportState::PrivateFragmentImportFinished
;
2505 return Actions
.ActOnPrivateModuleFragmentDecl(ModuleLoc
, PrivateLoc
);
2508 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> Path
;
2509 if (ParseModuleName(ModuleLoc
, Path
, /*IsImport*/ false))
2512 // Parse the optional module-partition.
2513 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> Partition
;
2514 if (Tok
.is(tok::colon
)) {
2515 SourceLocation ColonLoc
= ConsumeToken();
2516 if (!getLangOpts().CPlusPlusModules
)
2517 Diag(ColonLoc
, diag::err_unsupported_module_partition
)
2518 << SourceRange(ColonLoc
, Partition
.back().second
);
2519 // Recover by ignoring the partition name.
2520 else if (ParseModuleName(ModuleLoc
, Partition
, /*IsImport*/ false))
2524 // We don't support any module attributes yet; just parse them and diagnose.
2525 ParsedAttributes
Attrs(AttrFactory
);
2526 MaybeParseCXX11Attributes(Attrs
);
2527 ProhibitCXX11Attributes(Attrs
, diag::err_attribute_not_module_attr
,
2528 diag::err_keyword_not_module_attr
,
2529 /*DiagnoseEmptyAttrs=*/false,
2530 /*WarnOnUnknownAttrs=*/true);
2532 ExpectAndConsumeSemi(diag::err_module_expected_semi
);
2534 return Actions
.ActOnModuleDecl(StartLoc
, ModuleLoc
, MDK
, Path
, Partition
,
2538 /// Parse a module import declaration. This is essentially the same for
2539 /// Objective-C and C++20 except for the leading '@' (in ObjC) and the
2540 /// trailing optional attributes (in C++).
2542 /// [ObjC] @import declaration:
2543 /// '@' 'import' module-name ';'
2544 /// [ModTS] module-import-declaration:
2545 /// 'import' module-name attribute-specifier-seq[opt] ';'
2546 /// [C++20] module-import-declaration:
2547 /// 'export'[opt] 'import' module-name
2548 /// attribute-specifier-seq[opt] ';'
2549 /// 'export'[opt] 'import' module-partition
2550 /// attribute-specifier-seq[opt] ';'
2551 /// 'export'[opt] 'import' header-name
2552 /// attribute-specifier-seq[opt] ';'
2553 Decl
*Parser::ParseModuleImport(SourceLocation AtLoc
,
2554 Sema::ModuleImportState
&ImportState
) {
2555 SourceLocation StartLoc
= AtLoc
.isInvalid() ? Tok
.getLocation() : AtLoc
;
2557 SourceLocation ExportLoc
;
2558 TryConsumeToken(tok::kw_export
, ExportLoc
);
2560 assert((AtLoc
.isInvalid() ? Tok
.isOneOf(tok::kw_import
, tok::identifier
)
2561 : Tok
.isObjCAtKeyword(tok::objc_import
)) &&
2562 "Improper start to module import");
2563 bool IsObjCAtImport
= Tok
.isObjCAtKeyword(tok::objc_import
);
2564 SourceLocation ImportLoc
= ConsumeToken();
2566 // For C++20 modules, we can have "name" or ":Partition name" as valid input.
2567 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> Path
;
2568 bool IsPartition
= false;
2569 Module
*HeaderUnit
= nullptr;
2570 if (Tok
.is(tok::header_name
)) {
2571 // This is a header import that the preprocessor decided we should skip
2572 // because it was malformed in some way. Parse and ignore it; it's already
2575 } else if (Tok
.is(tok::annot_header_unit
)) {
2576 // This is a header import that the preprocessor mapped to a module import.
2577 HeaderUnit
= reinterpret_cast<Module
*>(Tok
.getAnnotationValue());
2578 ConsumeAnnotationToken();
2579 } else if (Tok
.is(tok::colon
)) {
2580 SourceLocation ColonLoc
= ConsumeToken();
2581 if (!getLangOpts().CPlusPlusModules
)
2582 Diag(ColonLoc
, diag::err_unsupported_module_partition
)
2583 << SourceRange(ColonLoc
, Path
.back().second
);
2584 // Recover by leaving partition empty.
2585 else if (ParseModuleName(ColonLoc
, Path
, /*IsImport*/ true))
2590 if (ParseModuleName(ImportLoc
, Path
, /*IsImport*/ true))
2594 ParsedAttributes
Attrs(AttrFactory
);
2595 MaybeParseCXX11Attributes(Attrs
);
2596 // We don't support any module import attributes yet.
2597 ProhibitCXX11Attributes(Attrs
, diag::err_attribute_not_import_attr
,
2598 diag::err_keyword_not_import_attr
,
2599 /*DiagnoseEmptyAttrs=*/false,
2600 /*WarnOnUnknownAttrs=*/true);
2602 if (PP
.hadModuleLoaderFatalFailure()) {
2603 // With a fatal failure in the module loader, we abort parsing.
2608 // Diagnose mis-imports.
2609 bool SeenError
= true;
2610 switch (ImportState
) {
2611 case Sema::ModuleImportState::ImportAllowed
:
2614 case Sema::ModuleImportState::FirstDecl
:
2615 // If we found an import decl as the first declaration, we must be not in
2616 // a C++20 module unit or we are in an invalid state.
2617 ImportState
= Sema::ModuleImportState::NotACXX20Module
;
2619 case Sema::ModuleImportState::NotACXX20Module
:
2620 // We can only import a partition within a module purview.
2622 Diag(ImportLoc
, diag::err_partition_import_outside_module
);
2626 case Sema::ModuleImportState::GlobalFragment
:
2627 case Sema::ModuleImportState::PrivateFragmentImportAllowed
:
2628 // We can only have pre-processor directives in the global module fragment
2629 // which allows pp-import, but not of a partition (since the global module
2630 // does not have partitions).
2631 // We cannot import a partition into a private module fragment, since
2632 // [module.private.frag]/1 disallows private module fragments in a multi-
2634 if (IsPartition
|| (HeaderUnit
&& HeaderUnit
->Kind
!=
2635 Module::ModuleKind::ModuleHeaderUnit
))
2636 Diag(ImportLoc
, diag::err_import_in_wrong_fragment
)
2638 << (ImportState
== Sema::ModuleImportState::GlobalFragment
? 0 : 1);
2642 case Sema::ModuleImportState::ImportFinished
:
2643 case Sema::ModuleImportState::PrivateFragmentImportFinished
:
2644 if (getLangOpts().CPlusPlusModules
)
2645 Diag(ImportLoc
, diag::err_import_not_allowed_here
);
2651 ExpectAndConsumeSemi(diag::err_module_expected_semi
);
2658 Actions
.ActOnModuleImport(StartLoc
, ExportLoc
, ImportLoc
, HeaderUnit
);
2659 else if (!Path
.empty())
2660 Import
= Actions
.ActOnModuleImport(StartLoc
, ExportLoc
, ImportLoc
, Path
,
2662 ExpectAndConsumeSemi(diag::err_module_expected_semi
);
2663 if (Import
.isInvalid())
2666 // Using '@import' in framework headers requires modules to be enabled so that
2667 // the header is parseable. Emit a warning to make the user aware.
2668 if (IsObjCAtImport
&& AtLoc
.isValid()) {
2669 auto &SrcMgr
= PP
.getSourceManager();
2670 auto FE
= SrcMgr
.getFileEntryRefForID(SrcMgr
.getFileID(AtLoc
));
2671 if (FE
&& llvm::sys::path::parent_path(FE
->getDir().getName())
2672 .ends_with(".framework"))
2673 Diags
.Report(AtLoc
, diag::warn_atimport_in_framework_header
);
2676 return Import
.get();
2679 /// Parse a C++ / Objective-C module name (both forms use the same
2683 /// module-name-qualifier[opt] identifier
2684 /// module-name-qualifier:
2685 /// module-name-qualifier[opt] identifier '.'
2686 bool Parser::ParseModuleName(
2687 SourceLocation UseLoc
,
2688 SmallVectorImpl
<std::pair
<IdentifierInfo
*, SourceLocation
>> &Path
,
2690 // Parse the module path.
2692 if (!Tok
.is(tok::identifier
)) {
2693 if (Tok
.is(tok::code_completion
)) {
2695 Actions
.CodeCompletion().CodeCompleteModuleImport(UseLoc
, Path
);
2699 Diag(Tok
, diag::err_module_expected_ident
) << IsImport
;
2700 SkipUntil(tok::semi
);
2704 // Record this part of the module path.
2705 Path
.push_back(std::make_pair(Tok
.getIdentifierInfo(), Tok
.getLocation()));
2708 if (Tok
.isNot(tok::period
))
2715 /// Try recover parser when module annotation appears where it must not
2717 /// \returns false if the recover was successful and parsing may be continued, or
2718 /// true if parser must bail out to top level and handle the token there.
2719 bool Parser::parseMisplacedModuleImport() {
2721 switch (Tok
.getKind()) {
2722 case tok::annot_module_end
:
2723 // If we recovered from a misplaced module begin, we expect to hit a
2724 // misplaced module end too. Stay in the current context when this
2726 if (MisplacedModuleBeginCount
) {
2727 --MisplacedModuleBeginCount
;
2728 Actions
.ActOnAnnotModuleEnd(
2730 reinterpret_cast<Module
*>(Tok
.getAnnotationValue()));
2731 ConsumeAnnotationToken();
2734 // Inform caller that recovery failed, the error must be handled at upper
2735 // level. This will generate the desired "missing '}' at end of module"
2736 // diagnostics on the way out.
2738 case tok::annot_module_begin
:
2739 // Recover by entering the module (Sema will diagnose).
2740 Actions
.ActOnAnnotModuleBegin(
2742 reinterpret_cast<Module
*>(Tok
.getAnnotationValue()));
2743 ConsumeAnnotationToken();
2744 ++MisplacedModuleBeginCount
;
2746 case tok::annot_module_include
:
2747 // Module import found where it should not be, for instance, inside a
2748 // namespace. Recover by importing the module.
2749 Actions
.ActOnAnnotModuleInclude(
2751 reinterpret_cast<Module
*>(Tok
.getAnnotationValue()));
2752 ConsumeAnnotationToken();
2753 // If there is another module import, process it.
2762 void Parser::diagnoseUseOfC11Keyword(const Token
&Tok
) {
2763 // Warn that this is a C11 extension if in an older mode or if in C++.
2764 // Otherwise, warn that it is incompatible with standards before C11 if in
2766 Diag(Tok
, getLangOpts().C11
? diag::warn_c11_compat_keyword
2767 : diag::ext_c11_feature
)
2771 bool BalancedDelimiterTracker::diagnoseOverflow() {
2772 P
.Diag(P
.Tok
, diag::err_bracket_depth_exceeded
)
2773 << P
.getLangOpts().BracketDepth
;
2774 P
.Diag(P
.Tok
, diag::note_bracket_depth
);
2779 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID
,
2781 tok::TokenKind SkipToTok
) {
2782 LOpen
= P
.Tok
.getLocation();
2783 if (P
.ExpectAndConsume(Kind
, DiagID
, Msg
)) {
2784 if (SkipToTok
!= tok::unknown
)
2785 P
.SkipUntil(SkipToTok
, Parser::StopAtSemi
);
2789 if (getDepth() < P
.getLangOpts().BracketDepth
)
2792 return diagnoseOverflow();
2795 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2796 assert(!P
.Tok
.is(Close
) && "Should have consumed closing delimiter");
2798 if (P
.Tok
.is(tok::annot_module_end
))
2799 P
.Diag(P
.Tok
, diag::err_missing_before_module_end
) << Close
;
2801 P
.Diag(P
.Tok
, diag::err_expected
) << Close
;
2802 P
.Diag(LOpen
, diag::note_matching
) << Kind
;
2804 // If we're not already at some kind of closing bracket, skip to our closing
2806 if (P
.Tok
.isNot(tok::r_paren
) && P
.Tok
.isNot(tok::r_brace
) &&
2807 P
.Tok
.isNot(tok::r_square
) &&
2808 P
.SkipUntil(Close
, FinalToken
,
2809 Parser::StopAtSemi
| Parser::StopBeforeMatch
) &&
2811 LClose
= P
.ConsumeAnyToken();
2815 void BalancedDelimiterTracker::skipToEnd() {
2816 P
.SkipUntil(Close
, Parser::StopBeforeMatch
);