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