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);
938 Decl* decls[] = {AnonRecord, TheDecl};
939 return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
941 return Actions.ConvertDeclToDeclGroup(TheDecl);
944 DS.takeAttributesFrom(attrs);
946 // ObjC2 allows prefix attributes on class interfaces and protocols.
947 // FIXME: This still needs better diagnostics. We should only accept
948 // attributes here, no types, etc.
949 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
950 SourceLocation AtLoc = ConsumeToken(); // the "@"
951 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
952 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
953 Diag(Tok, diag::err_objc_unexpected_attr);
954 SkipUntil(tok::semi); // FIXME: better skip?
960 const char *PrevSpec = nullptr;
962 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
963 Actions.getASTContext().getPrintingPolicy()))
964 Diag(AtLoc, DiagID) << PrevSpec;
966 if (Tok.isObjCAtKeyword(tok::objc_protocol))
967 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
969 return Actions.ConvertDeclToDeclGroup(
970 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
973 // If the declspec consisted only of 'extern' and we have a string
974 // literal following it, this must be a C++ linkage specifier like
976 if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
977 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
978 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
979 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
980 return Actions.ConvertDeclToDeclGroup(TheDecl);
983 return ParseDeclGroup(DS, Declarator::FileContext);
986 Parser::DeclGroupPtrTy
987 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
989 AccessSpecifier AS) {
991 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
993 ParsingDeclSpec PDS(*this);
994 // Must temporarily exit the objective-c container scope for
995 // parsing c constructs and re-enter objc container scope
997 ObjCDeclContextSwitch ObjCDC(*this);
999 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1003 /// ParseFunctionDefinition - We parsed and verified that the specified
1004 /// Declarator is well formed. If this is a K&R-style function, read the
1005 /// parameters declaration-list, then start the compound-statement.
1007 /// function-definition: [C99 6.9.1]
1008 /// decl-specs declarator declaration-list[opt] compound-statement
1009 /// [C90] function-definition: [C99 6.7.1] - implicit int result
1010 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
1011 /// [C++] function-definition: [C++ 8.4]
1012 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
1014 /// [C++] function-definition: [C++ 8.4]
1015 /// decl-specifier-seq[opt] declarator function-try-block
1017 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1018 const ParsedTemplateInfo &TemplateInfo,
1019 LateParsedAttrList *LateParsedAttrs) {
1020 // Poison SEH identifiers so they are flagged as illegal in function bodies.
1021 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
1022 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1024 // If this is C90 and the declspecs were completely missing, fudge in an
1025 // implicit int. We do this here because this is the only place where
1026 // declaration-specifiers are completely optional in the grammar.
1027 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
1028 const char *PrevSpec;
1030 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1031 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
1032 D.getIdentifierLoc(),
1035 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
1038 // If this declaration was formed with a K&R-style identifier list for the
1039 // arguments, parse declarations for all of the args next.
1040 // int foo(a,b) int a; float b; {}
1041 if (FTI.isKNRPrototype())
1042 ParseKNRParamDeclarations(D);
1044 // We should have either an opening brace or, in a C++ constructor,
1045 // we may have a colon.
1046 if (Tok.isNot(tok::l_brace) &&
1047 (!getLangOpts().CPlusPlus ||
1048 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1049 Tok.isNot(tok::equal)))) {
1050 Diag(Tok, diag::err_expected_fn_body);
1052 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1053 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1055 // If we didn't find the '{', bail out.
1056 if (Tok.isNot(tok::l_brace))
1060 // Check to make sure that any normal attributes are allowed to be on
1061 // a definition. Late parsed attributes are checked at the end.
1062 if (Tok.isNot(tok::equal)) {
1063 AttributeList *DtorAttrs = D.getAttributes();
1065 if (DtorAttrs->isKnownToGCC() &&
1066 !DtorAttrs->isCXX11Attribute()) {
1067 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
1068 << DtorAttrs->getName();
1070 DtorAttrs = DtorAttrs->getNext();
1074 // In delayed template parsing mode, for function template we consume the
1075 // tokens and store them for late parsing at the end of the translation unit.
1076 if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1077 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1078 Actions.canDelayFunctionBody(D)) {
1079 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1081 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1082 Scope *ParentScope = getCurScope()->getParent();
1084 D.setFunctionDefinitionKind(FDK_Definition);
1085 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1086 TemplateParameterLists);
1088 D.getMutableDeclSpec().abort();
1090 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1091 trySkippingFunctionBody()) {
1093 return Actions.ActOnSkippedFunctionBody(DP);
1097 LexTemplateFunctionForLateParsing(Toks);
1100 FunctionDecl *FnD = DP->getAsFunction();
1101 Actions.CheckForFunctionRedefinition(FnD);
1102 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1106 else if (CurParsedObjCImpl &&
1107 !TemplateInfo.TemplateParams &&
1108 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1109 Tok.is(tok::colon)) &&
1110 Actions.CurContext->isTranslationUnit()) {
1111 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1112 Scope *ParentScope = getCurScope()->getParent();
1114 D.setFunctionDefinitionKind(FDK_Definition);
1115 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1116 MultiTemplateParamsArg());
1117 D.complete(FuncDecl);
1118 D.getMutableDeclSpec().abort();
1120 // Consume the tokens and store them for later parsing.
1121 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1122 CurParsedObjCImpl->HasCFunction = true;
1125 // FIXME: Should we really fall through here?
1128 // Enter a scope for the function body.
1129 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1131 // Tell the actions module that we have entered a function definition with the
1132 // specified Declarator for the function.
1133 Sema::SkipBodyInfo SkipBody;
1134 Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,
1135 TemplateInfo.TemplateParams
1136 ? *TemplateInfo.TemplateParams
1137 : MultiTemplateParamsArg(),
1140 if (SkipBody.ShouldSkip) {
1145 // Break out of the ParsingDeclarator context before we parse the body.
1148 // Break out of the ParsingDeclSpec context, too. This const_cast is
1149 // safe because we're always the sole owner.
1150 D.getMutableDeclSpec().abort();
1152 if (TryConsumeToken(tok::equal)) {
1153 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1155 bool Delete = false;
1156 SourceLocation KWLoc;
1157 if (TryConsumeToken(tok::kw_delete, KWLoc)) {
1158 Diag(KWLoc, getLangOpts().CPlusPlus11
1159 ? diag::warn_cxx98_compat_defaulted_deleted_function
1160 : diag::ext_defaulted_deleted_function)
1162 Actions.SetDeclDeleted(Res, KWLoc);
1164 } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
1165 Diag(KWLoc, getLangOpts().CPlusPlus11
1166 ? diag::warn_cxx98_compat_defaulted_deleted_function
1167 : diag::ext_defaulted_deleted_function)
1168 << 0 /* defaulted */;
1169 Actions.SetDeclDefaulted(Res, KWLoc);
1171 llvm_unreachable("function definition after = not 'delete' or 'default'");
1174 if (Tok.is(tok::comma)) {
1175 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1177 SkipUntil(tok::semi);
1178 } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1179 Delete ? "delete" : "default")) {
1180 SkipUntil(tok::semi);
1183 Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;
1184 Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);
1188 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1189 trySkippingFunctionBody()) {
1191 Actions.ActOnSkippedFunctionBody(Res);
1192 return Actions.ActOnFinishFunctionBody(Res, nullptr, false);
1195 if (Tok.is(tok::kw_try))
1196 return ParseFunctionTryBlock(Res, BodyScope);
1198 // If we have a colon, then we're probably parsing a C++
1199 // ctor-initializer.
1200 if (Tok.is(tok::colon)) {
1201 ParseConstructorInitializer(Res);
1203 // Recover from error.
1204 if (!Tok.is(tok::l_brace)) {
1206 Actions.ActOnFinishFunctionBody(Res, nullptr);
1210 Actions.ActOnDefaultCtorInitializers(Res);
1212 // Late attributes are parsed in the same scope as the function body.
1213 if (LateParsedAttrs)
1214 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1216 return ParseFunctionStatementBody(Res, BodyScope);
1219 void Parser::SkipFunctionBody() {
1220 if (Tok.is(tok::equal)) {
1221 SkipUntil(tok::semi);
1225 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1226 if (IsFunctionTryBlock)
1229 CachedTokens Skipped;
1230 if (ConsumeAndStoreFunctionPrologue(Skipped))
1231 SkipMalformedDecl();
1233 SkipUntil(tok::r_brace);
1234 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1235 SkipUntil(tok::l_brace);
1236 SkipUntil(tok::r_brace);
1241 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1242 /// types for a function with a K&R-style identifier list for arguments.
1243 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1244 // We know that the top-level of this declarator is a function.
1245 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1247 // Enter function-declaration scope, limiting any declarators to the
1248 // function prototype scope, including parameter declarators.
1249 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1250 Scope::FunctionDeclarationScope | Scope::DeclScope);
1252 // Read all the argument declarations.
1253 while (isDeclarationSpecifier()) {
1254 SourceLocation DSStart = Tok.getLocation();
1256 // Parse the common declaration-specifiers piece.
1257 DeclSpec DS(AttrFactory);
1258 ParseDeclarationSpecifiers(DS);
1260 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1261 // least one declarator'.
1262 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1263 // the declarations though. It's trivial to ignore them, really hard to do
1264 // anything else with them.
1265 if (TryConsumeToken(tok::semi)) {
1266 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1270 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1272 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1273 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1274 Diag(DS.getStorageClassSpecLoc(),
1275 diag::err_invalid_storage_class_in_func_decl);
1276 DS.ClearStorageClassSpecs();
1278 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1279 Diag(DS.getThreadStorageClassSpecLoc(),
1280 diag::err_invalid_storage_class_in_func_decl);
1281 DS.ClearStorageClassSpecs();
1284 // Parse the first declarator attached to this declspec.
1285 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1286 ParseDeclarator(ParmDeclarator);
1288 // Handle the full declarator list.
1290 // If attributes are present, parse them.
1291 MaybeParseGNUAttributes(ParmDeclarator);
1293 // Ask the actions module to compute the type for this declarator.
1295 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1298 // A missing identifier has already been diagnosed.
1299 ParmDeclarator.getIdentifier()) {
1301 // Scan the argument list looking for the correct param to apply this
1303 for (unsigned i = 0; ; ++i) {
1304 // C99 6.9.1p6: those declarators shall declare only identifiers from
1305 // the identifier list.
1306 if (i == FTI.NumParams) {
1307 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1308 << ParmDeclarator.getIdentifier();
1312 if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
1313 // Reject redefinitions of parameters.
1314 if (FTI.Params[i].Param) {
1315 Diag(ParmDeclarator.getIdentifierLoc(),
1316 diag::err_param_redefinition)
1317 << ParmDeclarator.getIdentifier();
1319 FTI.Params[i].Param = Param;
1326 // If we don't have a comma, it is either the end of the list (a ';') or
1327 // an error, bail out.
1328 if (Tok.isNot(tok::comma))
1331 ParmDeclarator.clear();
1333 // Consume the comma.
1334 ParmDeclarator.setCommaLoc(ConsumeToken());
1336 // Parse the next declarator.
1337 ParseDeclarator(ParmDeclarator);
1340 // Consume ';' and continue parsing.
1341 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1344 // Otherwise recover by skipping to next semi or mandatory function body.
1345 if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
1347 TryConsumeToken(tok::semi);
1350 // The actions module must verify that all arguments were declared.
1351 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1355 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1356 /// allowed to be a wide string, and is not subject to character translation.
1358 /// [GNU] asm-string-literal:
1361 ExprResult Parser::ParseAsmStringLiteral() {
1362 if (!isTokenStringLiteral()) {
1363 Diag(Tok, diag::err_expected_string_literal)
1364 << /*Source='in...'*/0 << "'asm'";
1368 ExprResult AsmString(ParseStringLiteralExpression());
1369 if (!AsmString.isInvalid()) {
1370 const auto *SL = cast<StringLiteral>(AsmString.get());
1371 if (!SL->isAscii()) {
1372 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1374 << SL->getSourceRange();
1383 /// [GNU] simple-asm-expr:
1384 /// 'asm' '(' asm-string-literal ')'
1386 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1387 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1388 SourceLocation Loc = ConsumeToken();
1390 if (Tok.is(tok::kw_volatile)) {
1391 // Remove from the end of 'asm' to the end of 'volatile'.
1392 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1393 PP.getLocForEndOfToken(Tok.getLocation()));
1395 Diag(Tok, diag::warn_file_asm_volatile)
1396 << FixItHint::CreateRemoval(RemovalRange);
1400 BalancedDelimiterTracker T(*this, tok::l_paren);
1401 if (T.consumeOpen()) {
1402 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1406 ExprResult Result(ParseAsmStringLiteral());
1408 if (!Result.isInvalid()) {
1409 // Close the paren and get the location of the end bracket
1412 *EndLoc = T.getCloseLocation();
1413 } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
1415 *EndLoc = Tok.getLocation();
1422 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1423 /// cleanup pool so that it gets destroyed when parsing the current top level
1424 /// declaration is finished.
1425 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1426 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1427 TemplateIdAnnotation *
1428 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1432 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1433 // Push the current token back into the token stream (or revert it if it is
1434 // cached) and use an annotation scope token for current token.
1435 if (PP.isBacktrackEnabled())
1436 PP.RevertCachedTokens(1);
1439 Tok.setKind(tok::annot_cxxscope);
1440 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1441 Tok.setAnnotationRange(SS.getRange());
1443 // In case the tokens were cached, have Preprocessor replace them
1444 // with the annotation token. We don't need to do this if we've
1445 // just reverted back to a prior state.
1446 if (IsNewAnnotation)
1447 PP.AnnotateCachedTokens(Tok);
1450 /// \brief Attempt to classify the name at the current token position. This may
1451 /// form a type, scope or primary expression annotation, or replace the token
1452 /// with a typo-corrected keyword. This is only appropriate when the current
1453 /// name must refer to an entity which has already been declared.
1455 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1456 /// and might possibly have a dependent nested name specifier.
1457 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1458 /// no typo correction will be performed.
1459 Parser::AnnotatedNameKind
1460 Parser::TryAnnotateName(bool IsAddressOfOperand,
1461 std::unique_ptr<CorrectionCandidateCallback> CCC) {
1462 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1464 const bool EnteringContext = false;
1465 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1468 if (getLangOpts().CPlusPlus &&
1469 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1472 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1473 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1474 !WasScopeAnnotation))
1476 return ANK_Unresolved;
1479 IdentifierInfo *Name = Tok.getIdentifierInfo();
1480 SourceLocation NameLoc = Tok.getLocation();
1482 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1483 // typo-correct to tentatively-declared identifiers.
1484 if (isTentativelyDeclared(Name)) {
1485 // Identifier has been tentatively declared, and thus cannot be resolved as
1486 // an expression. Fall back to annotating it as a type.
1487 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1488 !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(bool EnteringContext, bool NeedType) {
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(EnteringContext, NeedType);
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(EnteringContext, NeedType) &&
1669 Tok.isAnnotation())) {
1670 unsigned DiagID = diag::err_expected_qualified_after_typename;
1671 // MS compatibility: MSVC permits using known types with typename.
1672 // e.g. "typedef typename T* pointer_type"
1673 if (getLangOpts().MicrosoftExt)
1674 DiagID = diag::warn_expected_qualified_after_typename;
1675 Diag(Tok.getLocation(), DiagID);
1680 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1685 if (Tok.is(tok::identifier)) {
1686 // FIXME: check whether the next token is '<', first!
1687 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1688 *Tok.getIdentifierInfo(),
1690 } else if (Tok.is(tok::annot_template_id)) {
1691 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1692 if (TemplateId->Kind != TNK_Type_template &&
1693 TemplateId->Kind != TNK_Dependent_template_name) {
1694 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1695 << Tok.getAnnotationRange();
1699 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1700 TemplateId->NumArgs);
1702 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1703 TemplateId->TemplateKWLoc,
1704 TemplateId->Template,
1705 TemplateId->TemplateNameLoc,
1706 TemplateId->LAngleLoc,
1708 TemplateId->RAngleLoc);
1710 Diag(Tok, diag::err_expected_type_name_after_typename)
1715 SourceLocation EndLoc = Tok.getLastLoc();
1716 Tok.setKind(tok::annot_typename);
1717 setTypeAnnotation(Tok, Ty.isInvalid() ? nullptr : Ty.get());
1718 Tok.setAnnotationEndLoc(EndLoc);
1719 Tok.setLocation(TypenameLoc);
1720 PP.AnnotateCachedTokens(Tok);
1724 // Remembers whether the token was originally a scope annotation.
1725 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1728 if (getLangOpts().CPlusPlus)
1729 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1732 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1733 SS, !WasScopeAnnotation);
1736 /// \brief Try to annotate a type or scope token, having already parsed an
1737 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1738 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1739 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1743 if (Tok.is(tok::identifier)) {
1744 IdentifierInfo *CorrectedII = nullptr;
1745 // Determine whether the identifier is a type name.
1746 if (ParsedType Ty = Actions.getTypeName(
1747 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,
1748 false, NextToken().is(tok::period), nullptr,
1749 /*IsCtorOrDtorName=*/false,
1750 /*NonTrivialTypeSourceInfo*/ true,
1751 NeedType ? &CorrectedII : nullptr)) {
1752 // A FixIt was applied as a result of typo correction
1754 Tok.setIdentifierInfo(CorrectedII);
1756 SourceLocation BeginLoc = Tok.getLocation();
1757 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1758 BeginLoc = SS.getBeginLoc();
1760 /// An Objective-C object type followed by '<' is a specialization of
1761 /// a parameterized class type or a protocol-qualified type.
1762 if (getLangOpts().ObjC1 && NextToken().is(tok::less) &&
1763 (Ty.get()->isObjCObjectType() ||
1764 Ty.get()->isObjCObjectPointerType())) {
1765 // Consume the name.
1766 SourceLocation IdentifierLoc = ConsumeToken();
1767 SourceLocation NewEndLoc;
1769 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1770 /*consumeLastToken=*/false,
1772 if (NewType.isUsable())
1774 else if (Tok.is(tok::eof)) // Nothing to do here, bail out...
1778 // This is a typename. Replace the current token in-place with an
1779 // annotation type token.
1780 Tok.setKind(tok::annot_typename);
1781 setTypeAnnotation(Tok, Ty);
1782 Tok.setAnnotationEndLoc(Tok.getLocation());
1783 Tok.setLocation(BeginLoc);
1785 // In case the tokens were cached, have Preprocessor replace
1786 // them with the annotation token.
1787 PP.AnnotateCachedTokens(Tok);
1791 if (!getLangOpts().CPlusPlus) {
1792 // If we're in C, we can't have :: tokens at all (the lexer won't return
1793 // them). If the identifier is not a type, then it can't be scope either,
1798 // If this is a template-id, annotate with a template-id or type token.
1799 if (NextToken().is(tok::less)) {
1800 TemplateTy Template;
1801 UnqualifiedId TemplateName;
1802 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1803 bool MemberOfUnknownSpecialization;
1804 if (TemplateNameKind TNK =
1805 Actions.isTemplateName(getCurScope(), SS,
1806 /*hasTemplateKeyword=*/false, TemplateName,
1807 /*ObjectType=*/nullptr, EnteringContext,
1808 Template, MemberOfUnknownSpecialization)) {
1809 // Consume the identifier.
1811 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1813 // If an unrecoverable error occurred, we need to return true here,
1814 // because the token stream is in a damaged state. We may not return
1815 // a valid identifier.
1821 // The current token, which is either an identifier or a
1822 // template-id, is not part of the annotation. Fall through to
1823 // push that token back into the stream and complete the C++ scope
1824 // specifier annotation.
1827 if (Tok.is(tok::annot_template_id)) {
1828 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1829 if (TemplateId->Kind == TNK_Type_template) {
1830 // A template-id that refers to a type was parsed into a
1831 // template-id annotation in a context where we weren't allowed
1832 // to produce a type annotation token. Update the template-id
1833 // annotation token to a type annotation token now.
1834 AnnotateTemplateIdTokenAsType();
1842 // A C++ scope specifier that isn't followed by a typename.
1843 AnnotateScopeToken(SS, IsNewScope);
1847 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1848 /// annotates C++ scope specifiers and template-ids. This returns
1849 /// true if there was an error that could not be recovered from.
1851 /// Note that this routine emits an error if you call it with ::new or ::delete
1852 /// as the current tokens, so only call it in contexts where these are invalid.
1853 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1854 assert(getLangOpts().CPlusPlus &&
1855 "Call sites of this function should be guarded by checking for C++");
1856 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1857 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1858 Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
1859 "Cannot be a type or scope token!");
1862 if (ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext))
1867 AnnotateScopeToken(SS, true);
1871 bool Parser::isTokenEqualOrEqualTypo() {
1872 tok::TokenKind Kind = Tok.getKind();
1876 case tok::ampequal: // &=
1877 case tok::starequal: // *=
1878 case tok::plusequal: // +=
1879 case tok::minusequal: // -=
1880 case tok::exclaimequal: // !=
1881 case tok::slashequal: // /=
1882 case tok::percentequal: // %=
1883 case tok::lessequal: // <=
1884 case tok::lesslessequal: // <<=
1885 case tok::greaterequal: // >=
1886 case tok::greatergreaterequal: // >>=
1887 case tok::caretequal: // ^=
1888 case tok::pipeequal: // |=
1889 case tok::equalequal: // ==
1890 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1892 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1898 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1899 assert(Tok.is(tok::code_completion));
1900 PrevTokLocation = Tok.getLocation();
1902 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1903 if (S->getFlags() & Scope::FnScope) {
1904 Actions.CodeCompleteOrdinaryName(getCurScope(),
1905 Sema::PCC_RecoveryInFunction);
1907 return PrevTokLocation;
1910 if (S->getFlags() & Scope::ClassScope) {
1911 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1913 return PrevTokLocation;
1917 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1919 return PrevTokLocation;
1922 // Code-completion pass-through functions
1924 void Parser::CodeCompleteDirective(bool InConditional) {
1925 Actions.CodeCompletePreprocessorDirective(InConditional);
1928 void Parser::CodeCompleteInConditionalExclusion() {
1929 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1932 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1933 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1936 void Parser::CodeCompletePreprocessorExpression() {
1937 Actions.CodeCompletePreprocessorExpression();
1940 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1941 MacroInfo *MacroInfo,
1942 unsigned ArgumentIndex) {
1943 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1947 void Parser::CodeCompleteNaturalLanguage() {
1948 Actions.CodeCompleteNaturalLanguage();
1951 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1952 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1953 "Expected '__if_exists' or '__if_not_exists'");
1954 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1955 Result.KeywordLoc = ConsumeToken();
1957 BalancedDelimiterTracker T(*this, tok::l_paren);
1958 if (T.consumeOpen()) {
1959 Diag(Tok, diag::err_expected_lparen_after)
1960 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1964 // Parse nested-name-specifier.
1965 if (getLangOpts().CPlusPlus)
1966 ParseOptionalCXXScopeSpecifier(Result.SS, nullptr,
1967 /*EnteringContext=*/false);
1969 // Check nested-name specifier.
1970 if (Result.SS.isInvalid()) {
1975 // Parse the unqualified-id.
1976 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1977 if (ParseUnqualifiedId(Result.SS, false, true, true, nullptr, TemplateKWLoc,
1983 if (T.consumeClose())
1986 // Check if the symbol exists.
1987 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1988 Result.IsIfExists, Result.SS,
1990 case Sema::IER_Exists:
1991 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1994 case Sema::IER_DoesNotExist:
1995 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1998 case Sema::IER_Dependent:
1999 Result.Behavior = IEB_Dependent;
2002 case Sema::IER_Error:
2009 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2010 IfExistsCondition Result;
2011 if (ParseMicrosoftIfExistsCondition(Result))
2014 BalancedDelimiterTracker Braces(*this, tok::l_brace);
2015 if (Braces.consumeOpen()) {
2016 Diag(Tok, diag::err_expected) << tok::l_brace;
2020 switch (Result.Behavior) {
2022 // Parse declarations below.
2026 llvm_unreachable("Cannot have a dependent external declaration");
2033 // Parse the declarations.
2034 // FIXME: Support module import within __if_exists?
2035 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2036 ParsedAttributesWithRange attrs(AttrFactory);
2037 MaybeParseCXX11Attributes(attrs);
2038 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
2039 if (Result && !getCurScope()->getParent())
2040 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
2042 Braces.consumeClose();
2045 /// Parse a C++ Modules TS module declaration, which appears at the beginning
2046 /// of a module interface, module partition, or module implementation file.
2048 /// module-declaration: [Modules TS + P0273R0]
2049 /// 'module' module-kind[opt] module-name attribute-specifier-seq[opt] ';'
2051 /// 'implementation'
2054 /// Note that the module-kind values are context-sensitive keywords.
2055 Parser::DeclGroupPtrTy Parser::ParseModuleDecl() {
2056 assert(Tok.is(tok::kw_module) && getLangOpts().ModulesTS &&
2057 "should not be parsing a module declaration");
2058 SourceLocation ModuleLoc = ConsumeToken();
2060 // Check for a module-kind.
2061 Sema::ModuleDeclKind MDK = Sema::ModuleDeclKind::Module;
2062 if (Tok.is(tok::identifier) && NextToken().is(tok::identifier)) {
2063 if (Tok.getIdentifierInfo()->isStr("implementation"))
2064 MDK = Sema::ModuleDeclKind::Implementation;
2065 else if (Tok.getIdentifierInfo()->isStr("partition"))
2066 MDK = Sema::ModuleDeclKind::Partition;
2068 Diag(Tok, diag::err_unexpected_module_kind) << Tok.getIdentifierInfo();
2069 SkipUntil(tok::semi);
2075 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2076 if (ParseModuleName(ModuleLoc, Path, /*IsImport*/false))
2079 ParsedAttributesWithRange Attrs(AttrFactory);
2080 MaybeParseCXX11Attributes(Attrs);
2081 // We don't support any module attributes yet.
2082 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2084 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2086 return Actions.ActOnModuleDecl(ModuleLoc, MDK, Path);
2089 /// Parse a module import declaration. This is essentially the same for
2090 /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC)
2091 /// and the trailing optional attributes (in C++).
2093 /// [ObjC] @import declaration:
2094 /// '@' 'import' module-name ';'
2095 /// [ModTS] module-import-declaration:
2096 /// 'import' module-name attribute-specifier-seq[opt] ';'
2097 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
2098 assert((AtLoc.isInvalid() ? Tok.is(tok::kw_import)
2099 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2100 "Improper start to module import");
2101 SourceLocation ImportLoc = ConsumeToken();
2102 SourceLocation StartLoc = AtLoc.isInvalid() ? ImportLoc : AtLoc;
2104 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2105 if (ParseModuleName(ImportLoc, Path, /*IsImport*/true))
2108 ParsedAttributesWithRange Attrs(AttrFactory);
2109 MaybeParseCXX11Attributes(Attrs);
2110 // We don't support any module import attributes yet.
2111 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2113 if (PP.hadModuleLoaderFatalFailure()) {
2114 // With a fatal failure in the module loader, we abort parsing.
2119 DeclResult Import = Actions.ActOnModuleImport(StartLoc, ImportLoc, Path);
2120 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2121 if (Import.isInvalid())
2124 return Actions.ConvertDeclToDeclGroup(Import.get());
2127 /// Parse a C++ Modules TS / Objective-C module name (both forms use the same
2131 /// module-name-qualifier[opt] identifier
2132 /// module-name-qualifier:
2133 /// module-name-qualifier[opt] identifier '.'
2134 bool Parser::ParseModuleName(
2135 SourceLocation UseLoc,
2136 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,
2138 // Parse the module path.
2140 if (!Tok.is(tok::identifier)) {
2141 if (Tok.is(tok::code_completion)) {
2142 Actions.CodeCompleteModuleImport(UseLoc, Path);
2147 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2148 SkipUntil(tok::semi);
2152 // Record this part of the module path.
2153 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
2156 if (Tok.isNot(tok::period))
2163 /// \brief Try recover parser when module annotation appears where it must not
2165 /// \returns false if the recover was successful and parsing may be continued, or
2166 /// true if parser must bail out to top level and handle the token there.
2167 bool Parser::parseMisplacedModuleImport() {
2169 switch (Tok.getKind()) {
2170 case tok::annot_module_end:
2171 // If we recovered from a misplaced module begin, we expect to hit a
2172 // misplaced module end too. Stay in the current context when this
2174 if (MisplacedModuleBeginCount) {
2175 --MisplacedModuleBeginCount;
2176 Actions.ActOnModuleEnd(Tok.getLocation(),
2177 reinterpret_cast<Module *>(
2178 Tok.getAnnotationValue()));
2182 // Inform caller that recovery failed, the error must be handled at upper
2183 // level. This will generate the desired "missing '}' at end of module"
2184 // diagnostics on the way out.
2186 case tok::annot_module_begin:
2187 // Recover by entering the module (Sema will diagnose).
2188 Actions.ActOnModuleBegin(Tok.getLocation(),
2189 reinterpret_cast<Module *>(
2190 Tok.getAnnotationValue()));
2192 ++MisplacedModuleBeginCount;
2194 case tok::annot_module_include:
2195 // Module import found where it should not be, for instance, inside a
2196 // namespace. Recover by importing the module.
2197 Actions.ActOnModuleInclude(Tok.getLocation(),
2198 reinterpret_cast<Module *>(
2199 Tok.getAnnotationValue()));
2201 // If there is another module import, process it.
2210 bool BalancedDelimiterTracker::diagnoseOverflow() {
2211 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2212 << P.getLangOpts().BracketDepth;
2213 P.Diag(P.Tok, diag::note_bracket_depth);
2218 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
2220 tok::TokenKind SkipToTok) {
2221 LOpen = P.Tok.getLocation();
2222 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2223 if (SkipToTok != tok::unknown)
2224 P.SkipUntil(SkipToTok, Parser::StopAtSemi);
2228 if (getDepth() < MaxDepth)
2231 return diagnoseOverflow();
2234 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2235 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
2237 if (P.Tok.is(tok::annot_module_end))
2238 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2240 P.Diag(P.Tok, diag::err_expected) << Close;
2241 P.Diag(LOpen, diag::note_matching) << Kind;
2243 // If we're not already at some kind of closing bracket, skip to our closing
2245 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2246 P.Tok.isNot(tok::r_square) &&
2247 P.SkipUntil(Close, FinalToken,
2248 Parser::StopAtSemi | Parser::StopBeforeMatch) &&
2250 LClose = P.ConsumeAnyToken();
2254 void BalancedDelimiterTracker::skipToEnd() {
2255 P.SkipUntil(Close, Parser::StopBeforeMatch);