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 "ParsePragma.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTConsumer.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 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
28 /// \brief A comment handler that passes comments found by the preprocessor
29 /// to the parser action.
30 class ActionCommentHandler : public CommentHandler {
34 explicit ActionCommentHandler(Sema &S) : S(S) { }
36 virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37 S.ActOnComment(Comment);
41 } // end anonymous namespace
43 IdentifierInfo *Parser::getSEHExceptKeyword() {
44 // __except is accepted as a (contextual) keyword
45 if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46 Ident__except = PP.getIdentifierInfo("__except");
51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53 GreaterThanIsOperator(true), ColonIsSacred(false),
54 InMessageExpression(false), TemplateParameterDepth(0),
55 ParsingInObjCContainer(false) {
56 SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
58 Tok.setKind(tok::eof);
61 ParenCount = BracketCount = BraceCount = 0;
62 CurParsedObjCImpl = 0;
64 // Add #pragma handlers. These are removed and destroyed in the
66 AlignHandler.reset(new PragmaAlignHandler());
67 PP.AddPragmaHandler(AlignHandler.get());
69 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
70 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
72 OptionsHandler.reset(new PragmaOptionsHandler());
73 PP.AddPragmaHandler(OptionsHandler.get());
75 PackHandler.reset(new PragmaPackHandler());
76 PP.AddPragmaHandler(PackHandler.get());
78 MSStructHandler.reset(new PragmaMSStructHandler());
79 PP.AddPragmaHandler(MSStructHandler.get());
81 UnusedHandler.reset(new PragmaUnusedHandler());
82 PP.AddPragmaHandler(UnusedHandler.get());
84 WeakHandler.reset(new PragmaWeakHandler());
85 PP.AddPragmaHandler(WeakHandler.get());
87 RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
88 PP.AddPragmaHandler(RedefineExtnameHandler.get());
90 FPContractHandler.reset(new PragmaFPContractHandler());
91 PP.AddPragmaHandler("STDC", FPContractHandler.get());
93 if (getLangOpts().OpenCL) {
94 OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
95 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
97 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
99 if (getLangOpts().OpenMP)
100 OpenMPHandler.reset(new PragmaOpenMPHandler());
102 OpenMPHandler.reset(new PragmaNoOpenMPHandler());
103 PP.AddPragmaHandler(OpenMPHandler.get());
105 if (getLangOpts().MicrosoftExt) {
106 MSCommentHandler.reset(new PragmaCommentHandler());
107 PP.AddPragmaHandler(MSCommentHandler.get());
110 CommentSemaHandler.reset(new ActionCommentHandler(actions));
111 PP.addCommentHandler(CommentSemaHandler.get());
113 PP.setCodeCompletionHandler(*this);
116 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
117 return Diags.Report(Loc, DiagID);
120 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
121 return Diag(Tok.getLocation(), DiagID);
124 /// \brief Emits a diagnostic suggesting parentheses surrounding a
127 /// \param Loc The location where we'll emit the diagnostic.
128 /// \param DK The kind of diagnostic to emit.
129 /// \param ParenRange Source range enclosing code that should be parenthesized.
130 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
131 SourceRange ParenRange) {
132 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
133 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
134 // We can't display the parentheses, so just dig the
135 // warning/error and return.
141 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
142 << FixItHint::CreateInsertion(EndLoc, ")");
145 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
146 switch (ExpectedTok) {
148 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
149 default: return false;
153 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
154 /// input. If so, it is consumed and false is returned.
156 /// If the input is malformed, this emits the specified diagnostic. Next, if
157 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
159 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
160 const char *Msg, tok::TokenKind SkipToTok) {
161 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
166 // Detect common single-character typos and resume.
167 if (IsCommonTypo(ExpectedTok, Tok)) {
168 SourceLocation Loc = Tok.getLocation();
171 << FixItHint::CreateReplacement(SourceRange(Loc),
172 getTokenSimpleSpelling(ExpectedTok));
175 // Pretend there wasn't a problem.
179 const char *Spelling = 0;
180 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
181 if (EndLoc.isValid() &&
182 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
183 // Show what code to insert to fix this problem.
186 << FixItHint::CreateInsertion(EndLoc, Spelling);
188 Diag(Tok, DiagID) << Msg;
190 if (SkipToTok != tok::unknown)
191 SkipUntil(SkipToTok);
195 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
196 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
201 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
202 NextToken().is(tok::semi)) {
203 Diag(Tok, diag::err_extraneous_token_before_semi)
204 << PP.getSpelling(Tok)
205 << FixItHint::CreateRemoval(Tok.getLocation());
206 ConsumeAnyToken(); // The ')' or ']'.
207 ConsumeToken(); // The ';'.
211 return ExpectAndConsume(tok::semi, DiagID);
214 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
215 if (!Tok.is(tok::semi)) return;
217 bool HadMultipleSemis = false;
218 SourceLocation StartLoc = Tok.getLocation();
219 SourceLocation EndLoc = Tok.getLocation();
222 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
223 HadMultipleSemis = true;
224 EndLoc = Tok.getLocation();
228 // C++11 allows extra semicolons at namespace scope, but not in any of the
230 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
231 if (getLangOpts().CPlusPlus11)
232 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
233 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
235 Diag(StartLoc, diag::ext_extra_semi_cxx11)
236 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
240 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
241 Diag(StartLoc, diag::ext_extra_semi)
242 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
243 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
245 // A single semicolon is valid after a member function definition.
246 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
247 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
250 //===----------------------------------------------------------------------===//
252 //===----------------------------------------------------------------------===//
254 /// SkipUntil - Read tokens until we get to the specified token, then consume
255 /// it (unless DontConsume is true). Because we cannot guarantee that the
256 /// token will ever occur, this skips to the next token, or to some likely
257 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
260 /// If SkipUntil finds the specified token, it returns true, otherwise it
262 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
263 bool DontConsume, bool StopAtCodeCompletion) {
264 // We always want this function to skip at least one token if the first token
265 // isn't T and if not at EOF.
266 bool isFirstTokenSkipped = true;
268 // If we found one of the tokens, stop and return true.
269 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
270 if (Tok.is(Toks[i])) {
272 // Noop, don't consume the token.
280 switch (Tok.getKind()) {
282 // Ran out of tokens.
285 case tok::code_completion:
286 if (!StopAtCodeCompletion)
291 // Recursively skip properly-nested parens.
293 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
296 // Recursively skip properly-nested square brackets.
298 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
301 // Recursively skip properly-nested braces.
303 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
306 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
307 // Since the user wasn't looking for this token (if they were, it would
308 // already be handled), this isn't balanced. If there is a LHS token at a
309 // higher level, we will assume that this matches the unbalanced token
310 // and return it. Otherwise, this is a spurious RHS token, which we skip.
312 if (ParenCount && !isFirstTokenSkipped)
313 return false; // Matches something.
317 if (BracketCount && !isFirstTokenSkipped)
318 return false; // Matches something.
322 if (BraceCount && !isFirstTokenSkipped)
323 return false; // Matches something.
327 case tok::string_literal:
328 case tok::wide_string_literal:
329 case tok::utf8_string_literal:
330 case tok::utf16_string_literal:
331 case tok::utf32_string_literal:
332 ConsumeStringToken();
344 isFirstTokenSkipped = false;
348 //===----------------------------------------------------------------------===//
349 // Scope manipulation
350 //===----------------------------------------------------------------------===//
352 /// EnterScope - Start a new scope.
353 void Parser::EnterScope(unsigned ScopeFlags) {
354 if (NumCachedScopes) {
355 Scope *N = ScopeCache[--NumCachedScopes];
356 N->Init(getCurScope(), ScopeFlags);
357 Actions.CurScope = N;
359 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
363 /// ExitScope - Pop a scope off the scope stack.
364 void Parser::ExitScope() {
365 assert(getCurScope() && "Scope imbalance!");
367 // Inform the actions module that this scope is going away if there are any
369 if (!getCurScope()->decl_empty())
370 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
372 Scope *OldScope = getCurScope();
373 Actions.CurScope = OldScope->getParent();
375 if (NumCachedScopes == ScopeCacheSize)
378 ScopeCache[NumCachedScopes++] = OldScope;
381 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
382 /// this object does nothing.
383 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
385 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
387 OldFlags = CurScope->getFlags();
388 CurScope->setFlags(ScopeFlags);
392 /// Restore the flags for the current scope to what they were before this
393 /// object overrode them.
394 Parser::ParseScopeFlags::~ParseScopeFlags() {
396 CurScope->setFlags(OldFlags);
400 //===----------------------------------------------------------------------===//
401 // C99 6.9: External Definitions.
402 //===----------------------------------------------------------------------===//
405 // If we still have scopes active, delete the scope tree.
406 delete getCurScope();
407 Actions.CurScope = 0;
409 // Free the scope cache.
410 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
411 delete ScopeCache[i];
413 // Free LateParsedTemplatedFunction nodes.
414 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
415 it != LateParsedTemplateMap.end(); ++it)
418 // Remove the pragma handlers we installed.
419 PP.RemovePragmaHandler(AlignHandler.get());
420 AlignHandler.reset();
421 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
422 GCCVisibilityHandler.reset();
423 PP.RemovePragmaHandler(OptionsHandler.get());
424 OptionsHandler.reset();
425 PP.RemovePragmaHandler(PackHandler.get());
427 PP.RemovePragmaHandler(MSStructHandler.get());
428 MSStructHandler.reset();
429 PP.RemovePragmaHandler(UnusedHandler.get());
430 UnusedHandler.reset();
431 PP.RemovePragmaHandler(WeakHandler.get());
433 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
434 RedefineExtnameHandler.reset();
436 if (getLangOpts().OpenCL) {
437 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
438 OpenCLExtensionHandler.reset();
439 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
441 PP.RemovePragmaHandler(OpenMPHandler.get());
442 OpenMPHandler.reset();
444 if (getLangOpts().MicrosoftExt) {
445 PP.RemovePragmaHandler(MSCommentHandler.get());
446 MSCommentHandler.reset();
449 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
450 FPContractHandler.reset();
452 PP.removeCommentHandler(CommentSemaHandler.get());
454 PP.clearCodeCompletionHandler();
456 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
459 /// Initialize - Warm up the parser.
461 void Parser::Initialize() {
462 // Create the translation unit scope. Install it as the current scope.
463 assert(getCurScope() == 0 && "A scope is already active?");
464 EnterScope(Scope::DeclScope);
465 Actions.ActOnTranslationUnitScope(getCurScope());
467 // Initialization for Objective-C context sensitive keywords recognition.
468 // Referenced in Parser::ParseObjCTypeQualifierList.
469 if (getLangOpts().ObjC1) {
470 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
471 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
472 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
473 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
474 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
475 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
478 Ident_instancetype = 0;
482 Ident_super = &PP.getIdentifierTable().get("super");
484 if (getLangOpts().AltiVec) {
485 Ident_vector = &PP.getIdentifierTable().get("vector");
486 Ident_pixel = &PP.getIdentifierTable().get("pixel");
489 Ident_introduced = 0;
490 Ident_deprecated = 0;
492 Ident_unavailable = 0;
496 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
497 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
498 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
500 if(getLangOpts().Borland) {
501 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
502 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
503 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
504 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
505 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
506 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
507 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
508 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
509 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
511 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
512 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
513 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
514 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
515 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
516 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
517 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
518 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
519 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
522 Actions.Initialize();
524 // Prime the lexer look-ahead.
529 /// \brief RAIIObject to destroy the contents of a SmallVector of
530 /// TemplateIdAnnotation pointers and clear the vector.
531 class DestroyTemplateIdAnnotationsRAIIObj {
532 SmallVectorImpl<TemplateIdAnnotation *> &Container;
534 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
536 : Container(Container) {}
538 ~DestroyTemplateIdAnnotationsRAIIObj() {
539 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
540 Container.begin(), E = Container.end();
548 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
549 /// action tells us to. This returns true if the EOF was encountered.
550 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
551 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
553 // Skip over the EOF token, flagging end of previous input for incremental
555 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
558 while (Tok.is(tok::annot_pragma_unused))
559 HandlePragmaUnused();
561 Result = DeclGroupPtrTy();
562 if (Tok.is(tok::eof)) {
563 // Late template parsing can begin.
564 if (getLangOpts().DelayedTemplateParsing)
565 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
566 if (!PP.isIncrementalProcessingEnabled())
567 Actions.ActOnEndOfTranslationUnit();
568 //else don't tell Sema that we ended parsing: more input might come.
573 ParsedAttributesWithRange attrs(AttrFactory);
574 MaybeParseCXX11Attributes(attrs);
575 MaybeParseMicrosoftAttributes(attrs);
577 Result = ParseExternalDeclaration(attrs);
581 /// ParseExternalDeclaration:
583 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
584 /// function-definition
586 /// [GNU] asm-definition
587 /// [GNU] __extension__ external-declaration
588 /// [OBJC] objc-class-definition
589 /// [OBJC] objc-class-declaration
590 /// [OBJC] objc-alias-declaration
591 /// [OBJC] objc-protocol-definition
592 /// [OBJC] objc-method-definition
594 /// [C++] linkage-specification
595 /// [GNU] asm-definition:
596 /// simple-asm-expr ';'
597 /// [C++11] empty-declaration
598 /// [C++11] attribute-declaration
600 /// [C++11] empty-declaration:
603 /// [C++0x/GNU] 'extern' 'template' declaration
604 Parser::DeclGroupPtrTy
605 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
606 ParsingDeclSpec *DS) {
607 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
608 ParenBraceBracketBalancer BalancerRAIIObj(*this);
610 if (PP.isCodeCompletionReached()) {
612 return DeclGroupPtrTy();
615 Decl *SingleDecl = 0;
616 switch (Tok.getKind()) {
617 case tok::annot_pragma_vis:
618 HandlePragmaVisibility();
619 return DeclGroupPtrTy();
620 case tok::annot_pragma_pack:
622 return DeclGroupPtrTy();
623 case tok::annot_pragma_msstruct:
624 HandlePragmaMSStruct();
625 return DeclGroupPtrTy();
626 case tok::annot_pragma_align:
628 return DeclGroupPtrTy();
629 case tok::annot_pragma_weak:
631 return DeclGroupPtrTy();
632 case tok::annot_pragma_weakalias:
633 HandlePragmaWeakAlias();
634 return DeclGroupPtrTy();
635 case tok::annot_pragma_redefine_extname:
636 HandlePragmaRedefineExtname();
637 return DeclGroupPtrTy();
638 case tok::annot_pragma_fp_contract:
639 HandlePragmaFPContract();
640 return DeclGroupPtrTy();
641 case tok::annot_pragma_opencl_extension:
642 HandlePragmaOpenCLExtension();
643 return DeclGroupPtrTy();
644 case tok::annot_pragma_openmp:
645 ParseOpenMPDeclarativeDirective();
646 return DeclGroupPtrTy();
648 // Either a C++11 empty-declaration or attribute-declaration.
649 SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
652 ConsumeExtraSemi(OutsideFunction);
655 Diag(Tok, diag::err_extraneous_closing_brace);
657 return DeclGroupPtrTy();
659 Diag(Tok, diag::err_expected_external_declaration);
660 return DeclGroupPtrTy();
661 case tok::kw___extension__: {
662 // __extension__ silences extension warnings in the subexpression.
663 ExtensionRAIIObject O(Diags); // Use RAII to do this.
665 return ParseExternalDeclaration(attrs);
668 ProhibitAttributes(attrs);
670 SourceLocation StartLoc = Tok.getLocation();
671 SourceLocation EndLoc;
672 ExprResult Result(ParseSimpleAsm(&EndLoc));
674 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
675 "top-level asm block");
677 if (Result.isInvalid())
678 return DeclGroupPtrTy();
679 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
683 return ParseObjCAtDirectives();
686 if (!getLangOpts().ObjC1) {
687 Diag(Tok, diag::err_expected_external_declaration);
689 return DeclGroupPtrTy();
691 SingleDecl = ParseObjCMethodDefinition();
693 case tok::code_completion:
694 Actions.CodeCompleteOrdinaryName(getCurScope(),
695 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
696 : Sema::PCC_Namespace);
698 return DeclGroupPtrTy();
700 case tok::kw_namespace:
701 case tok::kw_typedef:
702 case tok::kw_template:
703 case tok::kw_export: // As in 'export template'
704 case tok::kw_static_assert:
705 case tok::kw__Static_assert:
706 // A function definition cannot start with any of these keywords.
708 SourceLocation DeclEnd;
710 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
714 // Parse (then ignore) 'static' prior to a template instantiation. This is
715 // a GCC extension that we intentionally do not support.
716 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
717 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
719 SourceLocation DeclEnd;
721 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
726 if (getLangOpts().CPlusPlus) {
727 tok::TokenKind NextKind = NextToken().getKind();
729 // Inline namespaces. Allowed as an extension even in C++03.
730 if (NextKind == tok::kw_namespace) {
731 SourceLocation DeclEnd;
733 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
736 // Parse (then ignore) 'inline' prior to a template instantiation. This is
737 // a GCC extension that we intentionally do not support.
738 if (NextKind == tok::kw_template) {
739 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
741 SourceLocation DeclEnd;
743 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
749 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
751 SourceLocation ExternLoc = ConsumeToken();
752 SourceLocation TemplateLoc = ConsumeToken();
753 Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
754 diag::warn_cxx98_compat_extern_template :
755 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
756 SourceLocation DeclEnd;
757 return Actions.ConvertDeclToDeclGroup(
758 ParseExplicitInstantiation(Declarator::FileContext,
759 ExternLoc, TemplateLoc, DeclEnd));
761 // FIXME: Detect C++ linkage specifications here?
764 case tok::kw___if_exists:
765 case tok::kw___if_not_exists:
766 ParseMicrosoftIfExistsExternalDeclaration();
767 return DeclGroupPtrTy();
771 // We can't tell whether this is a function-definition or declaration yet.
772 return ParseDeclarationOrFunctionDefinition(attrs, DS);
775 // This routine returns a DeclGroup, if the thing we parsed only contains a
776 // single decl, convert it now.
777 return Actions.ConvertDeclToDeclGroup(SingleDecl);
780 /// \brief Determine whether the current token, if it occurs after a
781 /// declarator, continues a declaration or declaration list.
782 bool Parser::isDeclarationAfterDeclarator() {
783 // Check for '= delete' or '= default'
784 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
785 const Token &KW = NextToken();
786 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
790 return Tok.is(tok::equal) || // int X()= -> not a function def
791 Tok.is(tok::comma) || // int X(), -> not a function def
792 Tok.is(tok::semi) || // int X(); -> not a function def
793 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
794 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
795 (getLangOpts().CPlusPlus &&
796 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
799 /// \brief Determine whether the current token, if it occurs after a
800 /// declarator, indicates the start of a function definition.
801 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
802 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
803 if (Tok.is(tok::l_brace)) // int X() {}
806 // Handle K&R C argument lists: int X(f) int f; {}
807 if (!getLangOpts().CPlusPlus &&
808 Declarator.getFunctionTypeInfo().isKNRPrototype())
809 return isDeclarationSpecifier();
811 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
812 const Token &KW = NextToken();
813 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
816 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
817 Tok.is(tok::kw_try); // X() try { ... }
820 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
821 /// a declaration. We can't tell which we have until we read up to the
822 /// compound-statement in function-definition. TemplateParams, if
823 /// non-NULL, provides the template parameters when we're parsing a
824 /// C++ template-declaration.
826 /// function-definition: [C99 6.9.1]
827 /// decl-specs declarator declaration-list[opt] compound-statement
828 /// [C90] function-definition: [C99 6.7.1] - implicit int result
829 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
831 /// declaration: [C99 6.7]
832 /// declaration-specifiers init-declarator-list[opt] ';'
833 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
834 /// [OMP] threadprivate-directive [TODO]
836 Parser::DeclGroupPtrTy
837 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
839 AccessSpecifier AS) {
840 // Parse the common declaration-specifiers piece.
841 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
843 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
844 // declaration-specifiers init-declarator-list[opt] ';'
845 if (Tok.is(tok::semi)) {
846 ProhibitAttributes(attrs);
848 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
849 DS.complete(TheDecl);
850 return Actions.ConvertDeclToDeclGroup(TheDecl);
853 DS.takeAttributesFrom(attrs);
855 // ObjC2 allows prefix attributes on class interfaces and protocols.
856 // FIXME: This still needs better diagnostics. We should only accept
857 // attributes here, no types, etc.
858 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
859 SourceLocation AtLoc = ConsumeToken(); // the "@"
860 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
861 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
862 Diag(Tok, diag::err_objc_unexpected_attr);
863 SkipUntil(tok::semi); // FIXME: better skip?
864 return DeclGroupPtrTy();
869 const char *PrevSpec = 0;
871 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
872 Diag(AtLoc, DiagID) << PrevSpec;
874 if (Tok.isObjCAtKeyword(tok::objc_protocol))
875 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
877 return Actions.ConvertDeclToDeclGroup(
878 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
881 // If the declspec consisted only of 'extern' and we have a string
882 // literal following it, this must be a C++ linkage specifier like
884 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
885 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
886 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
887 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
888 return Actions.ConvertDeclToDeclGroup(TheDecl);
891 return ParseDeclGroup(DS, Declarator::FileContext, true);
894 Parser::DeclGroupPtrTy
895 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
897 AccessSpecifier AS) {
899 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
901 ParsingDeclSpec PDS(*this);
902 // Must temporarily exit the objective-c container scope for
903 // parsing c constructs and re-enter objc container scope
905 ObjCDeclContextSwitch ObjCDC(*this);
907 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
911 /// ParseFunctionDefinition - We parsed and verified that the specified
912 /// Declarator is well formed. If this is a K&R-style function, read the
913 /// parameters declaration-list, then start the compound-statement.
915 /// function-definition: [C99 6.9.1]
916 /// decl-specs declarator declaration-list[opt] compound-statement
917 /// [C90] function-definition: [C99 6.7.1] - implicit int result
918 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
919 /// [C++] function-definition: [C++ 8.4]
920 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
922 /// [C++] function-definition: [C++ 8.4]
923 /// decl-specifier-seq[opt] declarator function-try-block
925 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
926 const ParsedTemplateInfo &TemplateInfo,
927 LateParsedAttrList *LateParsedAttrs) {
928 // Poison the SEH identifiers so they are flagged as illegal in function bodies
929 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
930 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
932 // If this is C90 and the declspecs were completely missing, fudge in an
933 // implicit int. We do this here because this is the only place where
934 // declaration-specifiers are completely optional in the grammar.
935 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
936 const char *PrevSpec;
938 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
939 D.getIdentifierLoc(),
941 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
944 // If this declaration was formed with a K&R-style identifier list for the
945 // arguments, parse declarations for all of the args next.
946 // int foo(a,b) int a; float b; {}
947 if (FTI.isKNRPrototype())
948 ParseKNRParamDeclarations(D);
950 // We should have either an opening brace or, in a C++ constructor,
951 // we may have a colon.
952 if (Tok.isNot(tok::l_brace) &&
953 (!getLangOpts().CPlusPlus ||
954 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
955 Tok.isNot(tok::equal)))) {
956 Diag(Tok, diag::err_expected_fn_body);
958 // Skip over garbage, until we get to '{'. Don't eat the '{'.
959 SkipUntil(tok::l_brace, true, true);
961 // If we didn't find the '{', bail out.
962 if (Tok.isNot(tok::l_brace))
966 // Check to make sure that any normal attributes are allowed to be on
967 // a definition. Late parsed attributes are checked at the end.
968 if (Tok.isNot(tok::equal)) {
969 AttributeList *DtorAttrs = D.getAttributes();
971 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName()) &&
972 !DtorAttrs->isCXX11Attribute()) {
973 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
974 << DtorAttrs->getName()->getName();
976 DtorAttrs = DtorAttrs->getNext();
980 // In delayed template parsing mode, for function template we consume the
981 // tokens and store them for late parsing at the end of the translation unit.
982 if (getLangOpts().DelayedTemplateParsing &&
983 Tok.isNot(tok::equal) &&
984 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
985 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
987 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
988 Scope *ParentScope = getCurScope()->getParent();
990 D.setFunctionDefinitionKind(FDK_Definition);
991 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
992 TemplateParameterLists);
994 D.getMutableDeclSpec().abort();
997 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
999 FunctionDecl *FnD = 0;
1000 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1001 FnD = FunTmpl->getTemplatedDecl();
1003 FnD = cast<FunctionDecl>(DP);
1004 Actions.CheckForFunctionRedefinition(FnD);
1006 LateParsedTemplateMap[FnD] = LPT;
1007 Actions.MarkAsLateParsedTemplate(FnD);
1008 LexTemplateFunctionForLateParsing(LPT->Toks);
1011 LexTemplateFunctionForLateParsing(Toks);
1015 else if (CurParsedObjCImpl &&
1016 !TemplateInfo.TemplateParams &&
1017 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1018 Tok.is(tok::colon)) &&
1019 Actions.CurContext->isTranslationUnit()) {
1020 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1021 Scope *ParentScope = getCurScope()->getParent();
1023 D.setFunctionDefinitionKind(FDK_Definition);
1024 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1025 MultiTemplateParamsArg());
1026 D.complete(FuncDecl);
1027 D.getMutableDeclSpec().abort();
1029 // Consume the tokens and store them for later parsing.
1030 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1031 CurParsedObjCImpl->HasCFunction = true;
1036 // Enter a scope for the function body.
1037 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1039 // Tell the actions module that we have entered a function definition with the
1040 // specified Declarator for the function.
1041 Decl *Res = TemplateInfo.TemplateParams?
1042 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1043 *TemplateInfo.TemplateParams, D)
1044 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1046 // Break out of the ParsingDeclarator context before we parse the body.
1049 // Break out of the ParsingDeclSpec context, too. This const_cast is
1050 // safe because we're always the sole owner.
1051 D.getMutableDeclSpec().abort();
1053 if (Tok.is(tok::equal)) {
1054 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1057 Actions.ActOnFinishFunctionBody(Res, 0, false);
1059 bool Delete = false;
1060 SourceLocation KWLoc;
1061 if (Tok.is(tok::kw_delete)) {
1062 Diag(Tok, getLangOpts().CPlusPlus11 ?
1063 diag::warn_cxx98_compat_deleted_function :
1064 diag::ext_deleted_function);
1066 KWLoc = ConsumeToken();
1067 Actions.SetDeclDeleted(Res, KWLoc);
1069 } else if (Tok.is(tok::kw_default)) {
1070 Diag(Tok, getLangOpts().CPlusPlus11 ?
1071 diag::warn_cxx98_compat_defaulted_function :
1072 diag::ext_defaulted_function);
1074 KWLoc = ConsumeToken();
1075 Actions.SetDeclDefaulted(Res, KWLoc);
1077 llvm_unreachable("function definition after = not 'delete' or 'default'");
1080 if (Tok.is(tok::comma)) {
1081 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1083 SkipUntil(tok::semi);
1085 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1086 Delete ? "delete" : "default", tok::semi);
1092 if (Tok.is(tok::kw_try))
1093 return ParseFunctionTryBlock(Res, BodyScope);
1095 // If we have a colon, then we're probably parsing a C++
1096 // ctor-initializer.
1097 if (Tok.is(tok::colon)) {
1098 ParseConstructorInitializer(Res);
1100 // Recover from error.
1101 if (!Tok.is(tok::l_brace)) {
1103 Actions.ActOnFinishFunctionBody(Res, 0);
1107 Actions.ActOnDefaultCtorInitializers(Res);
1109 // Late attributes are parsed in the same scope as the function body.
1110 if (LateParsedAttrs)
1111 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1113 return ParseFunctionStatementBody(Res, BodyScope);
1116 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1117 /// types for a function with a K&R-style identifier list for arguments.
1118 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1119 // We know that the top-level of this declarator is a function.
1120 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1122 // Enter function-declaration scope, limiting any declarators to the
1123 // function prototype scope, including parameter declarators.
1124 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1125 Scope::FunctionDeclarationScope | Scope::DeclScope);
1127 // Read all the argument declarations.
1128 while (isDeclarationSpecifier()) {
1129 SourceLocation DSStart = Tok.getLocation();
1131 // Parse the common declaration-specifiers piece.
1132 DeclSpec DS(AttrFactory);
1133 ParseDeclarationSpecifiers(DS);
1135 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1136 // least one declarator'.
1137 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1138 // the declarations though. It's trivial to ignore them, really hard to do
1139 // anything else with them.
1140 if (Tok.is(tok::semi)) {
1141 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1146 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1148 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1149 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1150 Diag(DS.getStorageClassSpecLoc(),
1151 diag::err_invalid_storage_class_in_func_decl);
1152 DS.ClearStorageClassSpecs();
1154 if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1155 Diag(DS.getThreadStorageClassSpecLoc(),
1156 diag::err_invalid_storage_class_in_func_decl);
1157 DS.ClearStorageClassSpecs();
1160 // Parse the first declarator attached to this declspec.
1161 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1162 ParseDeclarator(ParmDeclarator);
1164 // Handle the full declarator list.
1166 // If attributes are present, parse them.
1167 MaybeParseGNUAttributes(ParmDeclarator);
1169 // Ask the actions module to compute the type for this declarator.
1171 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1174 // A missing identifier has already been diagnosed.
1175 ParmDeclarator.getIdentifier()) {
1177 // Scan the argument list looking for the correct param to apply this
1179 for (unsigned i = 0; ; ++i) {
1180 // C99 6.9.1p6: those declarators shall declare only identifiers from
1181 // the identifier list.
1182 if (i == FTI.NumArgs) {
1183 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1184 << ParmDeclarator.getIdentifier();
1188 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1189 // Reject redefinitions of parameters.
1190 if (FTI.ArgInfo[i].Param) {
1191 Diag(ParmDeclarator.getIdentifierLoc(),
1192 diag::err_param_redefinition)
1193 << ParmDeclarator.getIdentifier();
1195 FTI.ArgInfo[i].Param = Param;
1202 // If we don't have a comma, it is either the end of the list (a ';') or
1203 // an error, bail out.
1204 if (Tok.isNot(tok::comma))
1207 ParmDeclarator.clear();
1209 // Consume the comma.
1210 ParmDeclarator.setCommaLoc(ConsumeToken());
1212 // Parse the next declarator.
1213 ParseDeclarator(ParmDeclarator);
1216 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1217 // Skip to end of block or statement
1218 SkipUntil(tok::semi, true);
1219 if (Tok.is(tok::semi))
1224 // The actions module must verify that all arguments were declared.
1225 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1229 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1230 /// allowed to be a wide string, and is not subject to character translation.
1232 /// [GNU] asm-string-literal:
1235 Parser::ExprResult Parser::ParseAsmStringLiteral() {
1236 switch (Tok.getKind()) {
1237 case tok::string_literal:
1239 case tok::utf8_string_literal:
1240 case tok::utf16_string_literal:
1241 case tok::utf32_string_literal:
1242 case tok::wide_string_literal: {
1243 SourceLocation L = Tok.getLocation();
1244 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1245 << (Tok.getKind() == tok::wide_string_literal)
1246 << SourceRange(L, L);
1250 Diag(Tok, diag::err_expected_string_literal)
1251 << /*Source='in...'*/0 << "'asm'";
1255 return ParseStringLiteralExpression();
1260 /// [GNU] simple-asm-expr:
1261 /// 'asm' '(' asm-string-literal ')'
1263 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1264 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1265 SourceLocation Loc = ConsumeToken();
1267 if (Tok.is(tok::kw_volatile)) {
1268 // Remove from the end of 'asm' to the end of 'volatile'.
1269 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1270 PP.getLocForEndOfToken(Tok.getLocation()));
1272 Diag(Tok, diag::warn_file_asm_volatile)
1273 << FixItHint::CreateRemoval(RemovalRange);
1277 BalancedDelimiterTracker T(*this, tok::l_paren);
1278 if (T.consumeOpen()) {
1279 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1283 ExprResult Result(ParseAsmStringLiteral());
1285 if (Result.isInvalid()) {
1286 SkipUntil(tok::r_paren, true, true);
1288 *EndLoc = Tok.getLocation();
1291 // Close the paren and get the location of the end bracket
1294 *EndLoc = T.getCloseLocation();
1300 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1301 /// cleanup pool so that it gets destroyed when parsing the current top level
1302 /// declaration is finished.
1303 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1304 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1305 TemplateIdAnnotation *
1306 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1310 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1311 // Push the current token back into the token stream (or revert it if it is
1312 // cached) and use an annotation scope token for current token.
1313 if (PP.isBacktrackEnabled())
1314 PP.RevertCachedTokens(1);
1317 Tok.setKind(tok::annot_cxxscope);
1318 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1319 Tok.setAnnotationRange(SS.getRange());
1321 // In case the tokens were cached, have Preprocessor replace them
1322 // with the annotation token. We don't need to do this if we've
1323 // just reverted back to a prior state.
1324 if (IsNewAnnotation)
1325 PP.AnnotateCachedTokens(Tok);
1328 /// \brief Attempt to classify the name at the current token position. This may
1329 /// form a type, scope or primary expression annotation, or replace the token
1330 /// with a typo-corrected keyword. This is only appropriate when the current
1331 /// name must refer to an entity which has already been declared.
1333 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1334 /// and might possibly have a dependent nested name specifier.
1335 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1336 /// no typo correction will be performed.
1337 Parser::AnnotatedNameKind
1338 Parser::TryAnnotateName(bool IsAddressOfOperand,
1339 CorrectionCandidateCallback *CCC) {
1340 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1342 const bool EnteringContext = false;
1343 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1346 if (getLangOpts().CPlusPlus &&
1347 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1350 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1351 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1352 !WasScopeAnnotation))
1354 return ANK_Unresolved;
1357 IdentifierInfo *Name = Tok.getIdentifierInfo();
1358 SourceLocation NameLoc = Tok.getLocation();
1360 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1361 // typo-correct to tentatively-declared identifiers.
1362 if (isTentativelyDeclared(Name)) {
1363 // Identifier has been tentatively declared, and thus cannot be resolved as
1364 // an expression. Fall back to annotating it as a type.
1365 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1366 !WasScopeAnnotation))
1368 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1371 Token Next = NextToken();
1373 // Look up and classify the identifier. We don't perform any typo-correction
1374 // after a scope specifier, because in general we can't recover from typos
1375 // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1376 // back into scope specifier parsing).
1377 Sema::NameClassification Classification
1378 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1379 IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1381 switch (Classification.getKind()) {
1382 case Sema::NC_Error:
1385 case Sema::NC_Keyword:
1386 // The identifier was typo-corrected to a keyword.
1387 Tok.setIdentifierInfo(Name);
1388 Tok.setKind(Name->getTokenID());
1389 PP.TypoCorrectToken(Tok);
1390 if (SS.isNotEmpty())
1391 AnnotateScopeToken(SS, !WasScopeAnnotation);
1392 // We've "annotated" this as a keyword.
1395 case Sema::NC_Unknown:
1396 // It's not something we know about. Leave it unannotated.
1400 Tok.setKind(tok::annot_typename);
1401 setTypeAnnotation(Tok, Classification.getType());
1402 Tok.setAnnotationEndLoc(NameLoc);
1403 if (SS.isNotEmpty())
1404 Tok.setLocation(SS.getBeginLoc());
1405 PP.AnnotateCachedTokens(Tok);
1408 case Sema::NC_Expression:
1409 Tok.setKind(tok::annot_primary_expr);
1410 setExprAnnotation(Tok, Classification.getExpression());
1411 Tok.setAnnotationEndLoc(NameLoc);
1412 if (SS.isNotEmpty())
1413 Tok.setLocation(SS.getBeginLoc());
1414 PP.AnnotateCachedTokens(Tok);
1417 case Sema::NC_TypeTemplate:
1418 if (Next.isNot(tok::less)) {
1419 // This may be a type template being used as a template template argument.
1420 if (SS.isNotEmpty())
1421 AnnotateScopeToken(SS, !WasScopeAnnotation);
1422 return ANK_TemplateName;
1425 case Sema::NC_FunctionTemplate: {
1426 // We have a type or function template followed by '<'.
1429 Id.setIdentifier(Name, NameLoc);
1430 if (AnnotateTemplateIdToken(
1431 TemplateTy::make(Classification.getTemplateName()),
1432 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1437 case Sema::NC_NestedNameSpecifier:
1438 llvm_unreachable("already parsed nested name specifier");
1441 // Unable to classify the name, but maybe we can annotate a scope specifier.
1442 if (SS.isNotEmpty())
1443 AnnotateScopeToken(SS, !WasScopeAnnotation);
1444 return ANK_Unresolved;
1447 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1448 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1449 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1450 /// with a single annotation token representing the typename or C++ scope
1452 /// This simplifies handling of C++ scope specifiers and allows efficient
1453 /// backtracking without the need to re-parse and resolve nested-names and
1455 /// It will mainly be called when we expect to treat identifiers as typenames
1456 /// (if they are typenames). For example, in C we do not expect identifiers
1457 /// inside expressions to be treated as typenames so it will not be called
1458 /// for expressions in C.
1459 /// The benefit for C/ObjC is that a typename will be annotated and
1460 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1461 /// will not be called twice, once to check whether we have a declaration
1462 /// specifier, and another one to get the actual type inside
1463 /// ParseDeclarationSpecifiers).
1465 /// This returns true if an error occurred.
1467 /// Note that this routine emits an error if you call it with ::new or ::delete
1468 /// as the current tokens, so only call it in contexts where these are invalid.
1469 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1470 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1471 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1472 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1473 && "Cannot be a type or scope token!");
1475 if (Tok.is(tok::kw_typename)) {
1476 // Parse a C++ typename-specifier, e.g., "typename T::type".
1478 // typename-specifier:
1479 // 'typename' '::' [opt] nested-name-specifier identifier
1480 // 'typename' '::' [opt] nested-name-specifier template [opt]
1481 // simple-template-id
1482 SourceLocation TypenameLoc = ConsumeToken();
1484 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1485 /*EnteringContext=*/false,
1486 0, /*IsTypename*/true))
1489 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1490 Tok.is(tok::annot_decltype)) {
1491 // Attempt to recover by skipping the invalid 'typename'
1492 if (Tok.is(tok::annot_decltype) ||
1493 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1494 Tok.isAnnotation())) {
1495 unsigned DiagID = diag::err_expected_qualified_after_typename;
1496 // MS compatibility: MSVC permits using known types with typename.
1497 // e.g. "typedef typename T* pointer_type"
1498 if (getLangOpts().MicrosoftExt)
1499 DiagID = diag::warn_expected_qualified_after_typename;
1500 Diag(Tok.getLocation(), DiagID);
1505 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1510 if (Tok.is(tok::identifier)) {
1511 // FIXME: check whether the next token is '<', first!
1512 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1513 *Tok.getIdentifierInfo(),
1515 } else if (Tok.is(tok::annot_template_id)) {
1516 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1517 if (TemplateId->Kind == TNK_Function_template) {
1518 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1519 << Tok.getAnnotationRange();
1523 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1524 TemplateId->NumArgs);
1526 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1527 TemplateId->TemplateKWLoc,
1528 TemplateId->Template,
1529 TemplateId->TemplateNameLoc,
1530 TemplateId->LAngleLoc,
1532 TemplateId->RAngleLoc);
1534 Diag(Tok, diag::err_expected_type_name_after_typename)
1539 SourceLocation EndLoc = Tok.getLastLoc();
1540 Tok.setKind(tok::annot_typename);
1541 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1542 Tok.setAnnotationEndLoc(EndLoc);
1543 Tok.setLocation(TypenameLoc);
1544 PP.AnnotateCachedTokens(Tok);
1548 // Remembers whether the token was originally a scope annotation.
1549 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1552 if (getLangOpts().CPlusPlus)
1553 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1556 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1557 SS, !WasScopeAnnotation);
1560 /// \brief Try to annotate a type or scope token, having already parsed an
1561 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1562 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1563 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1567 if (Tok.is(tok::identifier)) {
1568 IdentifierInfo *CorrectedII = 0;
1569 // Determine whether the identifier is a type name.
1570 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1571 Tok.getLocation(), getCurScope(),
1573 NextToken().is(tok::period),
1575 /*IsCtorOrDtorName=*/false,
1576 /*NonTrivialTypeSourceInfo*/true,
1577 NeedType ? &CorrectedII : NULL)) {
1578 // A FixIt was applied as a result of typo correction
1580 Tok.setIdentifierInfo(CorrectedII);
1581 // This is a typename. Replace the current token in-place with an
1582 // annotation type token.
1583 Tok.setKind(tok::annot_typename);
1584 setTypeAnnotation(Tok, Ty);
1585 Tok.setAnnotationEndLoc(Tok.getLocation());
1586 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1587 Tok.setLocation(SS.getBeginLoc());
1589 // In case the tokens were cached, have Preprocessor replace
1590 // them with the annotation token.
1591 PP.AnnotateCachedTokens(Tok);
1595 if (!getLangOpts().CPlusPlus) {
1596 // If we're in C, we can't have :: tokens at all (the lexer won't return
1597 // them). If the identifier is not a type, then it can't be scope either,
1602 // If this is a template-id, annotate with a template-id or type token.
1603 if (NextToken().is(tok::less)) {
1604 TemplateTy Template;
1605 UnqualifiedId TemplateName;
1606 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1607 bool MemberOfUnknownSpecialization;
1608 if (TemplateNameKind TNK
1609 = Actions.isTemplateName(getCurScope(), SS,
1610 /*hasTemplateKeyword=*/false, TemplateName,
1611 /*ObjectType=*/ ParsedType(),
1613 Template, MemberOfUnknownSpecialization)) {
1614 // Consume the identifier.
1616 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1618 // If an unrecoverable error occurred, we need to return true here,
1619 // because the token stream is in a damaged state. We may not return
1620 // a valid identifier.
1626 // The current token, which is either an identifier or a
1627 // template-id, is not part of the annotation. Fall through to
1628 // push that token back into the stream and complete the C++ scope
1629 // specifier annotation.
1632 if (Tok.is(tok::annot_template_id)) {
1633 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1634 if (TemplateId->Kind == TNK_Type_template) {
1635 // A template-id that refers to a type was parsed into a
1636 // template-id annotation in a context where we weren't allowed
1637 // to produce a type annotation token. Update the template-id
1638 // annotation token to a type annotation token now.
1639 AnnotateTemplateIdTokenAsType();
1647 // A C++ scope specifier that isn't followed by a typename.
1648 AnnotateScopeToken(SS, IsNewScope);
1652 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1653 /// annotates C++ scope specifiers and template-ids. This returns
1654 /// true if there was an error that could not be recovered from.
1656 /// Note that this routine emits an error if you call it with ::new or ::delete
1657 /// as the current tokens, so only call it in contexts where these are invalid.
1658 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1659 assert(getLangOpts().CPlusPlus &&
1660 "Call sites of this function should be guarded by checking for C++");
1661 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1662 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1663 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1666 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1671 AnnotateScopeToken(SS, true);
1675 bool Parser::isTokenEqualOrEqualTypo() {
1676 tok::TokenKind Kind = Tok.getKind();
1680 case tok::ampequal: // &=
1681 case tok::starequal: // *=
1682 case tok::plusequal: // +=
1683 case tok::minusequal: // -=
1684 case tok::exclaimequal: // !=
1685 case tok::slashequal: // /=
1686 case tok::percentequal: // %=
1687 case tok::lessequal: // <=
1688 case tok::lesslessequal: // <<=
1689 case tok::greaterequal: // >=
1690 case tok::greatergreaterequal: // >>=
1691 case tok::caretequal: // ^=
1692 case tok::pipeequal: // |=
1693 case tok::equalequal: // ==
1694 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1695 << getTokenSimpleSpelling(Kind)
1696 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1702 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1703 assert(Tok.is(tok::code_completion));
1704 PrevTokLocation = Tok.getLocation();
1706 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1707 if (S->getFlags() & Scope::FnScope) {
1708 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1710 return PrevTokLocation;
1713 if (S->getFlags() & Scope::ClassScope) {
1714 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1716 return PrevTokLocation;
1720 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1722 return PrevTokLocation;
1725 // Anchor the Parser::FieldCallback vtable to this translation unit.
1726 // We use a spurious method instead of the destructor because
1727 // destroying FieldCallbacks can actually be slightly
1728 // performance-sensitive.
1729 void Parser::FieldCallback::_anchor() {
1732 // Code-completion pass-through functions
1734 void Parser::CodeCompleteDirective(bool InConditional) {
1735 Actions.CodeCompletePreprocessorDirective(InConditional);
1738 void Parser::CodeCompleteInConditionalExclusion() {
1739 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1742 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1743 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1746 void Parser::CodeCompletePreprocessorExpression() {
1747 Actions.CodeCompletePreprocessorExpression();
1750 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1751 MacroInfo *MacroInfo,
1752 unsigned ArgumentIndex) {
1753 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1757 void Parser::CodeCompleteNaturalLanguage() {
1758 Actions.CodeCompleteNaturalLanguage();
1761 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1762 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1763 "Expected '__if_exists' or '__if_not_exists'");
1764 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1765 Result.KeywordLoc = ConsumeToken();
1767 BalancedDelimiterTracker T(*this, tok::l_paren);
1768 if (T.consumeOpen()) {
1769 Diag(Tok, diag::err_expected_lparen_after)
1770 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1774 // Parse nested-name-specifier.
1775 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1776 /*EnteringContext=*/false);
1778 // Check nested-name specifier.
1779 if (Result.SS.isInvalid()) {
1784 // Parse the unqualified-id.
1785 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1786 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1787 TemplateKWLoc, Result.Name)) {
1792 if (T.consumeClose())
1795 // Check if the symbol exists.
1796 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1797 Result.IsIfExists, Result.SS,
1799 case Sema::IER_Exists:
1800 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1803 case Sema::IER_DoesNotExist:
1804 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1807 case Sema::IER_Dependent:
1808 Result.Behavior = IEB_Dependent;
1811 case Sema::IER_Error:
1818 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1819 IfExistsCondition Result;
1820 if (ParseMicrosoftIfExistsCondition(Result))
1823 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1824 if (Braces.consumeOpen()) {
1825 Diag(Tok, diag::err_expected_lbrace);
1829 switch (Result.Behavior) {
1831 // Parse declarations below.
1835 llvm_unreachable("Cannot have a dependent external declaration");
1842 // Parse the declarations.
1843 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1844 ParsedAttributesWithRange attrs(AttrFactory);
1845 MaybeParseCXX11Attributes(attrs);
1846 MaybeParseMicrosoftAttributes(attrs);
1847 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1848 if (Result && !getCurScope()->getParent())
1849 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1851 Braces.consumeClose();
1854 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1855 assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1856 "Improper start to module import");
1857 SourceLocation ImportLoc = ConsumeToken();
1859 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1861 // Parse the module path.
1863 if (!Tok.is(tok::identifier)) {
1864 if (Tok.is(tok::code_completion)) {
1865 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1866 ConsumeCodeCompletionToken();
1867 SkipUntil(tok::semi);
1868 return DeclGroupPtrTy();
1871 Diag(Tok, diag::err_module_expected_ident);
1872 SkipUntil(tok::semi);
1873 return DeclGroupPtrTy();
1876 // Record this part of the module path.
1877 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1880 if (Tok.is(tok::period)) {
1888 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1889 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1890 if (Import.isInvalid())
1891 return DeclGroupPtrTy();
1893 return Actions.ConvertDeclToDeclGroup(Import.get());
1896 bool BalancedDelimiterTracker::diagnoseOverflow() {
1897 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1898 << P.getLangOpts().BracketDepth;
1899 P.Diag(P.Tok, diag::note_bracket_depth);
1900 P.SkipUntil(tok::eof);
1904 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1906 tok::TokenKind SkipToToc ) {
1907 LOpen = P.Tok.getLocation();
1908 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1911 if (getDepth() < MaxDepth)
1914 return diagnoseOverflow();
1917 bool BalancedDelimiterTracker::diagnoseMissingClose() {
1918 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1920 const char *LHSName = "unknown";
1923 default: llvm_unreachable("Unexpected balanced token");
1924 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1925 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1926 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1929 P.Diag(LOpen, diag::note_matching) << LHSName;
1930 if (P.SkipUntil(Close, /*StopAtSemi*/ true, /*DontConsume*/ true))
1931 LClose = P.ConsumeAnyToken();
1935 void BalancedDelimiterTracker::skipToEnd() {
1936 P.SkipUntil(Close, false);