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/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/Path.h"
23 using namespace clang;
27 /// A comment handler that passes comments found by the preprocessor
28 /// to the parser action.
29 class ActionCommentHandler : public CommentHandler {
33 explicit ActionCommentHandler(Sema &S) : S(S) { }
35 bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
36 S.ActOnComment(Comment);
40 } // end anonymous namespace
42 IdentifierInfo *Parser::getSEHExceptKeyword() {
43 // __except is accepted as a (contextual) keyword
44 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
45 Ident__except = PP.getIdentifierInfo("__except");
50 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
51 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
52 GreaterThanIsOperator(true), ColonIsSacred(false),
53 InMessageExpression(false), TemplateParameterDepth(0),
54 ParsingInObjCContainer(false) {
55 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57 Tok.setKind(tok::eof);
58 Actions.CurScope = nullptr;
60 CurParsedObjCImpl = nullptr;
62 // Add #pragma handlers. These are removed and destroyed in the
64 initializePragmaHandlers();
66 CommentSemaHandler.reset(new ActionCommentHandler(actions));
67 PP.addCommentHandler(CommentSemaHandler.get());
69 PP.setCodeCompletionHandler(*this);
72 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
73 return Diags.Report(Loc, DiagID);
76 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
77 return Diag(Tok.getLocation(), DiagID);
80 /// Emits a diagnostic suggesting parentheses surrounding a
83 /// \param Loc The location where we'll emit the diagnostic.
84 /// \param DK The kind of diagnostic to emit.
85 /// \param ParenRange Source range enclosing code that should be parenthesized.
86 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
87 SourceRange ParenRange) {
88 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
89 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
90 // We can't display the parentheses, so just dig the
91 // warning/error and return.
97 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
98 << FixItHint::CreateInsertion(EndLoc, ")");
101 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
102 switch (ExpectedTok) {
104 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
105 default: return false;
109 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
111 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
116 // Detect common single-character typos and resume.
117 if (IsCommonTypo(ExpectedTok, Tok)) {
118 SourceLocation Loc = Tok.getLocation();
120 DiagnosticBuilder DB = Diag(Loc, DiagID);
121 DB << FixItHint::CreateReplacement(
122 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
123 if (DiagID == diag::err_expected)
125 else if (DiagID == diag::err_expected_after)
126 DB << Msg << ExpectedTok;
131 // Pretend there wasn't a problem.
136 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
137 const char *Spelling = nullptr;
138 if (EndLoc.isValid())
139 Spelling = tok::getPunctuatorSpelling(ExpectedTok);
141 DiagnosticBuilder DB =
143 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
145 if (DiagID == diag::err_expected)
147 else if (DiagID == diag::err_expected_after)
148 DB << Msg << ExpectedTok;
155 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
156 if (TryConsumeToken(tok::semi))
159 if (Tok.is(tok::code_completion)) {
160 handleUnexpectedCodeCompletionToken();
164 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
165 NextToken().is(tok::semi)) {
166 Diag(Tok, diag::err_extraneous_token_before_semi)
167 << PP.getSpelling(Tok)
168 << FixItHint::CreateRemoval(Tok.getLocation());
169 ConsumeAnyToken(); // The ')' or ']'.
170 ConsumeToken(); // The ';'.
174 return ExpectAndConsume(tok::semi, DiagID);
177 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
178 if (!Tok.is(tok::semi)) return;
180 bool HadMultipleSemis = false;
181 SourceLocation StartLoc = Tok.getLocation();
182 SourceLocation EndLoc = Tok.getLocation();
185 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
186 HadMultipleSemis = true;
187 EndLoc = Tok.getLocation();
191 // C++11 allows extra semicolons at namespace scope, but not in any of the
193 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
194 if (getLangOpts().CPlusPlus11)
195 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
196 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
198 Diag(StartLoc, diag::ext_extra_semi_cxx11)
199 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
203 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
204 Diag(StartLoc, diag::ext_extra_semi)
205 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
206 Actions.getASTContext().getPrintingPolicy())
207 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
209 // A single semicolon is valid after a member function definition.
210 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
211 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
214 bool Parser::expectIdentifier() {
215 if (Tok.is(tok::identifier))
217 if (const auto *II = Tok.getIdentifierInfo()) {
218 if (II->isCPlusPlusKeyword(getLangOpts())) {
219 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
220 << tok::identifier << Tok.getIdentifierInfo();
221 // Objective-C++: Recover by treating this keyword as a valid identifier.
225 Diag(Tok, diag::err_expected) << tok::identifier;
229 //===----------------------------------------------------------------------===//
231 //===----------------------------------------------------------------------===//
233 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
234 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
237 /// SkipUntil - Read tokens until we get to the specified token, then consume
238 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
239 /// token will ever occur, this skips to the next token, or to some likely
240 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
243 /// If SkipUntil finds the specified token, it returns true, otherwise it
245 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
246 // We always want this function to skip at least one token if the first token
247 // isn't T and if not at EOF.
248 bool isFirstTokenSkipped = true;
250 // If we found one of the tokens, stop and return true.
251 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
252 if (Tok.is(Toks[i])) {
253 if (HasFlagsSet(Flags, StopBeforeMatch)) {
254 // Noop, don't consume the token.
262 // Important special case: The caller has given up and just wants us to
263 // skip the rest of the file. Do this without recursing, since we can
264 // get here precisely because the caller detected too much recursion.
265 if (Toks.size() == 1 && Toks[0] == tok::eof &&
266 !HasFlagsSet(Flags, StopAtSemi) &&
267 !HasFlagsSet(Flags, StopAtCodeCompletion)) {
268 while (Tok.isNot(tok::eof))
273 switch (Tok.getKind()) {
275 // Ran out of tokens.
278 case tok::annot_pragma_openmp:
279 case tok::annot_pragma_openmp_end:
280 // Stop before an OpenMP pragma boundary.
281 case tok::annot_module_begin:
282 case tok::annot_module_end:
283 case tok::annot_module_include:
284 // Stop before we change submodules. They generally indicate a "good"
285 // place to pick up parsing again (except in the special case where
286 // we're trying to skip to EOF).
289 case tok::code_completion:
290 if (!HasFlagsSet(Flags, StopAtCodeCompletion))
291 handleUnexpectedCodeCompletionToken();
295 // Recursively skip properly-nested parens.
297 if (HasFlagsSet(Flags, StopAtCodeCompletion))
298 SkipUntil(tok::r_paren, StopAtCodeCompletion);
300 SkipUntil(tok::r_paren);
303 // Recursively skip properly-nested square brackets.
305 if (HasFlagsSet(Flags, StopAtCodeCompletion))
306 SkipUntil(tok::r_square, StopAtCodeCompletion);
308 SkipUntil(tok::r_square);
311 // Recursively skip properly-nested braces.
313 if (HasFlagsSet(Flags, StopAtCodeCompletion))
314 SkipUntil(tok::r_brace, StopAtCodeCompletion);
316 SkipUntil(tok::r_brace);
319 // Recursively skip ? ... : pairs; these function as brackets. But
320 // still stop at a semicolon if requested.
322 SkipUntil(tok::colon,
323 SkipUntilFlags(unsigned(Flags) &
324 unsigned(StopAtCodeCompletion | StopAtSemi)));
327 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
328 // Since the user wasn't looking for this token (if they were, it would
329 // already be handled), this isn't balanced. If there is a LHS token at a
330 // higher level, we will assume that this matches the unbalanced token
331 // and return it. Otherwise, this is a spurious RHS token, which we skip.
333 if (ParenCount && !isFirstTokenSkipped)
334 return false; // Matches something.
338 if (BracketCount && !isFirstTokenSkipped)
339 return false; // Matches something.
343 if (BraceCount && !isFirstTokenSkipped)
344 return false; // Matches something.
349 if (HasFlagsSet(Flags, StopAtSemi))
357 isFirstTokenSkipped = false;
361 //===----------------------------------------------------------------------===//
362 // Scope manipulation
363 //===----------------------------------------------------------------------===//
365 /// EnterScope - Start a new scope.
366 void Parser::EnterScope(unsigned ScopeFlags) {
367 if (NumCachedScopes) {
368 Scope *N = ScopeCache[--NumCachedScopes];
369 N->Init(getCurScope(), ScopeFlags);
370 Actions.CurScope = N;
372 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
376 /// ExitScope - Pop a scope off the scope stack.
377 void Parser::ExitScope() {
378 assert(getCurScope() && "Scope imbalance!");
380 // Inform the actions module that this scope is going away if there are any
382 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
384 Scope *OldScope = getCurScope();
385 Actions.CurScope = OldScope->getParent();
387 if (NumCachedScopes == ScopeCacheSize)
390 ScopeCache[NumCachedScopes++] = OldScope;
393 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
394 /// this object does nothing.
395 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
397 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
399 OldFlags = CurScope->getFlags();
400 CurScope->setFlags(ScopeFlags);
404 /// Restore the flags for the current scope to what they were before this
405 /// object overrode them.
406 Parser::ParseScopeFlags::~ParseScopeFlags() {
408 CurScope->setFlags(OldFlags);
412 //===----------------------------------------------------------------------===//
413 // C99 6.9: External Definitions.
414 //===----------------------------------------------------------------------===//
417 // If we still have scopes active, delete the scope tree.
418 delete getCurScope();
419 Actions.CurScope = nullptr;
421 // Free the scope cache.
422 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
423 delete ScopeCache[i];
425 resetPragmaHandlers();
427 PP.removeCommentHandler(CommentSemaHandler.get());
429 PP.clearCodeCompletionHandler();
431 if (getLangOpts().DelayedTemplateParsing &&
432 !PP.isIncrementalProcessingEnabled() && !TemplateIds.empty()) {
433 // If an ASTConsumer parsed delay-parsed templates in their
434 // HandleTranslationUnit() method, TemplateIds created there were not
435 // guarded by a DestroyTemplateIdAnnotationsRAIIObj object in
436 // ParseTopLevelDecl(). Destroy them here.
437 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
440 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
443 /// Initialize - Warm up the parser.
445 void Parser::Initialize() {
446 // Create the translation unit scope. Install it as the current scope.
447 assert(getCurScope() == nullptr && "A scope is already active?");
448 EnterScope(Scope::DeclScope);
449 Actions.ActOnTranslationUnitScope(getCurScope());
451 // Initialization for Objective-C context sensitive keywords recognition.
452 // Referenced in Parser::ParseObjCTypeQualifierList.
453 if (getLangOpts().ObjC) {
454 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
455 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
456 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
457 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
458 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
459 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
460 ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
461 ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
462 ObjCTypeQuals[objc_null_unspecified]
463 = &PP.getIdentifierTable().get("null_unspecified");
466 Ident_instancetype = nullptr;
467 Ident_final = nullptr;
468 Ident_sealed = nullptr;
469 Ident_override = nullptr;
470 Ident_GNU_final = nullptr;
471 Ident_import = nullptr;
472 Ident_module = nullptr;
474 Ident_super = &PP.getIdentifierTable().get("super");
476 Ident_vector = nullptr;
477 Ident_bool = nullptr;
478 Ident_pixel = nullptr;
479 if (getLangOpts().AltiVec || getLangOpts().ZVector) {
480 Ident_vector = &PP.getIdentifierTable().get("vector");
481 Ident_bool = &PP.getIdentifierTable().get("bool");
483 if (getLangOpts().AltiVec)
484 Ident_pixel = &PP.getIdentifierTable().get("pixel");
486 Ident_introduced = nullptr;
487 Ident_deprecated = nullptr;
488 Ident_obsoleted = nullptr;
489 Ident_unavailable = nullptr;
490 Ident_strict = nullptr;
491 Ident_replacement = nullptr;
493 Ident_language = Ident_defined_in = Ident_generated_declaration = nullptr;
495 Ident__except = nullptr;
497 Ident__exception_code = Ident__exception_info = nullptr;
498 Ident__abnormal_termination = Ident___exception_code = nullptr;
499 Ident___exception_info = Ident___abnormal_termination = nullptr;
500 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
501 Ident_AbnormalTermination = nullptr;
503 if(getLangOpts().Borland) {
504 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
505 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
506 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
507 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
508 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
509 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
510 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
511 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
512 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
514 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
515 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
516 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
517 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
518 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
519 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
520 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
521 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
522 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
525 if (getLangOpts().CPlusPlusModules) {
526 Ident_import = PP.getIdentifierInfo("import");
527 Ident_module = PP.getIdentifierInfo("module");
530 Actions.Initialize();
532 // Prime the lexer look-ahead.
536 void Parser::LateTemplateParserCleanupCallback(void *P) {
537 // While this RAII helper doesn't bracket any actual work, the destructor will
538 // clean up annotations that were created during ActOnEndOfTranslationUnit
539 // when incremental processing is enabled.
540 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
543 /// Parse the first top-level declaration in a translation unit.
545 /// translation-unit:
546 /// [C] external-declaration
547 /// [C] translation-unit external-declaration
548 /// [C++] top-level-declaration-seq[opt]
549 /// [C++20] global-module-fragment[opt] module-declaration
550 /// top-level-declaration-seq[opt] private-module-fragment[opt]
552 /// Note that in C, it is an error if there is no first declaration.
553 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result) {
554 Actions.ActOnStartOfTranslationUnit();
556 // C11 6.9p1 says translation units must have at least one top-level
557 // declaration. C++ doesn't have this restriction. We also don't want to
558 // complain if we have a precompiled header, although technically if the PCH
559 // is empty we should still emit the (pedantic) diagnostic.
560 bool NoTopLevelDecls = ParseTopLevelDecl(Result, true);
561 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
562 !getLangOpts().CPlusPlus)
563 Diag(diag::ext_empty_translation_unit);
565 return NoTopLevelDecls;
568 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
569 /// action tells us to. This returns true if the EOF was encountered.
571 /// top-level-declaration:
573 /// [C++20] module-import-declaration
574 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl) {
575 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
577 // Skip over the EOF token, flagging end of previous input for incremental
579 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
583 switch (Tok.getKind()) {
584 case tok::annot_pragma_unused:
585 HandlePragmaUnused();
589 switch (NextToken().getKind()) {
593 // Note: no need to handle kw_import here. We only form kw_import under
594 // the Modules TS, and in that case 'export import' is parsed as an
595 // export-declaration containing an import-declaration.
597 // Recognize context-sensitive C++20 'export module' and 'export import'
599 case tok::identifier: {
600 IdentifierInfo *II = NextToken().getIdentifierInfo();
601 if ((II == Ident_module || II == Ident_import) &&
602 GetLookAheadToken(2).isNot(tok::coloncolon)) {
603 if (II == Ident_module)
618 Result = ParseModuleDecl(IsFirstDecl);
621 // tok::kw_import is handled by ParseExternalDeclaration. (Under the Modules
622 // TS, an import can occur within an export block.)
624 Decl *ImportDecl = ParseModuleImport(SourceLocation());
625 Result = Actions.ConvertDeclToDeclGroup(ImportDecl);
629 case tok::annot_module_include:
630 Actions.ActOnModuleInclude(Tok.getLocation(),
631 reinterpret_cast<Module *>(
632 Tok.getAnnotationValue()));
633 ConsumeAnnotationToken();
636 case tok::annot_module_begin:
637 Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
638 Tok.getAnnotationValue()));
639 ConsumeAnnotationToken();
642 case tok::annot_module_end:
643 Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
644 Tok.getAnnotationValue()));
645 ConsumeAnnotationToken();
649 // Late template parsing can begin.
650 if (getLangOpts().DelayedTemplateParsing)
651 Actions.SetLateTemplateParser(LateTemplateParserCallback,
652 PP.isIncrementalProcessingEnabled() ?
653 LateTemplateParserCleanupCallback : nullptr,
655 if (!PP.isIncrementalProcessingEnabled())
656 Actions.ActOnEndOfTranslationUnit();
657 //else don't tell Sema that we ended parsing: more input might come.
660 case tok::identifier:
661 // C++2a [basic.link]p3:
662 // A token sequence beginning with 'export[opt] module' or
663 // 'export[opt] import' and not immediately followed by '::'
664 // is never interpreted as the declaration of a top-level-declaration.
665 if ((Tok.getIdentifierInfo() == Ident_module ||
666 Tok.getIdentifierInfo() == Ident_import) &&
667 NextToken().isNot(tok::coloncolon)) {
668 if (Tok.getIdentifierInfo() == Ident_module)
679 ParsedAttributesWithRange attrs(AttrFactory);
680 MaybeParseCXX11Attributes(attrs);
682 Result = ParseExternalDeclaration(attrs);
686 /// ParseExternalDeclaration:
688 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
689 /// function-definition
691 /// [GNU] asm-definition
692 /// [GNU] __extension__ external-declaration
693 /// [OBJC] objc-class-definition
694 /// [OBJC] objc-class-declaration
695 /// [OBJC] objc-alias-declaration
696 /// [OBJC] objc-protocol-definition
697 /// [OBJC] objc-method-definition
699 /// [C++] linkage-specification
700 /// [GNU] asm-definition:
701 /// simple-asm-expr ';'
702 /// [C++11] empty-declaration
703 /// [C++11] attribute-declaration
705 /// [C++11] empty-declaration:
708 /// [C++0x/GNU] 'extern' 'template' declaration
710 /// [Modules-TS] module-import-declaration
712 Parser::DeclGroupPtrTy
713 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
714 ParsingDeclSpec *DS) {
715 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
716 ParenBraceBracketBalancer BalancerRAIIObj(*this);
718 if (PP.isCodeCompletionReached()) {
723 Decl *SingleDecl = nullptr;
724 switch (Tok.getKind()) {
725 case tok::annot_pragma_vis:
726 HandlePragmaVisibility();
728 case tok::annot_pragma_pack:
731 case tok::annot_pragma_msstruct:
732 HandlePragmaMSStruct();
734 case tok::annot_pragma_align:
737 case tok::annot_pragma_weak:
740 case tok::annot_pragma_weakalias:
741 HandlePragmaWeakAlias();
743 case tok::annot_pragma_redefine_extname:
744 HandlePragmaRedefineExtname();
746 case tok::annot_pragma_fp_contract:
747 HandlePragmaFPContract();
749 case tok::annot_pragma_fenv_access:
750 HandlePragmaFEnvAccess();
752 case tok::annot_pragma_fp:
755 case tok::annot_pragma_opencl_extension:
756 HandlePragmaOpenCLExtension();
758 case tok::annot_pragma_openmp: {
759 AccessSpecifier AS = AS_none;
760 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
762 case tok::annot_pragma_ms_pointers_to_members:
763 HandlePragmaMSPointersToMembers();
765 case tok::annot_pragma_ms_vtordisp:
766 HandlePragmaMSVtorDisp();
768 case tok::annot_pragma_ms_pragma:
769 HandlePragmaMSPragma();
771 case tok::annot_pragma_dump:
774 case tok::annot_pragma_attribute:
775 HandlePragmaAttribute();
778 // Either a C++11 empty-declaration or attribute-declaration.
780 Actions.ActOnEmptyDeclaration(getCurScope(), attrs, Tok.getLocation());
781 ConsumeExtraSemi(OutsideFunction);
784 Diag(Tok, diag::err_extraneous_closing_brace);
788 Diag(Tok, diag::err_expected_external_declaration);
790 case tok::kw___extension__: {
791 // __extension__ silences extension warnings in the subexpression.
792 ExtensionRAIIObject O(Diags); // Use RAII to do this.
794 return ParseExternalDeclaration(attrs);
797 ProhibitAttributes(attrs);
799 SourceLocation StartLoc = Tok.getLocation();
800 SourceLocation EndLoc;
802 ExprResult Result(ParseSimpleAsm(&EndLoc));
804 // Check if GNU-style InlineAsm is disabled.
805 // Empty asm string is allowed because it will not introduce
806 // any assembly code.
807 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
808 const auto *SL = cast<StringLiteral>(Result.get());
809 if (!SL->getString().trim().empty())
810 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
813 ExpectAndConsume(tok::semi, diag::err_expected_after,
814 "top-level asm block");
816 if (Result.isInvalid())
818 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
822 return ParseObjCAtDirectives(attrs);
825 if (!getLangOpts().ObjC) {
826 Diag(Tok, diag::err_expected_external_declaration);
830 SingleDecl = ParseObjCMethodDefinition();
832 case tok::code_completion:
833 if (CurParsedObjCImpl) {
834 // Code-complete Objective-C methods even without leading '-'/'+' prefix.
835 Actions.CodeCompleteObjCMethodDecl(getCurScope(),
836 /*IsInstanceMethod=*/None,
837 /*ReturnType=*/nullptr);
839 Actions.CodeCompleteOrdinaryName(
841 CurParsedObjCImpl ? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace);
845 SingleDecl = ParseModuleImport(SourceLocation());
848 if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
849 SingleDecl = ParseExportDeclaration();
852 // This must be 'export template'. Parse it so we can diagnose our lack
856 case tok::kw_namespace:
857 case tok::kw_typedef:
858 case tok::kw_template:
859 case tok::kw_static_assert:
860 case tok::kw__Static_assert:
861 // A function definition cannot start with any of these keywords.
863 SourceLocation DeclEnd;
864 return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
868 // Parse (then ignore) 'static' prior to a template instantiation. This is
869 // a GCC extension that we intentionally do not support.
870 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
871 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
873 SourceLocation DeclEnd;
874 return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
879 if (getLangOpts().CPlusPlus) {
880 tok::TokenKind NextKind = NextToken().getKind();
882 // Inline namespaces. Allowed as an extension even in C++03.
883 if (NextKind == tok::kw_namespace) {
884 SourceLocation DeclEnd;
885 return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
888 // Parse (then ignore) 'inline' prior to a template instantiation. This is
889 // a GCC extension that we intentionally do not support.
890 if (NextKind == tok::kw_template) {
891 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
893 SourceLocation DeclEnd;
894 return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs);
900 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
902 SourceLocation ExternLoc = ConsumeToken();
903 SourceLocation TemplateLoc = ConsumeToken();
904 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
905 diag::warn_cxx98_compat_extern_template :
906 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
907 SourceLocation DeclEnd;
908 return Actions.ConvertDeclToDeclGroup(
909 ParseExplicitInstantiation(DeclaratorContext::FileContext, ExternLoc,
910 TemplateLoc, DeclEnd, attrs));
914 case tok::kw___if_exists:
915 case tok::kw___if_not_exists:
916 ParseMicrosoftIfExistsExternalDeclaration();
920 Diag(Tok, diag::err_unexpected_module_decl);
921 SkipUntil(tok::semi);
926 if (Tok.isEditorPlaceholder()) {
930 // We can't tell whether this is a function-definition or declaration yet.
931 return ParseDeclarationOrFunctionDefinition(attrs, DS);
934 // This routine returns a DeclGroup, if the thing we parsed only contains a
935 // single decl, convert it now.
936 return Actions.ConvertDeclToDeclGroup(SingleDecl);
939 /// Determine whether the current token, if it occurs after a
940 /// declarator, continues a declaration or declaration list.
941 bool Parser::isDeclarationAfterDeclarator() {
942 // Check for '= delete' or '= default'
943 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
944 const Token &KW = NextToken();
945 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
949 return Tok.is(tok::equal) || // int X()= -> not a function def
950 Tok.is(tok::comma) || // int X(), -> not a function def
951 Tok.is(tok::semi) || // int X(); -> not a function def
952 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
953 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
954 (getLangOpts().CPlusPlus &&
955 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
958 /// Determine whether the current token, if it occurs after a
959 /// declarator, indicates the start of a function definition.
960 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
961 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
962 if (Tok.is(tok::l_brace)) // int X() {}
965 // Handle K&R C argument lists: int X(f) int f; {}
966 if (!getLangOpts().CPlusPlus &&
967 Declarator.getFunctionTypeInfo().isKNRPrototype())
968 return isDeclarationSpecifier();
970 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
971 const Token &KW = NextToken();
972 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
975 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
976 Tok.is(tok::kw_try); // X() try { ... }
979 /// Parse either a function-definition or a declaration. We can't tell which
980 /// we have until we read up to the compound-statement in function-definition.
981 /// TemplateParams, if non-NULL, provides the template parameters when we're
982 /// parsing a C++ template-declaration.
984 /// function-definition: [C99 6.9.1]
985 /// decl-specs declarator declaration-list[opt] compound-statement
986 /// [C90] function-definition: [C99 6.7.1] - implicit int result
987 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
989 /// declaration: [C99 6.7]
990 /// declaration-specifiers init-declarator-list[opt] ';'
991 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
992 /// [OMP] threadprivate-directive
993 /// [OMP] allocate-directive [TODO]
995 Parser::DeclGroupPtrTy
996 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
998 AccessSpecifier AS) {
999 MaybeParseMicrosoftAttributes(DS.getAttributes());
1000 // Parse the common declaration-specifiers piece.
1001 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS,
1002 DeclSpecContext::DSC_top_level);
1004 // If we had a free-standing type definition with a missing semicolon, we
1005 // may get this far before the problem becomes obvious.
1006 if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(
1007 DS, AS, DeclSpecContext::DSC_top_level))
1010 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1011 // declaration-specifiers init-declarator-list[opt] ';'
1012 if (Tok.is(tok::semi)) {
1013 auto LengthOfTSTToken = [](DeclSpec::TST TKind) {
1014 assert(DeclSpec::isDeclRep(TKind));
1016 case DeclSpec::TST_class:
1018 case DeclSpec::TST_struct:
1020 case DeclSpec::TST_union:
1022 case DeclSpec::TST_enum:
1024 case DeclSpec::TST_interface:
1027 llvm_unreachable("we only expect to get the length of the class/struct/union/enum");
1031 // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'
1032 SourceLocation CorrectLocationForAttributes =
1033 DeclSpec::isDeclRep(DS.getTypeSpecType())
1034 ? DS.getTypeSpecTypeLoc().getLocWithOffset(
1035 LengthOfTSTToken(DS.getTypeSpecType()))
1037 ProhibitAttributes(attrs, CorrectLocationForAttributes);
1039 RecordDecl *AnonRecord = nullptr;
1040 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1042 DS.complete(TheDecl);
1043 if (getLangOpts().OpenCL)
1044 Actions.setCurrentOpenCLExtensionForDecl(TheDecl);
1046 Decl* decls[] = {AnonRecord, TheDecl};
1047 return Actions.BuildDeclaratorGroup(decls);
1049 return Actions.ConvertDeclToDeclGroup(TheDecl);
1052 DS.takeAttributesFrom(attrs);
1054 // ObjC2 allows prefix attributes on class interfaces and protocols.
1055 // FIXME: This still needs better diagnostics. We should only accept
1056 // attributes here, no types, etc.
1057 if (getLangOpts().ObjC && Tok.is(tok::at)) {
1058 SourceLocation AtLoc = ConsumeToken(); // the "@"
1059 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1060 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1061 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1062 Diag(Tok, diag::err_objc_unexpected_attr);
1063 SkipUntil(tok::semi);
1069 const char *PrevSpec = nullptr;
1071 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
1072 Actions.getASTContext().getPrintingPolicy()))
1073 Diag(AtLoc, DiagID) << PrevSpec;
1075 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1076 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
1078 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1079 return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());
1081 return Actions.ConvertDeclToDeclGroup(
1082 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
1085 // If the declspec consisted only of 'extern' and we have a string
1086 // literal following it, this must be a C++ linkage specifier like
1088 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
1089 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
1090 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
1091 Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::FileContext);
1092 return Actions.ConvertDeclToDeclGroup(TheDecl);
1095 return ParseDeclGroup(DS, DeclaratorContext::FileContext);
1098 Parser::DeclGroupPtrTy
1099 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
1100 ParsingDeclSpec *DS,
1101 AccessSpecifier AS) {
1103 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
1105 ParsingDeclSpec PDS(*this);
1106 // Must temporarily exit the objective-c container scope for
1107 // parsing c constructs and re-enter objc container scope
1109 ObjCDeclContextSwitch ObjCDC(*this);
1111 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1115 /// ParseFunctionDefinition - We parsed and verified that the specified
1116 /// Declarator is well formed. If this is a K&R-style function, read the
1117 /// parameters declaration-list, then start the compound-statement.
1119 /// function-definition: [C99 6.9.1]
1120 /// decl-specs declarator declaration-list[opt] compound-statement
1121 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1122 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1123 /// [C++] function-definition: [C++ 8.4]
1124 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1126 /// [C++] function-definition: [C++ 8.4]
1127 /// decl-specifier-seq[opt] declarator function-try-block
1129 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1130 const ParsedTemplateInfo &TemplateInfo,
1131 LateParsedAttrList *LateParsedAttrs) {
1132 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1133 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1134 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1136 // If this is C90 and the declspecs were completely missing, fudge in an
1137 // implicit int. We do this here because this is the only place where
1138 // declaration-specifiers are completely optional in the grammar.
1139 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
1140 const char *PrevSpec;
1142 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1143 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1144 D.getIdentifierLoc(),
1147 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1150 // If this declaration was formed with a K&R-style identifier list for the
1151 // arguments, parse declarations for all of the args next.
1152 // int foo(a,b) int a; float b; {}
1153 if (FTI.isKNRPrototype())
1154 ParseKNRParamDeclarations(D);
1156 // We should have either an opening brace or, in a C++ constructor,
1157 // we may have a colon.
1158 if (Tok.isNot(tok::l_brace) &&
1159 (!getLangOpts().CPlusPlus ||
1160 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1161 Tok.isNot(tok::equal)))) {
1162 Diag(Tok, diag::err_expected_fn_body);
1164 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1165 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1167 // If we didn't find the '{', bail out.
1168 if (Tok.isNot(tok::l_brace))
1172 // Check to make sure that any normal attributes are allowed to be on
1173 // a definition. Late parsed attributes are checked at the end.
1174 if (Tok.isNot(tok::equal)) {
1175 for (const ParsedAttr &AL : D.getAttributes())
1176 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
1177 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition)
1181 // In delayed template parsing mode, for function template we consume the
1182 // tokens and store them for late parsing at the end of the translation unit.
1183 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1184 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1185 Actions.canDelayFunctionBody(D)) {
1186 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1188 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1189 Scope::CompoundStmtScope);
1190 Scope *ParentScope = getCurScope()->getParent();
1192 D.setFunctionDefinitionKind(FDK_Definition);
1193 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1194 TemplateParameterLists);
1196 D.getMutableDeclSpec().abort();
1198 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1199 trySkippingFunctionBody()) {
1201 return Actions.ActOnSkippedFunctionBody(DP);
1205 LexTemplateFunctionForLateParsing(Toks);
1208 FunctionDecl *FnD = DP->getAsFunction();
1209 Actions.CheckForFunctionRedefinition(FnD);
1210 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1214 else if (CurParsedObjCImpl &&
1215 !TemplateInfo.TemplateParams &&
1216 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1217 Tok.is(tok::colon)) &&
1218 Actions.CurContext->isTranslationUnit()) {
1219 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1220 Scope::CompoundStmtScope);
1221 Scope *ParentScope = getCurScope()->getParent();
1223 D.setFunctionDefinitionKind(FDK_Definition);
1224 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1225 MultiTemplateParamsArg());
1226 D.complete(FuncDecl);
1227 D.getMutableDeclSpec().abort();
1229 // Consume the tokens and store them for later parsing.
1230 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1231 CurParsedObjCImpl->HasCFunction = true;
1234 // FIXME: Should we really fall through here?
1237 // Enter a scope for the function body.
1238 ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
1239 Scope::CompoundStmtScope);
1241 // Tell the actions module that we have entered a function definition with the
1242 // specified Declarator for the function.
1243 Sema::SkipBodyInfo SkipBody;
1244 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1245 TemplateInfo.TemplateParams
1246 ? *TemplateInfo.TemplateParams
1247 : MultiTemplateParamsArg(),
1250 if (SkipBody.ShouldSkip) {
1255 // Break out of the ParsingDeclarator context before we parse the body.
1258 // Break out of the ParsingDeclSpec context, too. This const_cast is
1259 // safe because we're always the sole owner.
1260 D.getMutableDeclSpec().abort();
1262 if (TryConsumeToken(tok::equal)) {
1263 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1265 bool Delete = false;
1266 SourceLocation KWLoc;
1267 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1268 Diag(KWLoc, getLangOpts().CPlusPlus11
1269 ? diag::warn_cxx98_compat_defaulted_deleted_function
1270 : diag::ext_defaulted_deleted_function)
1272 Actions.SetDeclDeleted(Res, KWLoc);
1274 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1275 Diag(KWLoc, getLangOpts().CPlusPlus11
1276 ? diag::warn_cxx98_compat_defaulted_deleted_function
1277 : diag::ext_defaulted_deleted_function)
1278 << 0 /* defaulted */;
1279 Actions.SetDeclDefaulted(Res, KWLoc);
1281 llvm_unreachable("function definition after = not 'delete' or 'default'");
1284 if (Tok.is(tok::comma)) {
1285 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1287 SkipUntil(tok::semi);
1288 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1289 Delete ? "delete" : "default")) {
1290 SkipUntil(tok::semi);
1293 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1294 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1298 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1299 trySkippingFunctionBody()) {
1301 Actions.ActOnSkippedFunctionBody(Res);
1302 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1305 if (Tok.is(tok::kw_try))
1306 return ParseFunctionTryBlock(Res, BodyScope);
1308 // If we have a colon, then we're probably parsing a C++
1309 // ctor-initializer.
1310 if (Tok.is(tok::colon)) {
1311 ParseConstructorInitializer(Res);
1313 // Recover from error.
1314 if (!Tok.is(tok::l_brace)) {
1316 Actions.ActOnFinishFunctionBody(Res, nullptr);
1320 Actions.ActOnDefaultCtorInitializers(Res);
1322 // Late attributes are parsed in the same scope as the function body.
1323 if (LateParsedAttrs)
1324 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1326 return ParseFunctionStatementBody(Res, BodyScope);
1329 void Parser::SkipFunctionBody() {
1330 if (Tok.is(tok::equal)) {
1331 SkipUntil(tok::semi);
1335 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1336 if (IsFunctionTryBlock)
1339 CachedTokens Skipped;
1340 if (ConsumeAndStoreFunctionPrologue(Skipped))
1341 SkipMalformedDecl();
1343 SkipUntil(tok::r_brace);
1344 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1345 SkipUntil(tok::l_brace);
1346 SkipUntil(tok::r_brace);
1351 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1352 /// types for a function with a K&R-style identifier list for arguments.
1353 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1354 // We know that the top-level of this declarator is a function.
1355 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1357 // Enter function-declaration scope, limiting any declarators to the
1358 // function prototype scope, including parameter declarators.
1359 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1360 Scope::FunctionDeclarationScope | Scope::DeclScope);
1362 // Read all the argument declarations.
1363 while (isDeclarationSpecifier()) {
1364 SourceLocation DSStart = Tok.getLocation();
1366 // Parse the common declaration-specifiers piece.
1367 DeclSpec DS(AttrFactory);
1368 ParseDeclarationSpecifiers(DS);
1370 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1371 // least one declarator'.
1372 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1373 // the declarations though. It's trivial to ignore them, really hard to do
1374 // anything else with them.
1375 if (TryConsumeToken(tok::semi)) {
1376 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1380 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1382 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1383 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1384 Diag(DS.getStorageClassSpecLoc(),
1385 diag::err_invalid_storage_class_in_func_decl);
1386 DS.ClearStorageClassSpecs();
1388 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1389 Diag(DS.getThreadStorageClassSpecLoc(),
1390 diag::err_invalid_storage_class_in_func_decl);
1391 DS.ClearStorageClassSpecs();
1394 // Parse the first declarator attached to this declspec.
1395 Declarator ParmDeclarator(DS, DeclaratorContext::KNRTypeListContext);
1396 ParseDeclarator(ParmDeclarator);
1398 // Handle the full declarator list.
1400 // If attributes are present, parse them.
1401 MaybeParseGNUAttributes(ParmDeclarator);
1403 // Ask the actions module to compute the type for this declarator.
1405 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1408 // A missing identifier has already been diagnosed.
1409 ParmDeclarator.getIdentifier()) {
1411 // Scan the argument list looking for the correct param to apply this
1413 for (unsigned i = 0; ; ++i) {
1414 // C99 6.9.1p6: those declarators shall declare only identifiers from
1415 // the identifier list.
1416 if (i == FTI.NumParams) {
1417 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1418 << ParmDeclarator.getIdentifier();
1422 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1423 // Reject redefinitions of parameters.
1424 if (FTI.Params[i].Param) {
1425 Diag(ParmDeclarator.getIdentifierLoc(),
1426 diag::err_param_redefinition)
1427 << ParmDeclarator.getIdentifier();
1429 FTI.Params[i].Param = Param;
1436 // If we don't have a comma, it is either the end of the list (a ';') or
1437 // an error, bail out.
1438 if (Tok.isNot(tok::comma))
1441 ParmDeclarator.clear();
1443 // Consume the comma.
1444 ParmDeclarator.setCommaLoc(ConsumeToken());
1446 // Parse the next declarator.
1447 ParseDeclarator(ParmDeclarator);
1450 // Consume ';' and continue parsing.
1451 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1454 // Otherwise recover by skipping to next semi or mandatory function body.
1455 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1457 TryConsumeToken(tok::semi);
1460 // The actions module must verify that all arguments were declared.
1461 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1465 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1466 /// allowed to be a wide string, and is not subject to character translation.
1468 /// [GNU] asm-string-literal:
1471 ExprResult Parser::ParseAsmStringLiteral() {
1472 if (!isTokenStringLiteral()) {
1473 Diag(Tok, diag::err_expected_string_literal)
1474 << /*Source='in...'*/0 << "'asm'";
1478 ExprResult AsmString(ParseStringLiteralExpression());
1479 if (!AsmString.isInvalid()) {
1480 const auto *SL = cast<StringLiteral>(AsmString.get());
1481 if (!SL->isAscii()) {
1482 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1484 << SL->getSourceRange();
1493 /// [GNU] simple-asm-expr:
1494 /// 'asm' '(' asm-string-literal ')'
1496 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1497 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1498 SourceLocation Loc = ConsumeToken();
1500 if (Tok.is(tok::kw_volatile)) {
1501 // Remove from the end of 'asm' to the end of 'volatile'.
1502 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1503 PP.getLocForEndOfToken(Tok.getLocation()));
1505 Diag(Tok, diag::warn_file_asm_volatile)
1506 << FixItHint::CreateRemoval(RemovalRange);
1510 BalancedDelimiterTracker T(*this, tok::l_paren);
1511 if (T.consumeOpen()) {
1512 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1516 ExprResult Result(ParseAsmStringLiteral());
1518 if (!Result.isInvalid()) {
1519 // Close the paren and get the location of the end bracket
1522 *EndLoc = T.getCloseLocation();
1523 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1525 *EndLoc = Tok.getLocation();
1532 /// Get the TemplateIdAnnotation from the token and put it in the
1533 /// cleanup pool so that it gets destroyed when parsing the current top level
1534 /// declaration is finished.
1535 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1536 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1537 TemplateIdAnnotation *
1538 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1542 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1543 // Push the current token back into the token stream (or revert it if it is
1544 // cached) and use an annotation scope token for current token.
1545 if (PP.isBacktrackEnabled())
1546 PP.RevertCachedTokens(1);
1548 PP.EnterToken(Tok, /*IsReinject=*/true);
1549 Tok.setKind(tok::annot_cxxscope);
1550 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1551 Tok.setAnnotationRange(SS.getRange());
1553 // In case the tokens were cached, have Preprocessor replace them
1554 // with the annotation token. We don't need to do this if we've
1555 // just reverted back to a prior state.
1556 if (IsNewAnnotation)
1557 PP.AnnotateCachedTokens(Tok);
1560 /// Attempt to classify the name at the current token position. This may
1561 /// form a type, scope or primary expression annotation, or replace the token
1562 /// with a typo-corrected keyword. This is only appropriate when the current
1563 /// name must refer to an entity which has already been declared.
1565 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1566 /// and might possibly have a dependent nested name specifier.
1567 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1568 /// no typo correction will be performed.
1569 Parser::AnnotatedNameKind
1570 Parser::TryAnnotateName(bool IsAddressOfOperand,
1571 CorrectionCandidateCallback *CCC) {
1572 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1574 const bool EnteringContext = false;
1575 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1578 if (getLangOpts().CPlusPlus &&
1579 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1582 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1583 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1585 return ANK_Unresolved;
1588 IdentifierInfo *Name = Tok.getIdentifierInfo();
1589 SourceLocation NameLoc = Tok.getLocation();
1591 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1592 // typo-correct to tentatively-declared identifiers.
1593 if (isTentativelyDeclared(Name)) {
1594 // Identifier has been tentatively declared, and thus cannot be resolved as
1595 // an expression. Fall back to annotating it as a type.
1596 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1598 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1601 Token Next = NextToken();
1603 // Look up and classify the identifier. We don't perform any typo-correction
1604 // after a scope specifier, because in general we can't recover from typos
1605 // there (eg, after correcting 'A::template B<X>::C' [sic], we would need to
1606 // jump back into scope specifier parsing).
1607 Sema::NameClassification Classification =
1608 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1609 IsAddressOfOperand, SS.isEmpty() ? CCC : nullptr);
1611 // If name lookup found nothing and we guessed that this was a template name,
1612 // double-check before committing to that interpretation. C++20 requires that
1613 // we interpret this as a template-id if it can be, but if it can't be, then
1614 // this is an error recovery case.
1615 if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&
1616 isTemplateArgumentList(1) == TPResult::False) {
1617 // It's not a template-id; re-classify without the '<' as a hint.
1618 Token FakeNext = Next;
1619 FakeNext.setKind(tok::unknown);
1621 Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,
1622 IsAddressOfOperand, SS.isEmpty() ? CCC : nullptr);
1625 switch (Classification.getKind()) {
1626 case Sema::NC_Error:
1629 case Sema::NC_Keyword:
1630 // The identifier was typo-corrected to a keyword.
1631 Tok.setIdentifierInfo(Name);
1632 Tok.setKind(Name->getTokenID());
1633 PP.TypoCorrectToken(Tok);
1634 if (SS.isNotEmpty())
1635 AnnotateScopeToken(SS, !WasScopeAnnotation);
1636 // We've "annotated" this as a keyword.
1639 case Sema::NC_Unknown:
1640 // It's not something we know about. Leave it unannotated.
1643 case Sema::NC_Type: {
1644 SourceLocation BeginLoc = NameLoc;
1645 if (SS.isNotEmpty())
1646 BeginLoc = SS.getBeginLoc();
1648 /// An Objective-C object type followed by '<' is a specialization of
1649 /// a parameterized class type or a protocol-qualified type.
1650 ParsedType Ty = Classification.getType();
1651 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1652 (Ty.get()->isObjCObjectType() ||
1653 Ty.get()->isObjCObjectPointerType())) {
1654 // Consume the name.
1655 SourceLocation IdentifierLoc = ConsumeToken();
1656 SourceLocation NewEndLoc;
1658 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1659 /*consumeLastToken=*/false,
1661 if (NewType.isUsable())
1663 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1667 Tok.setKind(tok::annot_typename);
1668 setTypeAnnotation(Tok, Ty);
1669 Tok.setAnnotationEndLoc(Tok.getLocation());
1670 Tok.setLocation(BeginLoc);
1671 PP.AnnotateCachedTokens(Tok);
1675 case Sema::NC_Expression:
1676 Tok.setKind(tok::annot_primary_expr);
1677 setExprAnnotation(Tok, Classification.getExpression());
1678 Tok.setAnnotationEndLoc(NameLoc);
1679 if (SS.isNotEmpty())
1680 Tok.setLocation(SS.getBeginLoc());
1681 PP.AnnotateCachedTokens(Tok);
1684 case Sema::NC_TypeTemplate:
1685 if (Next.isNot(tok::less)) {
1686 // This may be a type template being used as a template template argument.
1687 if (SS.isNotEmpty())
1688 AnnotateScopeToken(SS, !WasScopeAnnotation);
1689 return ANK_TemplateName;
1692 case Sema::NC_VarTemplate:
1693 case Sema::NC_FunctionTemplate:
1694 case Sema::NC_UndeclaredTemplate: {
1695 // We have a type, variable or function template followed by '<'.
1698 Id.setIdentifier(Name, NameLoc);
1699 if (AnnotateTemplateIdToken(
1700 TemplateTy::make(Classification.getTemplateName()),
1701 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1706 case Sema::NC_NestedNameSpecifier:
1707 llvm_unreachable("already parsed nested name specifier");
1710 // Unable to classify the name, but maybe we can annotate a scope specifier.
1711 if (SS.isNotEmpty())
1712 AnnotateScopeToken(SS, !WasScopeAnnotation);
1713 return ANK_Unresolved;
1716 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1717 assert(Tok.isNot(tok::identifier));
1718 Diag(Tok, diag::ext_keyword_as_ident)
1719 << PP.getSpelling(Tok)
1722 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1723 Tok.setKind(tok::identifier);
1727 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1728 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1729 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1730 /// with a single annotation token representing the typename or C++ scope
1732 /// This simplifies handling of C++ scope specifiers and allows efficient
1733 /// backtracking without the need to re-parse and resolve nested-names and
1735 /// It will mainly be called when we expect to treat identifiers as typenames
1736 /// (if they are typenames). For example, in C we do not expect identifiers
1737 /// inside expressions to be treated as typenames so it will not be called
1738 /// for expressions in C.
1739 /// The benefit for C/ObjC is that a typename will be annotated and
1740 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1741 /// will not be called twice, once to check whether we have a declaration
1742 /// specifier, and another one to get the actual type inside
1743 /// ParseDeclarationSpecifiers).
1745 /// This returns true if an error occurred.
1747 /// Note that this routine emits an error if you call it with ::new or ::delete
1748 /// as the current tokens, so only call it in contexts where these are invalid.
1749 bool Parser::TryAnnotateTypeOrScopeToken() {
1750 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1751 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1752 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1753 Tok.is(tok::kw___super)) &&
1754 "Cannot be a type or scope token!");
1756 if (Tok.is(tok::kw_typename)) {
1757 // MSVC lets you do stuff like:
1758 // typename typedef T_::D D;
1760 // We will consume the typedef token here and put it back after we have
1761 // parsed the first identifier, transforming it into something more like:
1762 // typename T_::D typedef D;
1763 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1765 PP.Lex(TypedefToken);
1766 bool Result = TryAnnotateTypeOrScopeToken();
1767 PP.EnterToken(Tok, /*IsReinject=*/true);
1770 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1774 // Parse a C++ typename-specifier, e.g., "typename T::type".
1776 // typename-specifier:
1777 // 'typename' '::' [opt] nested-name-specifier identifier
1778 // 'typename' '::' [opt] nested-name-specifier template [opt]
1779 // simple-template-id
1780 SourceLocation TypenameLoc = ConsumeToken();
1782 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1783 /*EnteringContext=*/false, nullptr,
1784 /*IsTypename*/ true))
1787 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1788 Tok.is(tok::annot_decltype)) {
1789 // Attempt to recover by skipping the invalid 'typename'
1790 if (Tok.is(tok::annot_decltype) ||
1791 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
1792 unsigned DiagID = diag::err_expected_qualified_after_typename;
1793 // MS compatibility: MSVC permits using known types with typename.
1794 // e.g. "typedef typename T* pointer_type"
1795 if (getLangOpts().MicrosoftExt)
1796 DiagID = diag::warn_expected_qualified_after_typename;
1797 Diag(Tok.getLocation(), DiagID);
1801 if (Tok.isEditorPlaceholder())
1804 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1809 if (Tok.is(tok::identifier)) {
1810 // FIXME: check whether the next token is '<', first!
1811 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1812 *Tok.getIdentifierInfo(),
1814 } else if (Tok.is(tok::annot_template_id)) {
1815 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1816 if (TemplateId->Kind != TNK_Type_template &&
1817 TemplateId->Kind != TNK_Dependent_template_name &&
1818 TemplateId->Kind != TNK_Undeclared_template) {
1819 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1820 << Tok.getAnnotationRange();
1824 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1825 TemplateId->NumArgs);
1827 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1828 TemplateId->TemplateKWLoc,
1829 TemplateId->Template,
1831 TemplateId->TemplateNameLoc,
1832 TemplateId->LAngleLoc,
1834 TemplateId->RAngleLoc);
1836 Diag(Tok, diag::err_expected_type_name_after_typename)
1841 SourceLocation EndLoc = Tok.getLastLoc();
1842 Tok.setKind(tok::annot_typename);
1843 setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1844 Tok.setAnnotationEndLoc(EndLoc);
1845 Tok.setLocation(TypenameLoc);
1846 PP.AnnotateCachedTokens(Tok);
1850 // Remembers whether the token was originally a scope annotation.
1851 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1854 if (getLangOpts().CPlusPlus)
1855 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext*/false))
1858 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
1861 /// Try to annotate a type or scope token, having already parsed an
1862 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1863 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1864 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
1866 if (Tok.is(tok::identifier)) {
1867 // Determine whether the identifier is a type name.
1868 if (ParsedType Ty = Actions.getTypeName(
1869 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1870 false, NextToken().is(tok::period), nullptr,
1871 /*IsCtorOrDtorName=*/false,
1872 /*NonTrivialTypeSourceInfo*/true,
1873 /*IsClassTemplateDeductionContext*/true)) {
1874 SourceLocation BeginLoc = Tok.getLocation();
1875 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1876 BeginLoc = SS.getBeginLoc();
1878 /// An Objective-C object type followed by '<' is a specialization of
1879 /// a parameterized class type or a protocol-qualified type.
1880 if (getLangOpts().ObjC && NextToken().is(tok::less) &&
1881 (Ty.get()->isObjCObjectType() ||
1882 Ty.get()->isObjCObjectPointerType())) {
1883 // Consume the name.
1884 SourceLocation IdentifierLoc = ConsumeToken();
1885 SourceLocation NewEndLoc;
1887 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1888 /*consumeLastToken=*/false,
1890 if (NewType.isUsable())
1892 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1896 // This is a typename. Replace the current token in-place with an
1897 // annotation type token.
1898 Tok.setKind(tok::annot_typename);
1899 setTypeAnnotation(Tok, Ty);
1900 Tok.setAnnotationEndLoc(Tok.getLocation());
1901 Tok.setLocation(BeginLoc);
1903 // In case the tokens were cached, have Preprocessor replace
1904 // them with the annotation token.
1905 PP.AnnotateCachedTokens(Tok);
1909 if (!getLangOpts().CPlusPlus) {
1910 // If we're in C, we can't have :: tokens at all (the lexer won't return
1911 // them). If the identifier is not a type, then it can't be scope either,
1916 // If this is a template-id, annotate with a template-id or type token.
1917 // FIXME: This appears to be dead code. We already have formed template-id
1918 // tokens when parsing the scope specifier; this can never form a new one.
1919 if (NextToken().is(tok::less)) {
1920 TemplateTy Template;
1921 UnqualifiedId TemplateName;
1922 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1923 bool MemberOfUnknownSpecialization;
1924 if (TemplateNameKind TNK = Actions.isTemplateName(
1926 /*hasTemplateKeyword=*/false, TemplateName,
1927 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
1928 MemberOfUnknownSpecialization)) {
1929 // Only annotate an undeclared template name as a template-id if the
1930 // following tokens have the form of a template argument list.
1931 if (TNK != TNK_Undeclared_template ||
1932 isTemplateArgumentList(1) != TPResult::False) {
1933 // Consume the identifier.
1935 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1937 // If an unrecoverable error occurred, we need to return true here,
1938 // because the token stream is in a damaged state. We may not
1939 // return a valid identifier.
1946 // The current token, which is either an identifier or a
1947 // template-id, is not part of the annotation. Fall through to
1948 // push that token back into the stream and complete the C++ scope
1949 // specifier annotation.
1952 if (Tok.is(tok::annot_template_id)) {
1953 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1954 if (TemplateId->Kind == TNK_Type_template) {
1955 // A template-id that refers to a type was parsed into a
1956 // template-id annotation in a context where we weren't allowed
1957 // to produce a type annotation token. Update the template-id
1958 // annotation token to a type annotation token now.
1959 AnnotateTemplateIdTokenAsType();
1967 // A C++ scope specifier that isn't followed by a typename.
1968 AnnotateScopeToken(SS, IsNewScope);
1972 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1973 /// annotates C++ scope specifiers and template-ids. This returns
1974 /// true if there was an error that could not be recovered from.
1976 /// Note that this routine emits an error if you call it with ::new or ::delete
1977 /// as the current tokens, so only call it in contexts where these are invalid.
1978 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1979 assert(getLangOpts().CPlusPlus &&
1980 "Call sites of this function should be guarded by checking for C++");
1981 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1982 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1983 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1984 "Cannot be a type or scope token!");
1987 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1992 AnnotateScopeToken(SS, true);
1996 bool Parser::isTokenEqualOrEqualTypo() {
1997 tok::TokenKind Kind = Tok.getKind();
2001 case tok::ampequal: // &=
2002 case tok::starequal: // *=
2003 case tok::plusequal: // +=
2004 case tok::minusequal: // -=
2005 case tok::exclaimequal: // !=
2006 case tok::slashequal: // /=
2007 case tok::percentequal: // %=
2008 case tok::lessequal: // <=
2009 case tok::lesslessequal: // <<=
2010 case tok::greaterequal: // >=
2011 case tok::greatergreaterequal: // >>=
2012 case tok::caretequal: // ^=
2013 case tok::pipeequal: // |=
2014 case tok::equalequal: // ==
2015 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2017 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
2024 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2025 assert(Tok.is(tok::code_completion));
2026 PrevTokLocation = Tok.getLocation();
2028 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2029 if (S->getFlags() & Scope::FnScope) {
2030 Actions.CodeCompleteOrdinaryName(getCurScope(),
2031 Sema::PCC_RecoveryInFunction);
2033 return PrevTokLocation;
2036 if (S->getFlags() & Scope::ClassScope) {
2037 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
2039 return PrevTokLocation;
2043 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
2045 return PrevTokLocation;
2048 // Code-completion pass-through functions
2050 void Parser::CodeCompleteDirective(bool InConditional) {
2051 Actions.CodeCompletePreprocessorDirective(InConditional);
2054 void Parser::CodeCompleteInConditionalExclusion() {
2055 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
2058 void Parser::CodeCompleteMacroName(bool IsDefinition) {
2059 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
2062 void Parser::CodeCompletePreprocessorExpression() {
2063 Actions.CodeCompletePreprocessorExpression();
2066 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
2067 MacroInfo *MacroInfo,
2068 unsigned ArgumentIndex) {
2069 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
2073 void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {
2074 Actions.CodeCompleteIncludedFile(Dir, IsAngled);
2077 void Parser::CodeCompleteNaturalLanguage() {
2078 Actions.CodeCompleteNaturalLanguage();
2081 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
2082 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2083 "Expected '__if_exists' or '__if_not_exists'");
2084 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2085 Result.KeywordLoc = ConsumeToken();
2087 BalancedDelimiterTracker T(*this, tok::l_paren);
2088 if (T.consumeOpen()) {
2089 Diag(Tok, diag::err_expected_lparen_after)
2090 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
2094 // Parse nested-name-specifier.
2095 if (getLangOpts().CPlusPlus)
2096 ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
2097 /*EnteringContext=*/false);
2099 // Check nested-name specifier.
2100 if (Result.SS.isInvalid()) {
2105 // Parse the unqualified-id.
2106 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
2107 if (ParseUnqualifiedId(
2108 Result.SS, /*EnteringContext*/false, /*AllowDestructorName*/true,
2109 /*AllowConstructorName*/true, /*AllowDeductionGuide*/false, nullptr,
2110 &TemplateKWLoc, Result.Name)) {
2115 if (T.consumeClose())
2118 // Check if the symbol exists.
2119 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
2120 Result.IsIfExists, Result.SS,
2122 case Sema::IER_Exists:
2123 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
2126 case Sema::IER_DoesNotExist:
2127 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
2130 case Sema::IER_Dependent:
2131 Result.Behavior = IEB_Dependent;
2134 case Sema::IER_Error:
2141 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2142 IfExistsCondition Result;
2143 if (ParseMicrosoftIfExistsCondition(Result))
2146 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2147 if (Braces.consumeOpen()) {
2148 Diag(Tok, diag::err_expected) << tok::l_brace;
2152 switch (Result.Behavior) {
2154 // Parse declarations below.
2158 llvm_unreachable("Cannot have a dependent external declaration");
2165 // Parse the declarations.
2166 // FIXME: Support module import within __if_exists?
2167 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2168 ParsedAttributesWithRange attrs(AttrFactory);
2169 MaybeParseCXX11Attributes(attrs);
2170 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2171 if (Result && !getCurScope()->getParent())
2172 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2174 Braces.consumeClose();
2177 /// Parse a declaration beginning with the 'module' keyword or C++20
2178 /// context-sensitive keyword (optionally preceded by 'export').
2180 /// module-declaration: [Modules TS + P0629R0]
2181 /// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'
2183 /// global-module-fragment: [C++2a]
2184 /// 'module' ';' top-level-declaration-seq[opt]
2185 /// module-declaration: [C++2a]
2186 /// 'export'[opt] 'module' module-name module-partition[opt]
2187 /// attribute-specifier-seq[opt] ';'
2188 /// private-module-fragment: [C++2a]
2189 /// 'module' ':' 'private' ';' top-level-declaration-seq[opt]
2190 Parser::DeclGroupPtrTy Parser::ParseModuleDecl(bool IsFirstDecl) {
2191 SourceLocation StartLoc = Tok.getLocation();
2193 Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)
2194 ? Sema::ModuleDeclKind::Interface
2195 : Sema::ModuleDeclKind::Implementation;
2198 (Tok.is(tok::kw_module) ||
2199 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2200 "not a module declaration");
2201 SourceLocation ModuleLoc = ConsumeToken();
2203 // Attributes appear after the module name, not before.
2204 // FIXME: Suggest moving the attributes later with a fixit.
2205 DiagnoseAndSkipCXX11Attributes();
2207 // Parse a global-module-fragment, if present.
2208 if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2209 SourceLocation SemiLoc = ConsumeToken();
2211 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2212 << SourceRange(StartLoc, SemiLoc);
2215 if (MDK == Sema::ModuleDeclKind::Interface) {
2216 Diag(StartLoc, diag::err_module_fragment_exported)
2217 << /*global*/0 << FixItHint::CreateRemoval(StartLoc);
2219 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2222 // Parse a private-module-fragment, if present.
2223 if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2224 NextToken().is(tok::kw_private)) {
2225 if (MDK == Sema::ModuleDeclKind::Interface) {
2226 Diag(StartLoc, diag::err_module_fragment_exported)
2227 << /*private*/1 << FixItHint::CreateRemoval(StartLoc);
2230 SourceLocation PrivateLoc = ConsumeToken();
2231 DiagnoseAndSkipCXX11Attributes();
2232 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2233 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2236 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2237 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2240 // Parse the optional module-partition.
2241 if (Tok.is(tok::colon)) {
2242 SourceLocation ColonLoc = ConsumeToken();
2243 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;
2244 if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/false))
2247 // FIXME: Support module partition declarations.
2248 Diag(ColonLoc, diag::err_unsupported_module_partition)
2249 << SourceRange(ColonLoc, Partition.back().second);
2250 // Recover by parsing as a non-partition.
2253 // We don't support any module attributes yet; just parse them and diagnose.
2254 ParsedAttributesWithRange Attrs(AttrFactory);
2255 MaybeParseCXX11Attributes(Attrs);
2256 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2258 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2260 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, IsFirstDecl);
2263 /// Parse a module import declaration. This is essentially the same for
2264 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2265 /// and the trailing optional attributes (in C++).
2267 /// [ObjC] @import declaration:
2268 /// '@' 'import' module-name ';'
2269 /// [ModTS] module-import-declaration:
2270 /// 'import' module-name attribute-specifier-seq[opt] ';'
2271 /// [C++2a] module-import-declaration:
2272 /// 'export'[opt] 'import' module-name
2273 /// attribute-specifier-seq[opt] ';'
2274 /// 'export'[opt] 'import' module-partition
2275 /// attribute-specifier-seq[opt] ';'
2276 /// 'export'[opt] 'import' header-name
2277 /// attribute-specifier-seq[opt] ';'
2278 Decl *Parser::ParseModuleImport(SourceLocation AtLoc) {
2279 SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;
2281 SourceLocation ExportLoc;
2282 TryConsumeToken(tok::kw_export, ExportLoc);
2284 assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2285 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2286 "Improper start to module import");
2287 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2288 SourceLocation ImportLoc = ConsumeToken();
2290 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2291 Module *HeaderUnit = nullptr;
2293 if (Tok.is(tok::header_name)) {
2294 // This is a header import that the preprocessor decided we should skip
2295 // because it was malformed in some way. Parse and ignore it; it's already
2298 } else if (Tok.is(tok::annot_header_unit)) {
2299 // This is a header import that the preprocessor mapped to a module import.
2300 HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());
2301 ConsumeAnnotationToken();
2302 } else if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon)) {
2303 SourceLocation ColonLoc = ConsumeToken();
2304 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2307 // FIXME: Support module partition import.
2308 Diag(ColonLoc, diag::err_unsupported_module_partition)
2309 << SourceRange(ColonLoc, Path.back().second);
2312 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2316 ParsedAttributesWithRange Attrs(AttrFactory);
2317 MaybeParseCXX11Attributes(Attrs);
2318 // We don't support any module import attributes yet.
2319 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2321 if (PP.hadModuleLoaderFatalFailure()) {
2322 // With a fatal failure in the module loader, we abort parsing.
2330 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2331 else if (!Path.empty())
2332 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path);
2333 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2334 if (Import.isInvalid())
2337 // Using '@import' in framework headers requires modules to be enabled so that
2338 // the header is parseable. Emit a warning to make the user aware.
2339 if (IsObjCAtImport && AtLoc.isValid()) {
2340 auto &SrcMgr = PP.getSourceManager();
2341 auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
2342 if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
2343 .endswith(".framework"))
2344 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2347 return Import.get();
2350 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2354 /// module-name-qualifier[opt] identifier
2355 /// module-name-qualifier:
2356 /// module-name-qualifier[opt] identifier '.'
2357 bool Parser::ParseModuleName(
2358 SourceLocation UseLoc,
2359 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2361 // Parse the module path.
2363 if (!Tok.is(tok::identifier)) {
2364 if (Tok.is(tok::code_completion)) {
2365 Actions.CodeCompleteModuleImport(UseLoc, Path);
2370 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2371 SkipUntil(tok::semi);
2375 // Record this part of the module path.
2376 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2379 if (Tok.isNot(tok::period))
2386 /// Try recover parser when module annotation appears where it must not
2388 /// \returns false if the recover was successful and parsing may be continued, or
2389 /// true if parser must bail out to top level and handle the token there.
2390 bool Parser::parseMisplacedModuleImport() {
2392 switch (Tok.getKind()) {
2393 case tok::annot_module_end:
2394 // If we recovered from a misplaced module begin, we expect to hit a
2395 // misplaced module end too. Stay in the current context when this
2397 if (MisplacedModuleBeginCount) {
2398 --MisplacedModuleBeginCount;
2399 Actions.ActOnModuleEnd(Tok.getLocation(),
2400 reinterpret_cast<Module *>(
2401 Tok.getAnnotationValue()));
2402 ConsumeAnnotationToken();
2405 // Inform caller that recovery failed, the error must be handled at upper
2406 // level. This will generate the desired "missing '}' at end of module"
2407 // diagnostics on the way out.
2409 case tok::annot_module_begin:
2410 // Recover by entering the module (Sema will diagnose).
2411 Actions.ActOnModuleBegin(Tok.getLocation(),
2412 reinterpret_cast<Module *>(
2413 Tok.getAnnotationValue()));
2414 ConsumeAnnotationToken();
2415 ++MisplacedModuleBeginCount;
2417 case tok::annot_module_include:
2418 // Module import found where it should not be, for instance, inside a
2419 // namespace. Recover by importing the module.
2420 Actions.ActOnModuleInclude(Tok.getLocation(),
2421 reinterpret_cast<Module *>(
2422 Tok.getAnnotationValue()));
2423 ConsumeAnnotationToken();
2424 // If there is another module import, process it.
2433 bool BalancedDelimiterTracker::diagnoseOverflow() {
2434 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2435 << P.getLangOpts().BracketDepth;
2436 P.Diag(P.Tok, diag::note_bracket_depth);
2441 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2443 tok::TokenKind SkipToTok) {
2444 LOpen = P.Tok.getLocation();
2445 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2446 if (SkipToTok != tok::unknown)
2447 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2451 if (getDepth() < P.getLangOpts().BracketDepth)
2454 return diagnoseOverflow();
2457 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2458 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2460 if (P.Tok.is(tok::annot_module_end))
2461 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2463 P.Diag(P.Tok, diag::err_expected) << Close;
2464 P.Diag(LOpen, diag::note_matching) << Kind;
2466 // If we're not already at some kind of closing bracket, skip to our closing
2468 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2469 P.Tok.isNot(tok::r_square) &&
2470 P.SkipUntil(Close, FinalToken,
2471 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2473 LClose = P.ConsumeAnyToken();
2477 void BalancedDelimiterTracker::skipToEnd() {
2478 P.SkipUntil(Close, Parser::StopBeforeMatch);