1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 using namespace clang;
27 /// \brief 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);
41 /// \brief RAIIObject to destroy the contents of a SmallVector of
42 /// TemplateIdAnnotation pointers and clear the vector.
43 class DestroyTemplateIdAnnotationsRAIIObj {
44 SmallVectorImpl<TemplateIdAnnotation *> &Container;
47 DestroyTemplateIdAnnotationsRAIIObj(
48 SmallVectorImpl<TemplateIdAnnotation *> &Container)
49 : Container(Container) {}
51 ~DestroyTemplateIdAnnotationsRAIIObj() {
52 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
60 } // end anonymous namespace
62 IdentifierInfo *Parser::getSEHExceptKeyword() {
63 // __except is accepted as a (contextual) keyword
64 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
65 Ident__except = PP.getIdentifierInfo("__except");
70 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
71 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
72 GreaterThanIsOperator(true), ColonIsSacred(false),
73 InMessageExpression(false), TemplateParameterDepth(0),
74 ParsingInObjCContainer(false) {
75 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
77 Tok.setKind(tok::eof);
78 Actions.CurScope = nullptr;
80 CurParsedObjCImpl = nullptr;
82 // Add #pragma handlers. These are removed and destroyed in the
84 initializePragmaHandlers();
86 CommentSemaHandler.reset(new ActionCommentHandler(actions));
87 PP.addCommentHandler(CommentSemaHandler.get());
89 PP.setCodeCompletionHandler(*this);
92 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
93 return Diags.Report(Loc, DiagID);
96 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
97 return Diag(Tok.getLocation(), DiagID);
100 /// \brief Emits a diagnostic suggesting parentheses surrounding a
103 /// \param Loc The location where we'll emit the diagnostic.
104 /// \param DK The kind of diagnostic to emit.
105 /// \param ParenRange Source range enclosing code that should be parenthesized.
106 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
107 SourceRange ParenRange) {
108 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
109 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
110 // We can't display the parentheses, so just dig the
111 // warning/error and return.
117 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
118 << FixItHint::CreateInsertion(EndLoc, ")");
121 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
122 switch (ExpectedTok) {
124 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
125 default: return false;
129 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
131 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
136 // Detect common single-character typos and resume.
137 if (IsCommonTypo(ExpectedTok, Tok)) {
138 SourceLocation Loc = Tok.getLocation();
140 DiagnosticBuilder DB = Diag(Loc, DiagID);
141 DB << FixItHint::CreateReplacement(
142 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
143 if (DiagID == diag::err_expected)
145 else if (DiagID == diag::err_expected_after)
146 DB << Msg << ExpectedTok;
151 // Pretend there wasn't a problem.
156 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
157 const char *Spelling = nullptr;
158 if (EndLoc.isValid())
159 Spelling = tok::getPunctuatorSpelling(ExpectedTok);
161 DiagnosticBuilder DB =
163 ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
165 if (DiagID == diag::err_expected)
167 else if (DiagID == diag::err_expected_after)
168 DB << Msg << ExpectedTok;
175 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
176 if (TryConsumeToken(tok::semi))
179 if (Tok.is(tok::code_completion)) {
180 handleUnexpectedCodeCompletionToken();
184 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
185 NextToken().is(tok::semi)) {
186 Diag(Tok, diag::err_extraneous_token_before_semi)
187 << PP.getSpelling(Tok)
188 << FixItHint::CreateRemoval(Tok.getLocation());
189 ConsumeAnyToken(); // The ')' or ']'.
190 ConsumeToken(); // The ';'.
194 return ExpectAndConsume(tok::semi, DiagID);
197 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
198 if (!Tok.is(tok::semi)) return;
200 bool HadMultipleSemis = false;
201 SourceLocation StartLoc = Tok.getLocation();
202 SourceLocation EndLoc = Tok.getLocation();
205 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
206 HadMultipleSemis = true;
207 EndLoc = Tok.getLocation();
211 // C++11 allows extra semicolons at namespace scope, but not in any of the
213 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
214 if (getLangOpts().CPlusPlus11)
215 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
216 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
218 Diag(StartLoc, diag::ext_extra_semi_cxx11)
219 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
223 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
224 Diag(StartLoc, diag::ext_extra_semi)
225 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
226 Actions.getASTContext().getPrintingPolicy())
227 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
229 // A single semicolon is valid after a member function definition.
230 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
231 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
234 //===----------------------------------------------------------------------===//
236 //===----------------------------------------------------------------------===//
238 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
239 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
242 /// SkipUntil - Read tokens until we get to the specified token, then consume
243 /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the
244 /// token will ever occur, this skips to the next token, or to some likely
245 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
248 /// If SkipUntil finds the specified token, it returns true, otherwise it
250 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
251 // We always want this function to skip at least one token if the first token
252 // isn't T and if not at EOF.
253 bool isFirstTokenSkipped = true;
255 // If we found one of the tokens, stop and return true.
256 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
257 if (Tok.is(Toks[i])) {
258 if (HasFlagsSet(Flags, StopBeforeMatch)) {
259 // Noop, don't consume the token.
267 // Important special case: The caller has given up and just wants us to
268 // skip the rest of the file. Do this without recursing, since we can
269 // get here precisely because the caller detected too much recursion.
270 if (Toks.size() == 1 && Toks[0] == tok::eof &&
271 !HasFlagsSet(Flags, StopAtSemi) &&
272 !HasFlagsSet(Flags, StopAtCodeCompletion)) {
273 while (Tok.isNot(tok::eof))
278 switch (Tok.getKind()) {
280 // Ran out of tokens.
283 case tok::annot_pragma_openmp:
284 case tok::annot_pragma_openmp_end:
285 // Stop before an OpenMP pragma boundary.
286 case tok::annot_module_begin:
287 case tok::annot_module_end:
288 case tok::annot_module_include:
289 // Stop before we change submodules. They generally indicate a "good"
290 // place to pick up parsing again (except in the special case where
291 // we're trying to skip to EOF).
294 case tok::code_completion:
295 if (!HasFlagsSet(Flags, StopAtCodeCompletion))
296 handleUnexpectedCodeCompletionToken();
300 // Recursively skip properly-nested parens.
302 if (HasFlagsSet(Flags, StopAtCodeCompletion))
303 SkipUntil(tok::r_paren, StopAtCodeCompletion);
305 SkipUntil(tok::r_paren);
308 // Recursively skip properly-nested square brackets.
310 if (HasFlagsSet(Flags, StopAtCodeCompletion))
311 SkipUntil(tok::r_square, StopAtCodeCompletion);
313 SkipUntil(tok::r_square);
316 // Recursively skip properly-nested braces.
318 if (HasFlagsSet(Flags, StopAtCodeCompletion))
319 SkipUntil(tok::r_brace, StopAtCodeCompletion);
321 SkipUntil(tok::r_brace);
324 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
325 // Since the user wasn't looking for this token (if they were, it would
326 // already be handled), this isn't balanced. If there is a LHS token at a
327 // higher level, we will assume that this matches the unbalanced token
328 // and return it. Otherwise, this is a spurious RHS token, which we skip.
330 if (ParenCount && !isFirstTokenSkipped)
331 return false; // Matches something.
335 if (BracketCount && !isFirstTokenSkipped)
336 return false; // Matches something.
340 if (BraceCount && !isFirstTokenSkipped)
341 return false; // Matches something.
345 case tok::string_literal:
346 case tok::wide_string_literal:
347 case tok::utf8_string_literal:
348 case tok::utf16_string_literal:
349 case tok::utf32_string_literal:
350 ConsumeStringToken();
354 if (HasFlagsSet(Flags, StopAtSemi))
362 isFirstTokenSkipped = false;
366 //===----------------------------------------------------------------------===//
367 // Scope manipulation
368 //===----------------------------------------------------------------------===//
370 /// EnterScope - Start a new scope.
371 void Parser::EnterScope(unsigned ScopeFlags) {
372 if (NumCachedScopes) {
373 Scope *N = ScopeCache[--NumCachedScopes];
374 N->Init(getCurScope(), ScopeFlags);
375 Actions.CurScope = N;
377 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
381 /// ExitScope - Pop a scope off the scope stack.
382 void Parser::ExitScope() {
383 assert(getCurScope() && "Scope imbalance!");
385 // Inform the actions module that this scope is going away if there are any
387 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
389 Scope *OldScope = getCurScope();
390 Actions.CurScope = OldScope->getParent();
392 if (NumCachedScopes == ScopeCacheSize)
395 ScopeCache[NumCachedScopes++] = OldScope;
398 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
399 /// this object does nothing.
400 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
402 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
404 OldFlags = CurScope->getFlags();
405 CurScope->setFlags(ScopeFlags);
409 /// Restore the flags for the current scope to what they were before this
410 /// object overrode them.
411 Parser::ParseScopeFlags::~ParseScopeFlags() {
413 CurScope->setFlags(OldFlags);
417 //===----------------------------------------------------------------------===//
418 // C99 6.9: External Definitions.
419 //===----------------------------------------------------------------------===//
422 // If we still have scopes active, delete the scope tree.
423 delete getCurScope();
424 Actions.CurScope = nullptr;
426 // Free the scope cache.
427 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
428 delete ScopeCache[i];
430 resetPragmaHandlers();
432 PP.removeCommentHandler(CommentSemaHandler.get());
434 PP.clearCodeCompletionHandler();
436 if (getLangOpts().DelayedTemplateParsing &&
437 !PP.isIncrementalProcessingEnabled() && !TemplateIds.empty()) {
438 // If an ASTConsumer parsed delay-parsed templates in their
439 // HandleTranslationUnit() method, TemplateIds created there were not
440 // guarded by a DestroyTemplateIdAnnotationsRAIIObj object in
441 // ParseTopLevelDecl(). Destroy them here.
442 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
445 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
448 /// Initialize - Warm up the parser.
450 void Parser::Initialize() {
451 // Create the translation unit scope. Install it as the current scope.
452 assert(getCurScope() == nullptr && "A scope is already active?");
453 EnterScope(Scope::DeclScope);
454 Actions.ActOnTranslationUnitScope(getCurScope());
456 // Initialization for Objective-C context sensitive keywords recognition.
457 // Referenced in Parser::ParseObjCTypeQualifierList.
458 if (getLangOpts().ObjC1) {
459 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
460 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
461 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
462 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
463 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
464 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
465 ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");
466 ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");
467 ObjCTypeQuals[objc_null_unspecified]
468 = &PP.getIdentifierTable().get("null_unspecified");
471 Ident_instancetype = nullptr;
472 Ident_final = nullptr;
473 Ident_sealed = nullptr;
474 Ident_override = nullptr;
475 Ident_GNU_final = nullptr;
477 Ident_super = &PP.getIdentifierTable().get("super");
479 Ident_vector = nullptr;
480 Ident_bool = nullptr;
481 Ident_pixel = nullptr;
482 if (getLangOpts().AltiVec || getLangOpts().ZVector) {
483 Ident_vector = &PP.getIdentifierTable().get("vector");
484 Ident_bool = &PP.getIdentifierTable().get("bool");
486 if (getLangOpts().AltiVec)
487 Ident_pixel = &PP.getIdentifierTable().get("pixel");
489 Ident_introduced = nullptr;
490 Ident_deprecated = nullptr;
491 Ident_obsoleted = nullptr;
492 Ident_unavailable = nullptr;
493 Ident_strict = nullptr;
494 Ident_replacement = nullptr;
496 Ident__except = nullptr;
498 Ident__exception_code = Ident__exception_info = nullptr;
499 Ident__abnormal_termination = Ident___exception_code = nullptr;
500 Ident___exception_info = Ident___abnormal_termination = nullptr;
501 Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
502 Ident_AbnormalTermination = nullptr;
504 if(getLangOpts().Borland) {
505 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
506 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
507 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
508 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
509 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
510 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
511 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
512 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
513 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
515 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
516 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
517 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
518 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
519 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
520 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
521 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
522 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
523 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
526 Actions.Initialize();
528 // Prime the lexer look-ahead.
532 void Parser::LateTemplateParserCleanupCallback(void *P) {
533 // While this RAII helper doesn't bracket any actual work, the destructor will
534 // clean up annotations that were created during ActOnEndOfTranslationUnit
535 // when incremental processing is enabled.
536 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
539 bool Parser::ParseFirstTopLevelDecl(DeclGroupPtrTy &Result) {
540 // C++ Modules TS: module-declaration must be the first declaration in the
541 // file. (There can be no preceding preprocessor directives, but we expect
542 // the lexer to check that.)
543 if (Tok.is(tok::kw_module)) {
544 Result = ParseModuleDecl();
546 } else if (getLangOpts().getCompilingModule() ==
547 LangOptions::CMK_ModuleInterface) {
548 // FIXME: We avoid providing this diagnostic when generating an object file
549 // from an existing PCM file. This is not a good way to detect this
550 // condition; we should provide a mechanism to indicate whether we've
551 // already parsed a declaration in this translation unit and avoid calling
552 // ParseFirstTopLevelDecl in that case.
553 if (Actions.TUKind == TU_Module)
554 Diag(Tok, diag::err_expected_module_interface_decl);
557 // C11 6.9p1 says translation units must have at least one top-level
558 // declaration. C++ doesn't have this restriction. We also don't want to
559 // complain if we have a precompiled header, although technically if the PCH
560 // is empty we should still emit the (pedantic) diagnostic.
561 bool NoTopLevelDecls = ParseTopLevelDecl(Result);
562 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
563 !getLangOpts().CPlusPlus)
564 Diag(diag::ext_empty_translation_unit);
566 return NoTopLevelDecls;
569 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
570 /// action tells us to. This returns true if the EOF was encountered.
571 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
572 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
574 // Skip over the EOF token, flagging end of previous input for incremental
576 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
580 switch (Tok.getKind()) {
581 case tok::annot_pragma_unused:
582 HandlePragmaUnused();
586 Result = ParseModuleImport(SourceLocation());
589 case tok::annot_module_include:
590 Actions.ActOnModuleInclude(Tok.getLocation(),
591 reinterpret_cast<Module *>(
592 Tok.getAnnotationValue()));
596 case tok::annot_module_begin:
597 Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>(
598 Tok.getAnnotationValue()));
602 case tok::annot_module_end:
603 Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>(
604 Tok.getAnnotationValue()));
609 // Late template parsing can begin.
610 if (getLangOpts().DelayedTemplateParsing)
611 Actions.SetLateTemplateParser(LateTemplateParserCallback,
612 PP.isIncrementalProcessingEnabled() ?
613 LateTemplateParserCleanupCallback : nullptr,
615 if (!PP.isIncrementalProcessingEnabled())
616 Actions.ActOnEndOfTranslationUnit();
617 //else don't tell Sema that we ended parsing: more input might come.
624 ParsedAttributesWithRange attrs(AttrFactory);
625 MaybeParseCXX11Attributes(attrs);
627 Result = ParseExternalDeclaration(attrs);
631 /// ParseExternalDeclaration:
633 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
634 /// function-definition
636 /// [GNU] asm-definition
637 /// [GNU] __extension__ external-declaration
638 /// [OBJC] objc-class-definition
639 /// [OBJC] objc-class-declaration
640 /// [OBJC] objc-alias-declaration
641 /// [OBJC] objc-protocol-definition
642 /// [OBJC] objc-method-definition
644 /// [C++] linkage-specification
645 /// [GNU] asm-definition:
646 /// simple-asm-expr ';'
647 /// [C++11] empty-declaration
648 /// [C++11] attribute-declaration
650 /// [C++11] empty-declaration:
653 /// [C++0x/GNU] 'extern' 'template' declaration
654 Parser::DeclGroupPtrTy
655 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
656 ParsingDeclSpec *DS) {
657 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
658 ParenBraceBracketBalancer BalancerRAIIObj(*this);
660 if (PP.isCodeCompletionReached()) {
665 Decl *SingleDecl = nullptr;
666 switch (Tok.getKind()) {
667 case tok::annot_pragma_vis:
668 HandlePragmaVisibility();
670 case tok::annot_pragma_pack:
673 case tok::annot_pragma_msstruct:
674 HandlePragmaMSStruct();
676 case tok::annot_pragma_align:
679 case tok::annot_pragma_weak:
682 case tok::annot_pragma_weakalias:
683 HandlePragmaWeakAlias();
685 case tok::annot_pragma_redefine_extname:
686 HandlePragmaRedefineExtname();
688 case tok::annot_pragma_fp_contract:
689 HandlePragmaFPContract();
691 case tok::annot_pragma_opencl_extension:
692 HandlePragmaOpenCLExtension();
694 case tok::annot_pragma_openmp: {
695 AccessSpecifier AS = AS_none;
696 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
698 case tok::annot_pragma_ms_pointers_to_members:
699 HandlePragmaMSPointersToMembers();
701 case tok::annot_pragma_ms_vtordisp:
702 HandlePragmaMSVtorDisp();
704 case tok::annot_pragma_ms_pragma:
705 HandlePragmaMSPragma();
707 case tok::annot_pragma_dump:
711 // Either a C++11 empty-declaration or attribute-declaration.
712 SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
715 ConsumeExtraSemi(OutsideFunction);
718 Diag(Tok, diag::err_extraneous_closing_brace);
722 Diag(Tok, diag::err_expected_external_declaration);
724 case tok::kw___extension__: {
725 // __extension__ silences extension warnings in the subexpression.
726 ExtensionRAIIObject O(Diags); // Use RAII to do this.
728 return ParseExternalDeclaration(attrs);
731 ProhibitAttributes(attrs);
733 SourceLocation StartLoc = Tok.getLocation();
734 SourceLocation EndLoc;
736 ExprResult Result(ParseSimpleAsm(&EndLoc));
738 // Check if GNU-style InlineAsm is disabled.
739 // Empty asm string is allowed because it will not introduce
740 // any assembly code.
741 if (!(getLangOpts().GNUAsm || Result.isInvalid())) {
742 const auto *SL = cast<StringLiteral>(Result.get());
743 if (!SL->getString().trim().empty())
744 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
747 ExpectAndConsume(tok::semi, diag::err_expected_after,
748 "top-level asm block");
750 if (Result.isInvalid())
752 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
756 return ParseObjCAtDirectives();
759 if (!getLangOpts().ObjC1) {
760 Diag(Tok, diag::err_expected_external_declaration);
764 SingleDecl = ParseObjCMethodDefinition();
766 case tok::code_completion:
767 Actions.CodeCompleteOrdinaryName(getCurScope(),
768 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
769 : Sema::PCC_Namespace);
773 if (getLangOpts().ModulesTS) {
774 SingleDecl = ParseExportDeclaration();
777 // This must be 'export template'. Parse it so we can diagnose our lack
780 case tok::kw_namespace:
781 case tok::kw_typedef:
782 case tok::kw_template:
783 case tok::kw_static_assert:
784 case tok::kw__Static_assert:
785 // A function definition cannot start with any of these keywords.
787 SourceLocation DeclEnd;
788 return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
792 // Parse (then ignore) 'static' prior to a template instantiation. This is
793 // a GCC extension that we intentionally do not support.
794 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
795 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
797 SourceLocation DeclEnd;
798 return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
803 if (getLangOpts().CPlusPlus) {
804 tok::TokenKind NextKind = NextToken().getKind();
806 // Inline namespaces. Allowed as an extension even in C++03.
807 if (NextKind == tok::kw_namespace) {
808 SourceLocation DeclEnd;
809 return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
812 // Parse (then ignore) 'inline' prior to a template instantiation. This is
813 // a GCC extension that we intentionally do not support.
814 if (NextKind == tok::kw_template) {
815 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
817 SourceLocation DeclEnd;
818 return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
824 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
826 SourceLocation ExternLoc = ConsumeToken();
827 SourceLocation TemplateLoc = ConsumeToken();
828 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
829 diag::warn_cxx98_compat_extern_template :
830 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
831 SourceLocation DeclEnd;
832 return Actions.ConvertDeclToDeclGroup(
833 ParseExplicitInstantiation(Declarator::FileContext,
834 ExternLoc, TemplateLoc, DeclEnd));
838 case tok::kw___if_exists:
839 case tok::kw___if_not_exists:
840 ParseMicrosoftIfExistsExternalDeclaration();
844 Diag(Tok, diag::err_unexpected_module_decl);
845 SkipUntil(tok::semi);
850 // We can't tell whether this is a function-definition or declaration yet.
851 return ParseDeclarationOrFunctionDefinition(attrs, DS);
854 // This routine returns a DeclGroup, if the thing we parsed only contains a
855 // single decl, convert it now.
856 return Actions.ConvertDeclToDeclGroup(SingleDecl);
859 /// \brief Determine whether the current token, if it occurs after a
860 /// declarator, continues a declaration or declaration list.
861 bool Parser::isDeclarationAfterDeclarator() {
862 // Check for '= delete' or '= default'
863 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
864 const Token &KW = NextToken();
865 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
869 return Tok.is(tok::equal) || // int X()= -> not a function def
870 Tok.is(tok::comma) || // int X(), -> not a function def
871 Tok.is(tok::semi) || // int X(); -> not a function def
872 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
873 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
874 (getLangOpts().CPlusPlus &&
875 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
878 /// \brief Determine whether the current token, if it occurs after a
879 /// declarator, indicates the start of a function definition.
880 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
881 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
882 if (Tok.is(tok::l_brace)) // int X() {}
885 // Handle K&R C argument lists: int X(f) int f; {}
886 if (!getLangOpts().CPlusPlus &&
887 Declarator.getFunctionTypeInfo().isKNRPrototype())
888 return isDeclarationSpecifier();
890 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
891 const Token &KW = NextToken();
892 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
895 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
896 Tok.is(tok::kw_try); // X() try { ... }
899 /// Parse either a function-definition or a declaration. We can't tell which
900 /// we have until we read up to the compound-statement in function-definition.
901 /// TemplateParams, if non-NULL, provides the template parameters when we're
902 /// parsing a C++ template-declaration.
904 /// function-definition: [C99 6.9.1]
905 /// decl-specs declarator declaration-list[opt] compound-statement
906 /// [C90] function-definition: [C99 6.7.1] - implicit int result
907 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
909 /// declaration: [C99 6.7]
910 /// declaration-specifiers init-declarator-list[opt] ';'
911 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
912 /// [OMP] threadprivate-directive [TODO]
914 Parser::DeclGroupPtrTy
915 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
917 AccessSpecifier AS) {
918 MaybeParseMicrosoftAttributes(DS.getAttributes());
919 // Parse the common declaration-specifiers piece.
920 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
922 // If we had a free-standing type definition with a missing semicolon, we
923 // may get this far before the problem becomes obvious.
924 if (DS.hasTagDefinition() &&
925 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
928 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
929 // declaration-specifiers init-declarator-list[opt] ';'
930 if (Tok.is(tok::semi)) {
931 ProhibitAttributes(attrs);
933 RecordDecl *AnonRecord = nullptr;
934 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
936 DS.complete(TheDecl);
937 if (getLangOpts().OpenCL)
938 Actions.setCurrentOpenCLExtensionForDecl(TheDecl);
940 Decl* decls[] = {AnonRecord, TheDecl};
941 return Actions.BuildDeclaratorGroup(decls);
943 return Actions.ConvertDeclToDeclGroup(TheDecl);
946 DS.takeAttributesFrom(attrs);
948 // ObjC2 allows prefix attributes on class interfaces and protocols.
949 // FIXME: This still needs better diagnostics. We should only accept
950 // attributes here, no types, etc.
951 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
952 SourceLocation AtLoc = ConsumeToken(); // the "@"
953 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
954 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
955 Diag(Tok, diag::err_objc_unexpected_attr);
956 SkipUntil(tok::semi); // FIXME: better skip?
962 const char *PrevSpec = nullptr;
964 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
965 Actions.getASTContext().getPrintingPolicy()))
966 Diag(AtLoc, DiagID) << PrevSpec;
968 if (Tok.isObjCAtKeyword(tok::objc_protocol))
969 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
971 return Actions.ConvertDeclToDeclGroup(
972 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
975 // If the declspec consisted only of 'extern' and we have a string
976 // literal following it, this must be a C++ linkage specifier like
978 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
979 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
980 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
981 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
982 return Actions.ConvertDeclToDeclGroup(TheDecl);
985 return ParseDeclGroup(DS, Declarator::FileContext);
988 Parser::DeclGroupPtrTy
989 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
991 AccessSpecifier AS) {
993 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
995 ParsingDeclSpec PDS(*this);
996 // Must temporarily exit the objective-c container scope for
997 // parsing c constructs and re-enter objc container scope
999 ObjCDeclContextSwitch ObjCDC(*this);
1001 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1005 /// ParseFunctionDefinition - We parsed and verified that the specified
1006 /// Declarator is well formed. If this is a K&R-style function, read the
1007 /// parameters declaration-list, then start the compound-statement.
1009 /// function-definition: [C99 6.9.1]
1010 /// decl-specs declarator declaration-list[opt] compound-statement
1011 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1012 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1013 /// [C++] function-definition: [C++ 8.4]
1014 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1016 /// [C++] function-definition: [C++ 8.4]
1017 /// decl-specifier-seq[opt] declarator function-try-block
1019 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1020 const ParsedTemplateInfo &TemplateInfo,
1021 LateParsedAttrList *LateParsedAttrs) {
1022 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1023 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1024 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1026 // If this is C90 and the declspecs were completely missing, fudge in an
1027 // implicit int. We do this here because this is the only place where
1028 // declaration-specifiers are completely optional in the grammar.
1029 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
1030 const char *PrevSpec;
1032 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1033 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1034 D.getIdentifierLoc(),
1037 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1040 // If this declaration was formed with a K&R-style identifier list for the
1041 // arguments, parse declarations for all of the args next.
1042 // int foo(a,b) int a; float b; {}
1043 if (FTI.isKNRPrototype())
1044 ParseKNRParamDeclarations(D);
1046 // We should have either an opening brace or, in a C++ constructor,
1047 // we may have a colon.
1048 if (Tok.isNot(tok::l_brace) &&
1049 (!getLangOpts().CPlusPlus ||
1050 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1051 Tok.isNot(tok::equal)))) {
1052 Diag(Tok, diag::err_expected_fn_body);
1054 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1055 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1057 // If we didn't find the '{', bail out.
1058 if (Tok.isNot(tok::l_brace))
1062 // Check to make sure that any normal attributes are allowed to be on
1063 // a definition. Late parsed attributes are checked at the end.
1064 if (Tok.isNot(tok::equal)) {
1065 AttributeList *DtorAttrs = D.getAttributes();
1067 if (DtorAttrs->isKnownToGCC() &&
1068 !DtorAttrs->isCXX11Attribute()) {
1069 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
1070 << DtorAttrs->getName();
1072 DtorAttrs = DtorAttrs->getNext();
1076 // In delayed template parsing mode, for function template we consume the
1077 // tokens and store them for late parsing at the end of the translation unit.
1078 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1079 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1080 Actions.canDelayFunctionBody(D)) {
1081 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1083 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1084 Scope *ParentScope = getCurScope()->getParent();
1086 D.setFunctionDefinitionKind(FDK_Definition);
1087 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1088 TemplateParameterLists);
1090 D.getMutableDeclSpec().abort();
1092 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1093 trySkippingFunctionBody()) {
1095 return Actions.ActOnSkippedFunctionBody(DP);
1099 LexTemplateFunctionForLateParsing(Toks);
1102 FunctionDecl *FnD = DP->getAsFunction();
1103 Actions.CheckForFunctionRedefinition(FnD);
1104 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1108 else if (CurParsedObjCImpl &&
1109 !TemplateInfo.TemplateParams &&
1110 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1111 Tok.is(tok::colon)) &&
1112 Actions.CurContext->isTranslationUnit()) {
1113 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1114 Scope *ParentScope = getCurScope()->getParent();
1116 D.setFunctionDefinitionKind(FDK_Definition);
1117 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1118 MultiTemplateParamsArg());
1119 D.complete(FuncDecl);
1120 D.getMutableDeclSpec().abort();
1122 // Consume the tokens and store them for later parsing.
1123 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1124 CurParsedObjCImpl->HasCFunction = true;
1127 // FIXME: Should we really fall through here?
1130 // Enter a scope for the function body.
1131 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1133 // Tell the actions module that we have entered a function definition with the
1134 // specified Declarator for the function.
1135 Sema::SkipBodyInfo SkipBody;
1136 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1137 TemplateInfo.TemplateParams
1138 ? *TemplateInfo.TemplateParams
1139 : MultiTemplateParamsArg(),
1142 if (SkipBody.ShouldSkip) {
1147 // Break out of the ParsingDeclarator context before we parse the body.
1150 // Break out of the ParsingDeclSpec context, too. This const_cast is
1151 // safe because we're always the sole owner.
1152 D.getMutableDeclSpec().abort();
1154 if (TryConsumeToken(tok::equal)) {
1155 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1157 bool Delete = false;
1158 SourceLocation KWLoc;
1159 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1160 Diag(KWLoc, getLangOpts().CPlusPlus11
1161 ? diag::warn_cxx98_compat_defaulted_deleted_function
1162 : diag::ext_defaulted_deleted_function)
1164 Actions.SetDeclDeleted(Res, KWLoc);
1166 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1167 Diag(KWLoc, getLangOpts().CPlusPlus11
1168 ? diag::warn_cxx98_compat_defaulted_deleted_function
1169 : diag::ext_defaulted_deleted_function)
1170 << 0 /* defaulted */;
1171 Actions.SetDeclDefaulted(Res, KWLoc);
1173 llvm_unreachable("function definition after = not 'delete' or 'default'");
1176 if (Tok.is(tok::comma)) {
1177 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1179 SkipUntil(tok::semi);
1180 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1181 Delete ? "delete" : "default")) {
1182 SkipUntil(tok::semi);
1185 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1186 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1190 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1191 trySkippingFunctionBody()) {
1193 Actions.ActOnSkippedFunctionBody(Res);
1194 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1197 if (Tok.is(tok::kw_try))
1198 return ParseFunctionTryBlock(Res, BodyScope);
1200 // If we have a colon, then we're probably parsing a C++
1201 // ctor-initializer.
1202 if (Tok.is(tok::colon)) {
1203 ParseConstructorInitializer(Res);
1205 // Recover from error.
1206 if (!Tok.is(tok::l_brace)) {
1208 Actions.ActOnFinishFunctionBody(Res, nullptr);
1212 Actions.ActOnDefaultCtorInitializers(Res);
1214 // Late attributes are parsed in the same scope as the function body.
1215 if (LateParsedAttrs)
1216 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1218 return ParseFunctionStatementBody(Res, BodyScope);
1221 void Parser::SkipFunctionBody() {
1222 if (Tok.is(tok::equal)) {
1223 SkipUntil(tok::semi);
1227 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1228 if (IsFunctionTryBlock)
1231 CachedTokens Skipped;
1232 if (ConsumeAndStoreFunctionPrologue(Skipped))
1233 SkipMalformedDecl();
1235 SkipUntil(tok::r_brace);
1236 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1237 SkipUntil(tok::l_brace);
1238 SkipUntil(tok::r_brace);
1243 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1244 /// types for a function with a K&R-style identifier list for arguments.
1245 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1246 // We know that the top-level of this declarator is a function.
1247 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1249 // Enter function-declaration scope, limiting any declarators to the
1250 // function prototype scope, including parameter declarators.
1251 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1252 Scope::FunctionDeclarationScope | Scope::DeclScope);
1254 // Read all the argument declarations.
1255 while (isDeclarationSpecifier()) {
1256 SourceLocation DSStart = Tok.getLocation();
1258 // Parse the common declaration-specifiers piece.
1259 DeclSpec DS(AttrFactory);
1260 ParseDeclarationSpecifiers(DS);
1262 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1263 // least one declarator'.
1264 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1265 // the declarations though. It's trivial to ignore them, really hard to do
1266 // anything else with them.
1267 if (TryConsumeToken(tok::semi)) {
1268 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1272 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1274 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1275 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1276 Diag(DS.getStorageClassSpecLoc(),
1277 diag::err_invalid_storage_class_in_func_decl);
1278 DS.ClearStorageClassSpecs();
1280 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1281 Diag(DS.getThreadStorageClassSpecLoc(),
1282 diag::err_invalid_storage_class_in_func_decl);
1283 DS.ClearStorageClassSpecs();
1286 // Parse the first declarator attached to this declspec.
1287 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1288 ParseDeclarator(ParmDeclarator);
1290 // Handle the full declarator list.
1292 // If attributes are present, parse them.
1293 MaybeParseGNUAttributes(ParmDeclarator);
1295 // Ask the actions module to compute the type for this declarator.
1297 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1300 // A missing identifier has already been diagnosed.
1301 ParmDeclarator.getIdentifier()) {
1303 // Scan the argument list looking for the correct param to apply this
1305 for (unsigned i = 0; ; ++i) {
1306 // C99 6.9.1p6: those declarators shall declare only identifiers from
1307 // the identifier list.
1308 if (i == FTI.NumParams) {
1309 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1310 << ParmDeclarator.getIdentifier();
1314 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1315 // Reject redefinitions of parameters.
1316 if (FTI.Params[i].Param) {
1317 Diag(ParmDeclarator.getIdentifierLoc(),
1318 diag::err_param_redefinition)
1319 << ParmDeclarator.getIdentifier();
1321 FTI.Params[i].Param = Param;
1328 // If we don't have a comma, it is either the end of the list (a ';') or
1329 // an error, bail out.
1330 if (Tok.isNot(tok::comma))
1333 ParmDeclarator.clear();
1335 // Consume the comma.
1336 ParmDeclarator.setCommaLoc(ConsumeToken());
1338 // Parse the next declarator.
1339 ParseDeclarator(ParmDeclarator);
1342 // Consume ';' and continue parsing.
1343 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1346 // Otherwise recover by skipping to next semi or mandatory function body.
1347 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1349 TryConsumeToken(tok::semi);
1352 // The actions module must verify that all arguments were declared.
1353 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1357 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1358 /// allowed to be a wide string, and is not subject to character translation.
1360 /// [GNU] asm-string-literal:
1363 ExprResult Parser::ParseAsmStringLiteral() {
1364 if (!isTokenStringLiteral()) {
1365 Diag(Tok, diag::err_expected_string_literal)
1366 << /*Source='in...'*/0 << "'asm'";
1370 ExprResult AsmString(ParseStringLiteralExpression());
1371 if (!AsmString.isInvalid()) {
1372 const auto *SL = cast<StringLiteral>(AsmString.get());
1373 if (!SL->isAscii()) {
1374 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1376 << SL->getSourceRange();
1385 /// [GNU] simple-asm-expr:
1386 /// 'asm' '(' asm-string-literal ')'
1388 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1389 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1390 SourceLocation Loc = ConsumeToken();
1392 if (Tok.is(tok::kw_volatile)) {
1393 // Remove from the end of 'asm' to the end of 'volatile'.
1394 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1395 PP.getLocForEndOfToken(Tok.getLocation()));
1397 Diag(Tok, diag::warn_file_asm_volatile)
1398 << FixItHint::CreateRemoval(RemovalRange);
1402 BalancedDelimiterTracker T(*this, tok::l_paren);
1403 if (T.consumeOpen()) {
1404 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1408 ExprResult Result(ParseAsmStringLiteral());
1410 if (!Result.isInvalid()) {
1411 // Close the paren and get the location of the end bracket
1414 *EndLoc = T.getCloseLocation();
1415 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1417 *EndLoc = Tok.getLocation();
1424 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1425 /// cleanup pool so that it gets destroyed when parsing the current top level
1426 /// declaration is finished.
1427 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1428 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1429 TemplateIdAnnotation *
1430 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1434 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1435 // Push the current token back into the token stream (or revert it if it is
1436 // cached) and use an annotation scope token for current token.
1437 if (PP.isBacktrackEnabled())
1438 PP.RevertCachedTokens(1);
1441 Tok.setKind(tok::annot_cxxscope);
1442 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1443 Tok.setAnnotationRange(SS.getRange());
1445 // In case the tokens were cached, have Preprocessor replace them
1446 // with the annotation token. We don't need to do this if we've
1447 // just reverted back to a prior state.
1448 if (IsNewAnnotation)
1449 PP.AnnotateCachedTokens(Tok);
1452 /// \brief Attempt to classify the name at the current token position. This may
1453 /// form a type, scope or primary expression annotation, or replace the token
1454 /// with a typo-corrected keyword. This is only appropriate when the current
1455 /// name must refer to an entity which has already been declared.
1457 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1458 /// and might possibly have a dependent nested name specifier.
1459 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1460 /// no typo correction will be performed.
1461 Parser::AnnotatedNameKind
1462 Parser::TryAnnotateName(bool IsAddressOfOperand,
1463 std::unique_ptr<CorrectionCandidateCallback> CCC) {
1464 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1466 const bool EnteringContext = false;
1467 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1470 if (getLangOpts().CPlusPlus &&
1471 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1474 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1475 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1477 return ANK_Unresolved;
1480 IdentifierInfo *Name = Tok.getIdentifierInfo();
1481 SourceLocation NameLoc = Tok.getLocation();
1483 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1484 // typo-correct to tentatively-declared identifiers.
1485 if (isTentativelyDeclared(Name)) {
1486 // Identifier has been tentatively declared, and thus cannot be resolved as
1487 // an expression. Fall back to annotating it as a type.
1488 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation))
1490 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1493 Token Next = NextToken();
1495 // Look up and classify the identifier. We don't perform any typo-correction
1496 // after a scope specifier, because in general we can't recover from typos
1497 // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
1498 // jump back into scope specifier parsing).
1499 Sema::NameClassification Classification = Actions.ClassifyName(
1500 getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1501 SS.isEmpty() ? std::move(CCC) : nullptr);
1503 switch (Classification.getKind()) {
1504 case Sema::NC_Error:
1507 case Sema::NC_Keyword:
1508 // The identifier was typo-corrected to a keyword.
1509 Tok.setIdentifierInfo(Name);
1510 Tok.setKind(Name->getTokenID());
1511 PP.TypoCorrectToken(Tok);
1512 if (SS.isNotEmpty())
1513 AnnotateScopeToken(SS, !WasScopeAnnotation);
1514 // We've "annotated" this as a keyword.
1517 case Sema::NC_Unknown:
1518 // It's not something we know about. Leave it unannotated.
1521 case Sema::NC_Type: {
1522 SourceLocation BeginLoc = NameLoc;
1523 if (SS.isNotEmpty())
1524 BeginLoc = SS.getBeginLoc();
1526 /// An Objective-C object type followed by '<' is a specialization of
1527 /// a parameterized class type or a protocol-qualified type.
1528 ParsedType Ty = Classification.getType();
1529 if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1530 (Ty.get()->isObjCObjectType() ||
1531 Ty.get()->isObjCObjectPointerType())) {
1532 // Consume the name.
1533 SourceLocation IdentifierLoc = ConsumeToken();
1534 SourceLocation NewEndLoc;
1536 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1537 /*consumeLastToken=*/false,
1539 if (NewType.isUsable())
1541 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1545 Tok.setKind(tok::annot_typename);
1546 setTypeAnnotation(Tok, Ty);
1547 Tok.setAnnotationEndLoc(Tok.getLocation());
1548 Tok.setLocation(BeginLoc);
1549 PP.AnnotateCachedTokens(Tok);
1553 case Sema::NC_Expression:
1554 Tok.setKind(tok::annot_primary_expr);
1555 setExprAnnotation(Tok, Classification.getExpression());
1556 Tok.setAnnotationEndLoc(NameLoc);
1557 if (SS.isNotEmpty())
1558 Tok.setLocation(SS.getBeginLoc());
1559 PP.AnnotateCachedTokens(Tok);
1562 case Sema::NC_TypeTemplate:
1563 if (Next.isNot(tok::less)) {
1564 // This may be a type template being used as a template template argument.
1565 if (SS.isNotEmpty())
1566 AnnotateScopeToken(SS, !WasScopeAnnotation);
1567 return ANK_TemplateName;
1570 case Sema::NC_VarTemplate:
1571 case Sema::NC_FunctionTemplate: {
1572 // We have a type, variable or function template followed by '<'.
1575 Id.setIdentifier(Name, NameLoc);
1576 if (AnnotateTemplateIdToken(
1577 TemplateTy::make(Classification.getTemplateName()),
1578 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1583 case Sema::NC_NestedNameSpecifier:
1584 llvm_unreachable("already parsed nested name specifier");
1587 // Unable to classify the name, but maybe we can annotate a scope specifier.
1588 if (SS.isNotEmpty())
1589 AnnotateScopeToken(SS, !WasScopeAnnotation);
1590 return ANK_Unresolved;
1593 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
1594 assert(Tok.isNot(tok::identifier));
1595 Diag(Tok, diag::ext_keyword_as_ident)
1596 << PP.getSpelling(Tok)
1599 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1600 Tok.setKind(tok::identifier);
1604 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1605 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1606 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1607 /// with a single annotation token representing the typename or C++ scope
1609 /// This simplifies handling of C++ scope specifiers and allows efficient
1610 /// backtracking without the need to re-parse and resolve nested-names and
1612 /// It will mainly be called when we expect to treat identifiers as typenames
1613 /// (if they are typenames). For example, in C we do not expect identifiers
1614 /// inside expressions to be treated as typenames so it will not be called
1615 /// for expressions in C.
1616 /// The benefit for C/ObjC is that a typename will be annotated and
1617 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1618 /// will not be called twice, once to check whether we have a declaration
1619 /// specifier, and another one to get the actual type inside
1620 /// ParseDeclarationSpecifiers).
1622 /// This returns true if an error occurred.
1624 /// Note that this routine emits an error if you call it with ::new or ::delete
1625 /// as the current tokens, so only call it in contexts where these are invalid.
1626 bool Parser::TryAnnotateTypeOrScopeToken() {
1627 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1628 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1629 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1630 Tok.is(tok::kw___super)) &&
1631 "Cannot be a type or scope token!");
1633 if (Tok.is(tok::kw_typename)) {
1634 // MSVC lets you do stuff like:
1635 // typename typedef T_::D D;
1637 // We will consume the typedef token here and put it back after we have
1638 // parsed the first identifier, transforming it into something more like:
1639 // typename T_::D typedef D;
1640 if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
1642 PP.Lex(TypedefToken);
1643 bool Result = TryAnnotateTypeOrScopeToken();
1647 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1651 // Parse a C++ typename-specifier, e.g., "typename T::type".
1653 // typename-specifier:
1654 // 'typename' '::' [opt] nested-name-specifier identifier
1655 // 'typename' '::' [opt] nested-name-specifier template [opt]
1656 // simple-template-id
1657 SourceLocation TypenameLoc = ConsumeToken();
1659 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1660 /*EnteringContext=*/false, nullptr,
1661 /*IsTypename*/ true))
1664 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1665 Tok.is(tok::annot_decltype)) {
1666 // Attempt to recover by skipping the invalid 'typename'
1667 if (Tok.is(tok::annot_decltype) ||
1668 (!TryAnnotateTypeOrScopeToken() && Tok.isAnnotation())) {
1669 unsigned DiagID = diag::err_expected_qualified_after_typename;
1670 // MS compatibility: MSVC permits using known types with typename.
1671 // e.g. "typedef typename T* pointer_type"
1672 if (getLangOpts().MicrosoftExt)
1673 DiagID = diag::warn_expected_qualified_after_typename;
1674 Diag(Tok.getLocation(), DiagID);
1679 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1684 if (Tok.is(tok::identifier)) {
1685 // FIXME: check whether the next token is '<', first!
1686 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1687 *Tok.getIdentifierInfo(),
1689 } else if (Tok.is(tok::annot_template_id)) {
1690 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1691 if (TemplateId->Kind != TNK_Type_template &&
1692 TemplateId->Kind != TNK_Dependent_template_name) {
1693 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1694 << Tok.getAnnotationRange();
1698 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1699 TemplateId->NumArgs);
1701 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1702 TemplateId->TemplateKWLoc,
1703 TemplateId->Template,
1704 TemplateId->TemplateNameLoc,
1705 TemplateId->LAngleLoc,
1707 TemplateId->RAngleLoc);
1709 Diag(Tok, diag::err_expected_type_name_after_typename)
1714 SourceLocation EndLoc = Tok.getLastLoc();
1715 Tok.setKind(tok::annot_typename);
1716 setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1717 Tok.setAnnotationEndLoc(EndLoc);
1718 Tok.setLocation(TypenameLoc);
1719 PP.AnnotateCachedTokens(Tok);
1723 // Remembers whether the token was originally a scope annotation.
1724 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1727 if (getLangOpts().CPlusPlus)
1728 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext*/false))
1731 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation);
1734 /// \brief Try to annotate a type or scope token, having already parsed an
1735 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1736 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1737 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS,
1739 if (Tok.is(tok::identifier)) {
1740 // Determine whether the identifier is a type name.
1741 if (ParsedType Ty = Actions.getTypeName(
1742 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1743 false, NextToken().is(tok::period), nullptr,
1744 /*IsCtorOrDtorName=*/false,
1745 /*NonTrivialTypeSourceInfo*/ true)) {
1746 SourceLocation BeginLoc = Tok.getLocation();
1747 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1748 BeginLoc = SS.getBeginLoc();
1750 /// An Objective-C object type followed by '<' is a specialization of
1751 /// a parameterized class type or a protocol-qualified type.
1752 if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1753 (Ty.get()->isObjCObjectType() ||
1754 Ty.get()->isObjCObjectPointerType())) {
1755 // Consume the name.
1756 SourceLocation IdentifierLoc = ConsumeToken();
1757 SourceLocation NewEndLoc;
1759 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1760 /*consumeLastToken=*/false,
1762 if (NewType.isUsable())
1764 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1768 // This is a typename. Replace the current token in-place with an
1769 // annotation type token.
1770 Tok.setKind(tok::annot_typename);
1771 setTypeAnnotation(Tok, Ty);
1772 Tok.setAnnotationEndLoc(Tok.getLocation());
1773 Tok.setLocation(BeginLoc);
1775 // In case the tokens were cached, have Preprocessor replace
1776 // them with the annotation token.
1777 PP.AnnotateCachedTokens(Tok);
1781 if (!getLangOpts().CPlusPlus) {
1782 // If we're in C, we can't have :: tokens at all (the lexer won't return
1783 // them). If the identifier is not a type, then it can't be scope either,
1788 // If this is a template-id, annotate with a template-id or type token.
1789 if (NextToken().is(tok::less)) {
1790 TemplateTy Template;
1791 UnqualifiedId TemplateName;
1792 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1793 bool MemberOfUnknownSpecialization;
1794 if (TemplateNameKind TNK = Actions.isTemplateName(
1796 /*hasTemplateKeyword=*/false, TemplateName,
1797 /*ObjectType=*/nullptr, /*EnteringContext*/false, Template,
1798 MemberOfUnknownSpecialization)) {
1799 // Consume the identifier.
1801 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1803 // If an unrecoverable error occurred, we need to return true here,
1804 // because the token stream is in a damaged state. We may not return
1805 // a valid identifier.
1811 // The current token, which is either an identifier or a
1812 // template-id, is not part of the annotation. Fall through to
1813 // push that token back into the stream and complete the C++ scope
1814 // specifier annotation.
1817 if (Tok.is(tok::annot_template_id)) {
1818 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1819 if (TemplateId->Kind == TNK_Type_template) {
1820 // A template-id that refers to a type was parsed into a
1821 // template-id annotation in a context where we weren't allowed
1822 // to produce a type annotation token. Update the template-id
1823 // annotation token to a type annotation token now.
1824 AnnotateTemplateIdTokenAsType();
1832 // A C++ scope specifier that isn't followed by a typename.
1833 AnnotateScopeToken(SS, IsNewScope);
1837 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1838 /// annotates C++ scope specifiers and template-ids. This returns
1839 /// true if there was an error that could not be recovered from.
1841 /// Note that this routine emits an error if you call it with ::new or ::delete
1842 /// as the current tokens, so only call it in contexts where these are invalid.
1843 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1844 assert(getLangOpts().CPlusPlus &&
1845 "Call sites of this function should be guarded by checking for C++");
1846 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1847 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1848 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1849 "Cannot be a type or scope token!");
1852 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1857 AnnotateScopeToken(SS, true);
1861 bool Parser::isTokenEqualOrEqualTypo() {
1862 tok::TokenKind Kind = Tok.getKind();
1866 case tok::ampequal: // &=
1867 case tok::starequal: // *=
1868 case tok::plusequal: // +=
1869 case tok::minusequal: // -=
1870 case tok::exclaimequal: // !=
1871 case tok::slashequal: // /=
1872 case tok::percentequal: // %=
1873 case tok::lessequal: // <=
1874 case tok::lesslessequal: // <<=
1875 case tok::greaterequal: // >=
1876 case tok::greatergreaterequal: // >>=
1877 case tok::caretequal: // ^=
1878 case tok::pipeequal: // |=
1879 case tok::equalequal: // ==
1880 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1882 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1888 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1889 assert(Tok.is(tok::code_completion));
1890 PrevTokLocation = Tok.getLocation();
1892 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1893 if (S->getFlags() & Scope::FnScope) {
1894 Actions.CodeCompleteOrdinaryName(getCurScope(),
1895 Sema::PCC_RecoveryInFunction);
1897 return PrevTokLocation;
1900 if (S->getFlags() & Scope::ClassScope) {
1901 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1903 return PrevTokLocation;
1907 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1909 return PrevTokLocation;
1912 // Code-completion pass-through functions
1914 void Parser::CodeCompleteDirective(bool InConditional) {
1915 Actions.CodeCompletePreprocessorDirective(InConditional);
1918 void Parser::CodeCompleteInConditionalExclusion() {
1919 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1922 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1923 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1926 void Parser::CodeCompletePreprocessorExpression() {
1927 Actions.CodeCompletePreprocessorExpression();
1930 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1931 MacroInfo *MacroInfo,
1932 unsigned ArgumentIndex) {
1933 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1937 void Parser::CodeCompleteNaturalLanguage() {
1938 Actions.CodeCompleteNaturalLanguage();
1941 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1942 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1943 "Expected '__if_exists' or '__if_not_exists'");
1944 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1945 Result.KeywordLoc = ConsumeToken();
1947 BalancedDelimiterTracker T(*this, tok::l_paren);
1948 if (T.consumeOpen()) {
1949 Diag(Tok, diag::err_expected_lparen_after)
1950 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1954 // Parse nested-name-specifier.
1955 if (getLangOpts().CPlusPlus)
1956 ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
1957 /*EnteringContext=*/false);
1959 // Check nested-name specifier.
1960 if (Result.SS.isInvalid()) {
1965 // Parse the unqualified-id.
1966 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1967 if (ParseUnqualifiedId(Result.SS, false, true, true, nullptr, TemplateKWLoc,
1973 if (T.consumeClose())
1976 // Check if the symbol exists.
1977 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1978 Result.IsIfExists, Result.SS,
1980 case Sema::IER_Exists:
1981 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1984 case Sema::IER_DoesNotExist:
1985 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1988 case Sema::IER_Dependent:
1989 Result.Behavior = IEB_Dependent;
1992 case Sema::IER_Error:
1999 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2000 IfExistsCondition Result;
2001 if (ParseMicrosoftIfExistsCondition(Result))
2004 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2005 if (Braces.consumeOpen()) {
2006 Diag(Tok, diag::err_expected) << tok::l_brace;
2010 switch (Result.Behavior) {
2012 // Parse declarations below.
2016 llvm_unreachable("Cannot have a dependent external declaration");
2023 // Parse the declarations.
2024 // FIXME: Support module import within __if_exists?
2025 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2026 ParsedAttributesWithRange attrs(AttrFactory);
2027 MaybeParseCXX11Attributes(attrs);
2028 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2029 if (Result && !getCurScope()->getParent())
2030 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2032 Braces.consumeClose();
2035 /// Parse a C++ Modules TS module declaration, which appears at the beginning
2036 /// of a module interface, module partition, or module implementation file.
2038 /// module-declaration: [Modules TS + P0273R0]
2039 /// 'module' module-kind[opt] module-name attribute-specifier-seq[opt] ';'
2041 /// 'implementation'
2044 /// Note that the module-kind values are context-sensitive keywords.
2045 Parser::DeclGroupPtrTy Parser::ParseModuleDecl() {
2046 assert(Tok.is(tok::kw_module) && getLangOpts().ModulesTS &&
2047 "should not be parsing a module declaration");
2048 SourceLocation ModuleLoc = ConsumeToken();
2050 // Check for a module-kind.
2051 Sema::ModuleDeclKind MDK = Sema::ModuleDeclKind::Module;
2052 if (Tok.is(tok::identifier) && NextToken().is(tok::identifier)) {
2053 if (Tok.getIdentifierInfo()->isStr("implementation"))
2054 MDK = Sema::ModuleDeclKind::Implementation;
2055 else if (Tok.getIdentifierInfo()->isStr("partition"))
2056 MDK = Sema::ModuleDeclKind::Partition;
2058 Diag(Tok, diag::err_unexpected_module_kind) << Tok.getIdentifierInfo();
2059 SkipUntil(tok::semi);
2065 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2066 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2069 ParsedAttributesWithRange Attrs(AttrFactory);
2070 MaybeParseCXX11Attributes(Attrs);
2071 // We don't support any module attributes yet.
2072 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2074 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2076 return Actions.ActOnModuleDecl(ModuleLoc, MDK, Path);
2079 /// Parse a module import declaration. This is essentially the same for
2080 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2081 /// and the trailing optional attributes (in C++).
2083 /// [ObjC] @import declaration:
2084 /// '@' 'import' module-name ';'
2085 /// [ModTS] module-import-declaration:
2086 /// 'import' module-name attribute-specifier-seq[opt] ';'
2087 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
2088 assert((AtLoc.isInvalid() ? Tok.is(tok::kw_import)
2089 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2090 "Improper start to module import");
2091 SourceLocation ImportLoc = ConsumeToken();
2092 SourceLocation StartLoc = AtLoc.isInvalid() ? ImportLoc : AtLoc;
2094 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2095 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2098 ParsedAttributesWithRange Attrs(AttrFactory);
2099 MaybeParseCXX11Attributes(Attrs);
2100 // We don't support any module import attributes yet.
2101 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2103 if (PP.hadModuleLoaderFatalFailure()) {
2104 // With a fatal failure in the module loader, we abort parsing.
2109 DeclResult Import = Actions.ActOnModuleImport(StartLoc, ImportLoc, Path);
2110 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2111 if (Import.isInvalid())
2114 return Actions.ConvertDeclToDeclGroup(Import.get());
2117 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2121 /// module-name-qualifier[opt] identifier
2122 /// module-name-qualifier:
2123 /// module-name-qualifier[opt] identifier '.'
2124 bool Parser::ParseModuleName(
2125 SourceLocation UseLoc,
2126 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2128 // Parse the module path.
2130 if (!Tok.is(tok::identifier)) {
2131 if (Tok.is(tok::code_completion)) {
2132 Actions.CodeCompleteModuleImport(UseLoc, Path);
2137 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2138 SkipUntil(tok::semi);
2142 // Record this part of the module path.
2143 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2146 if (Tok.isNot(tok::period))
2153 /// \brief Try recover parser when module annotation appears where it must not
2155 /// \returns false if the recover was successful and parsing may be continued, or
2156 /// true if parser must bail out to top level and handle the token there.
2157 bool Parser::parseMisplacedModuleImport() {
2159 switch (Tok.getKind()) {
2160 case tok::annot_module_end:
2161 // If we recovered from a misplaced module begin, we expect to hit a
2162 // misplaced module end too. Stay in the current context when this
2164 if (MisplacedModuleBeginCount) {
2165 --MisplacedModuleBeginCount;
2166 Actions.ActOnModuleEnd(Tok.getLocation(),
2167 reinterpret_cast<Module *>(
2168 Tok.getAnnotationValue()));
2172 // Inform caller that recovery failed, the error must be handled at upper
2173 // level. This will generate the desired "missing '}' at end of module"
2174 // diagnostics on the way out.
2176 case tok::annot_module_begin:
2177 // Recover by entering the module (Sema will diagnose).
2178 Actions.ActOnModuleBegin(Tok.getLocation(),
2179 reinterpret_cast<Module *>(
2180 Tok.getAnnotationValue()));
2182 ++MisplacedModuleBeginCount;
2184 case tok::annot_module_include:
2185 // Module import found where it should not be, for instance, inside a
2186 // namespace. Recover by importing the module.
2187 Actions.ActOnModuleInclude(Tok.getLocation(),
2188 reinterpret_cast<Module *>(
2189 Tok.getAnnotationValue()));
2191 // If there is another module import, process it.
2200 bool BalancedDelimiterTracker::diagnoseOverflow() {
2201 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2202 << P.getLangOpts().BracketDepth;
2203 P.Diag(P.Tok, diag::note_bracket_depth);
2208 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2210 tok::TokenKind SkipToTok) {
2211 LOpen = P.Tok.getLocation();
2212 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2213 if (SkipToTok != tok::unknown)
2214 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2218 if (getDepth() < MaxDepth)
2221 return diagnoseOverflow();
2224 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2225 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2227 if (P.Tok.is(tok::annot_module_end))
2228 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2230 P.Diag(P.Tok, diag::err_expected) << Close;
2231 P.Diag(LOpen, diag::note_matching) << Kind;
2233 // If we're not already at some kind of closing bracket, skip to our closing
2235 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2236 P.Tok.isNot(tok::r_square) &&
2237 P.SkipUntil(Close, FinalToken,
2238 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2240 LClose = P.ConsumeAnyToken();
2244 void BalancedDelimiterTracker::skipToEnd() {
2245 P.SkipUntil(Close, Parser::StopBeforeMatch);