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 "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Sema/DeclSpec.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "RAIIObjectsForParser.h"
21 #include "ParsePragma.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ASTConsumer.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());
100 CommentSemaHandler.reset(new ActionCommentHandler(actions));
101 PP.addCommentHandler(CommentSemaHandler.get());
103 PP.setCodeCompletionHandler(*this);
106 /// If a crash happens while the parser is active, print out a line indicating
107 /// what the current token is.
108 void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
109 const Token &Tok = P.getCurToken();
110 if (Tok.is(tok::eof)) {
111 OS << "<eof> parser at end of file\n";
115 if (Tok.getLocation().isInvalid()) {
116 OS << "<unknown> parser at unknown location\n";
120 const Preprocessor &PP = P.getPreprocessor();
121 Tok.getLocation().print(OS, PP.getSourceManager());
122 if (Tok.isAnnotation())
123 OS << ": at annotation token \n";
125 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
129 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
130 return Diags.Report(Loc, DiagID);
133 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
134 return Diag(Tok.getLocation(), DiagID);
137 /// \brief Emits a diagnostic suggesting parentheses surrounding a
140 /// \param Loc The location where we'll emit the diagnostic.
141 /// \param DK The kind of diagnostic to emit.
142 /// \param ParenRange Source range enclosing code that should be parenthesized.
143 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
144 SourceRange ParenRange) {
145 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
146 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
147 // We can't display the parentheses, so just dig the
148 // warning/error and return.
154 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
155 << FixItHint::CreateInsertion(EndLoc, ")");
158 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
159 switch (ExpectedTok) {
161 return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
162 default: return false;
166 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
167 /// input. If so, it is consumed and false is returned.
169 /// If the input is malformed, this emits the specified diagnostic. Next, if
170 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
172 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
173 const char *Msg, tok::TokenKind SkipToTok) {
174 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
179 // Detect common single-character typos and resume.
180 if (IsCommonTypo(ExpectedTok, Tok)) {
181 SourceLocation Loc = Tok.getLocation();
184 << FixItHint::CreateReplacement(SourceRange(Loc),
185 getTokenSimpleSpelling(ExpectedTok));
188 // Pretend there wasn't a problem.
192 const char *Spelling = 0;
193 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
194 if (EndLoc.isValid() &&
195 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
196 // Show what code to insert to fix this problem.
199 << FixItHint::CreateInsertion(EndLoc, Spelling);
201 Diag(Tok, DiagID) << Msg;
203 if (SkipToTok != tok::unknown)
204 SkipUntil(SkipToTok);
208 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
209 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
214 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
215 NextToken().is(tok::semi)) {
216 Diag(Tok, diag::err_extraneous_token_before_semi)
217 << PP.getSpelling(Tok)
218 << FixItHint::CreateRemoval(Tok.getLocation());
219 ConsumeAnyToken(); // The ')' or ']'.
220 ConsumeToken(); // The ';'.
224 return ExpectAndConsume(tok::semi, DiagID);
227 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
228 if (!Tok.is(tok::semi)) return;
230 bool HadMultipleSemis = false;
231 SourceLocation StartLoc = Tok.getLocation();
232 SourceLocation EndLoc = Tok.getLocation();
235 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
236 HadMultipleSemis = true;
237 EndLoc = Tok.getLocation();
241 // C++11 allows extra semicolons at namespace scope, but not in any of the
243 if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
244 if (getLangOpts().CPlusPlus0x)
245 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
246 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
248 Diag(StartLoc, diag::ext_extra_semi_cxx11)
249 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
253 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
254 Diag(StartLoc, diag::ext_extra_semi)
255 << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
256 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
258 // A single semicolon is valid after a member function definition.
259 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
260 << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
263 //===----------------------------------------------------------------------===//
265 //===----------------------------------------------------------------------===//
267 /// SkipUntil - Read tokens until we get to the specified token, then consume
268 /// it (unless DontConsume is true). Because we cannot guarantee that the
269 /// token will ever occur, this skips to the next token, or to some likely
270 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
273 /// If SkipUntil finds the specified token, it returns true, otherwise it
275 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
276 bool DontConsume, bool StopAtCodeCompletion) {
277 // We always want this function to skip at least one token if the first token
278 // isn't T and if not at EOF.
279 bool isFirstTokenSkipped = true;
281 // If we found one of the tokens, stop and return true.
282 for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
283 if (Tok.is(Toks[i])) {
285 // Noop, don't consume the token.
293 switch (Tok.getKind()) {
295 // Ran out of tokens.
298 case tok::code_completion:
299 if (!StopAtCodeCompletion)
304 // Recursively skip properly-nested parens.
306 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
309 // Recursively skip properly-nested square brackets.
311 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
314 // Recursively skip properly-nested braces.
316 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
319 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
320 // Since the user wasn't looking for this token (if they were, it would
321 // already be handled), this isn't balanced. If there is a LHS token at a
322 // higher level, we will assume that this matches the unbalanced token
323 // and return it. Otherwise, this is a spurious RHS token, which we skip.
325 if (ParenCount && !isFirstTokenSkipped)
326 return false; // Matches something.
330 if (BracketCount && !isFirstTokenSkipped)
331 return false; // Matches something.
335 if (BraceCount && !isFirstTokenSkipped)
336 return false; // Matches something.
340 case tok::string_literal:
341 case tok::wide_string_literal:
342 case tok::utf8_string_literal:
343 case tok::utf16_string_literal:
344 case tok::utf32_string_literal:
345 ConsumeStringToken();
357 isFirstTokenSkipped = false;
361 //===----------------------------------------------------------------------===//
362 // Scope manipulation
363 //===----------------------------------------------------------------------===//
365 /// EnterScope - Start a new scope.
366 void Parser::EnterScope(unsigned ScopeFlags) {
367 if (NumCachedScopes) {
368 Scope *N = ScopeCache[--NumCachedScopes];
369 N->Init(getCurScope(), ScopeFlags);
370 Actions.CurScope = N;
372 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
376 /// ExitScope - Pop a scope off the scope stack.
377 void Parser::ExitScope() {
378 assert(getCurScope() && "Scope imbalance!");
380 // Inform the actions module that this scope is going away if there are any
382 if (!getCurScope()->decl_empty())
383 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
385 Scope *OldScope = getCurScope();
386 Actions.CurScope = OldScope->getParent();
388 if (NumCachedScopes == ScopeCacheSize)
391 ScopeCache[NumCachedScopes++] = OldScope;
394 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
395 /// this object does nothing.
396 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
398 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
400 OldFlags = CurScope->getFlags();
401 CurScope->setFlags(ScopeFlags);
405 /// Restore the flags for the current scope to what they were before this
406 /// object overrode them.
407 Parser::ParseScopeFlags::~ParseScopeFlags() {
409 CurScope->setFlags(OldFlags);
413 //===----------------------------------------------------------------------===//
414 // C99 6.9: External Definitions.
415 //===----------------------------------------------------------------------===//
418 // If we still have scopes active, delete the scope tree.
419 delete getCurScope();
420 Actions.CurScope = 0;
422 // Free the scope cache.
423 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
424 delete ScopeCache[i];
426 // Free LateParsedTemplatedFunction nodes.
427 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
428 it != LateParsedTemplateMap.end(); ++it)
431 // Remove the pragma handlers we installed.
432 PP.RemovePragmaHandler(AlignHandler.get());
433 AlignHandler.reset();
434 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
435 GCCVisibilityHandler.reset();
436 PP.RemovePragmaHandler(OptionsHandler.get());
437 OptionsHandler.reset();
438 PP.RemovePragmaHandler(PackHandler.get());
440 PP.RemovePragmaHandler(MSStructHandler.get());
441 MSStructHandler.reset();
442 PP.RemovePragmaHandler(UnusedHandler.get());
443 UnusedHandler.reset();
444 PP.RemovePragmaHandler(WeakHandler.get());
446 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
447 RedefineExtnameHandler.reset();
449 if (getLangOpts().OpenCL) {
450 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
451 OpenCLExtensionHandler.reset();
452 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
455 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
456 FPContractHandler.reset();
458 PP.removeCommentHandler(CommentSemaHandler.get());
460 PP.clearCodeCompletionHandler();
462 assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
465 /// Initialize - Warm up the parser.
467 void Parser::Initialize() {
468 // Create the translation unit scope. Install it as the current scope.
469 assert(getCurScope() == 0 && "A scope is already active?");
470 EnterScope(Scope::DeclScope);
471 Actions.ActOnTranslationUnitScope(getCurScope());
473 // Initialization for Objective-C context sensitive keywords recognition.
474 // Referenced in Parser::ParseObjCTypeQualifierList.
475 if (getLangOpts().ObjC1) {
476 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
477 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
478 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
479 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
480 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
481 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
484 Ident_instancetype = 0;
488 Ident_super = &PP.getIdentifierTable().get("super");
490 if (getLangOpts().AltiVec) {
491 Ident_vector = &PP.getIdentifierTable().get("vector");
492 Ident_pixel = &PP.getIdentifierTable().get("pixel");
495 Ident_introduced = 0;
496 Ident_deprecated = 0;
498 Ident_unavailable = 0;
502 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
503 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
504 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
506 if(getLangOpts().Borland) {
507 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
508 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
509 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
510 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
511 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
512 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
513 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
514 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
515 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
517 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
518 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
519 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
520 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
521 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
522 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
523 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
524 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
525 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
528 Actions.Initialize();
530 // Prime the lexer look-ahead.
535 /// \brief RAIIObject to destroy the contents of a SmallVector of
536 /// TemplateIdAnnotation pointers and clear the vector.
537 class DestroyTemplateIdAnnotationsRAIIObj {
538 SmallVectorImpl<TemplateIdAnnotation *> &Container;
540 DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
542 : Container(Container) {}
544 ~DestroyTemplateIdAnnotationsRAIIObj() {
545 for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
546 Container.begin(), E = Container.end();
554 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
555 /// action tells us to. This returns true if the EOF was encountered.
556 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
557 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
559 // Skip over the EOF token, flagging end of previous input for incremental
561 if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
564 while (Tok.is(tok::annot_pragma_unused))
565 HandlePragmaUnused();
567 Result = DeclGroupPtrTy();
568 if (Tok.is(tok::eof)) {
569 // Late template parsing can begin.
570 if (getLangOpts().DelayedTemplateParsing)
571 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
572 if (!PP.isIncrementalProcessingEnabled())
573 Actions.ActOnEndOfTranslationUnit();
574 //else don't tell Sema that we ended parsing: more input might come.
579 ParsedAttributesWithRange attrs(AttrFactory);
580 MaybeParseCXX0XAttributes(attrs);
581 MaybeParseMicrosoftAttributes(attrs);
583 Result = ParseExternalDeclaration(attrs);
587 /// ParseTranslationUnit:
588 /// translation-unit: [C99 6.9]
589 /// external-declaration
590 /// translation-unit external-declaration
591 void Parser::ParseTranslationUnit() {
595 while (!ParseTopLevelDecl(Res))
599 assert(getCurScope() == 0 && "Scope imbalance!");
602 /// ParseExternalDeclaration:
604 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
605 /// function-definition
607 /// [C++0x] empty-declaration
608 /// [GNU] asm-definition
609 /// [GNU] __extension__ external-declaration
610 /// [OBJC] objc-class-definition
611 /// [OBJC] objc-class-declaration
612 /// [OBJC] objc-alias-declaration
613 /// [OBJC] objc-protocol-definition
614 /// [OBJC] objc-method-definition
616 /// [C++] linkage-specification
617 /// [GNU] asm-definition:
618 /// simple-asm-expr ';'
620 /// [C++0x] empty-declaration:
623 /// [C++0x/GNU] 'extern' 'template' declaration
624 Parser::DeclGroupPtrTy
625 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
626 ParsingDeclSpec *DS) {
627 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
628 ParenBraceBracketBalancer BalancerRAIIObj(*this);
630 if (PP.isCodeCompletionReached()) {
632 return DeclGroupPtrTy();
635 Decl *SingleDecl = 0;
636 switch (Tok.getKind()) {
637 case tok::annot_pragma_vis:
638 HandlePragmaVisibility();
639 return DeclGroupPtrTy();
640 case tok::annot_pragma_pack:
642 return DeclGroupPtrTy();
643 case tok::annot_pragma_msstruct:
644 HandlePragmaMSStruct();
645 return DeclGroupPtrTy();
646 case tok::annot_pragma_align:
648 return DeclGroupPtrTy();
649 case tok::annot_pragma_weak:
651 return DeclGroupPtrTy();
652 case tok::annot_pragma_weakalias:
653 HandlePragmaWeakAlias();
654 return DeclGroupPtrTy();
655 case tok::annot_pragma_redefine_extname:
656 HandlePragmaRedefineExtname();
657 return DeclGroupPtrTy();
658 case tok::annot_pragma_fp_contract:
659 HandlePragmaFPContract();
660 return DeclGroupPtrTy();
661 case tok::annot_pragma_opencl_extension:
662 HandlePragmaOpenCLExtension();
663 return DeclGroupPtrTy();
665 ConsumeExtraSemi(OutsideFunction);
666 // TODO: Invoke action for top-level semicolon.
667 return DeclGroupPtrTy();
669 Diag(Tok, diag::err_extraneous_closing_brace);
671 return DeclGroupPtrTy();
673 Diag(Tok, diag::err_expected_external_declaration);
674 return DeclGroupPtrTy();
675 case tok::kw___extension__: {
676 // __extension__ silences extension warnings in the subexpression.
677 ExtensionRAIIObject O(Diags); // Use RAII to do this.
679 return ParseExternalDeclaration(attrs);
682 ProhibitAttributes(attrs);
684 SourceLocation StartLoc = Tok.getLocation();
685 SourceLocation EndLoc;
686 ExprResult Result(ParseSimpleAsm(&EndLoc));
688 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
689 "top-level asm block");
691 if (Result.isInvalid())
692 return DeclGroupPtrTy();
693 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
697 return ParseObjCAtDirectives();
700 if (!getLangOpts().ObjC1) {
701 Diag(Tok, diag::err_expected_external_declaration);
703 return DeclGroupPtrTy();
705 SingleDecl = ParseObjCMethodDefinition();
707 case tok::code_completion:
708 Actions.CodeCompleteOrdinaryName(getCurScope(),
709 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
710 : Sema::PCC_Namespace);
712 return DeclGroupPtrTy();
714 case tok::kw_namespace:
715 case tok::kw_typedef:
716 case tok::kw_template:
717 case tok::kw_export: // As in 'export template'
718 case tok::kw_static_assert:
719 case tok::kw__Static_assert:
720 // A function definition cannot start with any of these keywords.
722 SourceLocation DeclEnd;
724 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
728 // Parse (then ignore) 'static' prior to a template instantiation. This is
729 // a GCC extension that we intentionally do not support.
730 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
731 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
733 SourceLocation DeclEnd;
735 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
740 if (getLangOpts().CPlusPlus) {
741 tok::TokenKind NextKind = NextToken().getKind();
743 // Inline namespaces. Allowed as an extension even in C++03.
744 if (NextKind == tok::kw_namespace) {
745 SourceLocation DeclEnd;
747 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
750 // Parse (then ignore) 'inline' prior to a template instantiation. This is
751 // a GCC extension that we intentionally do not support.
752 if (NextKind == tok::kw_template) {
753 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
755 SourceLocation DeclEnd;
757 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
763 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
765 SourceLocation ExternLoc = ConsumeToken();
766 SourceLocation TemplateLoc = ConsumeToken();
767 Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
768 diag::warn_cxx98_compat_extern_template :
769 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
770 SourceLocation DeclEnd;
771 return Actions.ConvertDeclToDeclGroup(
772 ParseExplicitInstantiation(Declarator::FileContext,
773 ExternLoc, TemplateLoc, DeclEnd));
775 // FIXME: Detect C++ linkage specifications here?
778 case tok::kw___if_exists:
779 case tok::kw___if_not_exists:
780 ParseMicrosoftIfExistsExternalDeclaration();
781 return DeclGroupPtrTy();
785 // We can't tell whether this is a function-definition or declaration yet.
787 return ParseDeclarationOrFunctionDefinition(attrs, DS);
789 return ParseDeclarationOrFunctionDefinition(attrs);
793 // This routine returns a DeclGroup, if the thing we parsed only contains a
794 // single decl, convert it now.
795 return Actions.ConvertDeclToDeclGroup(SingleDecl);
798 /// \brief Determine whether the current token, if it occurs after a
799 /// declarator, continues a declaration or declaration list.
800 bool Parser::isDeclarationAfterDeclarator() {
801 // Check for '= delete' or '= default'
802 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
803 const Token &KW = NextToken();
804 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
808 return Tok.is(tok::equal) || // int X()= -> not a function def
809 Tok.is(tok::comma) || // int X(), -> not a function def
810 Tok.is(tok::semi) || // int X(); -> not a function def
811 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
812 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
813 (getLangOpts().CPlusPlus &&
814 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
817 /// \brief Determine whether the current token, if it occurs after a
818 /// declarator, indicates the start of a function definition.
819 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
820 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
821 if (Tok.is(tok::l_brace)) // int X() {}
824 // Handle K&R C argument lists: int X(f) int f; {}
825 if (!getLangOpts().CPlusPlus &&
826 Declarator.getFunctionTypeInfo().isKNRPrototype())
827 return isDeclarationSpecifier();
829 if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
830 const Token &KW = NextToken();
831 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
834 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
835 Tok.is(tok::kw_try); // X() try { ... }
838 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
839 /// a declaration. We can't tell which we have until we read up to the
840 /// compound-statement in function-definition. TemplateParams, if
841 /// non-NULL, provides the template parameters when we're parsing a
842 /// C++ template-declaration.
844 /// function-definition: [C99 6.9.1]
845 /// decl-specs declarator declaration-list[opt] compound-statement
846 /// [C90] function-definition: [C99 6.7.1] - implicit int result
847 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
849 /// declaration: [C99 6.7]
850 /// declaration-specifiers init-declarator-list[opt] ';'
851 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
852 /// [OMP] threadprivate-directive [TODO]
854 Parser::DeclGroupPtrTy
855 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
857 AccessSpecifier AS) {
858 // Parse the common declaration-specifiers piece.
859 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
861 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
862 // declaration-specifiers init-declarator-list[opt] ';'
863 if (Tok.is(tok::semi)) {
864 ProhibitAttributes(attrs);
866 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
867 DS.complete(TheDecl);
868 return Actions.ConvertDeclToDeclGroup(TheDecl);
871 DS.takeAttributesFrom(attrs);
873 // ObjC2 allows prefix attributes on class interfaces and protocols.
874 // FIXME: This still needs better diagnostics. We should only accept
875 // attributes here, no types, etc.
876 if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
877 SourceLocation AtLoc = ConsumeToken(); // the "@"
878 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
879 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
880 Diag(Tok, diag::err_objc_unexpected_attr);
881 SkipUntil(tok::semi); // FIXME: better skip?
882 return DeclGroupPtrTy();
887 const char *PrevSpec = 0;
889 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
890 Diag(AtLoc, DiagID) << PrevSpec;
892 if (Tok.isObjCAtKeyword(tok::objc_protocol))
893 return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
895 return Actions.ConvertDeclToDeclGroup(
896 ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
899 // If the declspec consisted only of 'extern' and we have a string
900 // literal following it, this must be a C++ linkage specifier like
902 if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
903 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
904 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
905 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
906 return Actions.ConvertDeclToDeclGroup(TheDecl);
909 return ParseDeclGroup(DS, Declarator::FileContext, true);
912 Parser::DeclGroupPtrTy
913 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
915 AccessSpecifier AS) {
917 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
919 ParsingDeclSpec PDS(*this);
920 // Must temporarily exit the objective-c container scope for
921 // parsing c constructs and re-enter objc container scope
923 ObjCDeclContextSwitch ObjCDC(*this);
925 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
929 /// ParseFunctionDefinition - We parsed and verified that the specified
930 /// Declarator is well formed. If this is a K&R-style function, read the
931 /// parameters declaration-list, then start the compound-statement.
933 /// function-definition: [C99 6.9.1]
934 /// decl-specs declarator declaration-list[opt] compound-statement
935 /// [C90] function-definition: [C99 6.7.1] - implicit int result
936 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
937 /// [C++] function-definition: [C++ 8.4]
938 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
940 /// [C++] function-definition: [C++ 8.4]
941 /// decl-specifier-seq[opt] declarator function-try-block
943 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
944 const ParsedTemplateInfo &TemplateInfo,
945 LateParsedAttrList *LateParsedAttrs) {
946 // Poison the SEH identifiers so they are flagged as illegal in function bodies
947 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
948 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
950 // If this is C90 and the declspecs were completely missing, fudge in an
951 // implicit int. We do this here because this is the only place where
952 // declaration-specifiers are completely optional in the grammar.
953 if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
954 const char *PrevSpec;
956 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
957 D.getIdentifierLoc(),
959 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
962 // If this declaration was formed with a K&R-style identifier list for the
963 // arguments, parse declarations for all of the args next.
964 // int foo(a,b) int a; float b; {}
965 if (FTI.isKNRPrototype())
966 ParseKNRParamDeclarations(D);
968 // We should have either an opening brace or, in a C++ constructor,
969 // we may have a colon.
970 if (Tok.isNot(tok::l_brace) &&
971 (!getLangOpts().CPlusPlus ||
972 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
973 Tok.isNot(tok::equal)))) {
974 Diag(Tok, diag::err_expected_fn_body);
976 // Skip over garbage, until we get to '{'. Don't eat the '{'.
977 SkipUntil(tok::l_brace, true, true);
979 // If we didn't find the '{', bail out.
980 if (Tok.isNot(tok::l_brace))
984 // Check to make sure that any normal attributes are allowed to be on
985 // a definition. Late parsed attributes are checked at the end.
986 if (Tok.isNot(tok::equal)) {
987 AttributeList *DtorAttrs = D.getAttributes();
989 if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
990 Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
991 << DtorAttrs->getName()->getName();
993 DtorAttrs = DtorAttrs->getNext();
997 // In delayed template parsing mode, for function template we consume the
998 // tokens and store them for late parsing at the end of the translation unit.
999 if (getLangOpts().DelayedTemplateParsing &&
1000 Tok.isNot(tok::equal) &&
1001 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
1002 MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
1004 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1005 Scope *ParentScope = getCurScope()->getParent();
1007 D.setFunctionDefinitionKind(FDK_Definition);
1008 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1009 TemplateParameterLists);
1011 D.getMutableDeclSpec().abort();
1014 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
1016 FunctionDecl *FnD = 0;
1017 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
1018 FnD = FunTmpl->getTemplatedDecl();
1020 FnD = cast<FunctionDecl>(DP);
1021 Actions.CheckForFunctionRedefinition(FnD);
1023 LateParsedTemplateMap[FnD] = LPT;
1024 Actions.MarkAsLateParsedTemplate(FnD);
1025 LexTemplateFunctionForLateParsing(LPT->Toks);
1028 LexTemplateFunctionForLateParsing(Toks);
1032 else if (CurParsedObjCImpl &&
1033 !TemplateInfo.TemplateParams &&
1034 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1035 Tok.is(tok::colon)) &&
1036 Actions.CurContext->isTranslationUnit()) {
1037 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1038 Scope *ParentScope = getCurScope()->getParent();
1040 D.setFunctionDefinitionKind(FDK_Definition);
1041 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1042 MultiTemplateParamsArg());
1043 D.complete(FuncDecl);
1044 D.getMutableDeclSpec().abort();
1046 // Consume the tokens and store them for later parsing.
1047 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1048 CurParsedObjCImpl->HasCFunction = true;
1053 // Enter a scope for the function body.
1054 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1056 // Tell the actions module that we have entered a function definition with the
1057 // specified Declarator for the function.
1058 Decl *Res = TemplateInfo.TemplateParams?
1059 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1060 *TemplateInfo.TemplateParams, D)
1061 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1063 // Break out of the ParsingDeclarator context before we parse the body.
1066 // Break out of the ParsingDeclSpec context, too. This const_cast is
1067 // safe because we're always the sole owner.
1068 D.getMutableDeclSpec().abort();
1070 if (Tok.is(tok::equal)) {
1071 assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1074 Actions.ActOnFinishFunctionBody(Res, 0, false);
1076 bool Delete = false;
1077 SourceLocation KWLoc;
1078 if (Tok.is(tok::kw_delete)) {
1079 Diag(Tok, getLangOpts().CPlusPlus0x ?
1080 diag::warn_cxx98_compat_deleted_function :
1081 diag::ext_deleted_function);
1083 KWLoc = ConsumeToken();
1084 Actions.SetDeclDeleted(Res, KWLoc);
1086 } else if (Tok.is(tok::kw_default)) {
1087 Diag(Tok, getLangOpts().CPlusPlus0x ?
1088 diag::warn_cxx98_compat_defaulted_function :
1089 diag::ext_defaulted_function);
1091 KWLoc = ConsumeToken();
1092 Actions.SetDeclDefaulted(Res, KWLoc);
1094 llvm_unreachable("function definition after = not 'delete' or 'default'");
1097 if (Tok.is(tok::comma)) {
1098 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1100 SkipUntil(tok::semi);
1102 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1103 Delete ? "delete" : "default", tok::semi);
1109 if (Tok.is(tok::kw_try))
1110 return ParseFunctionTryBlock(Res, BodyScope);
1112 // If we have a colon, then we're probably parsing a C++
1113 // ctor-initializer.
1114 if (Tok.is(tok::colon)) {
1115 ParseConstructorInitializer(Res);
1117 // Recover from error.
1118 if (!Tok.is(tok::l_brace)) {
1120 Actions.ActOnFinishFunctionBody(Res, 0);
1124 Actions.ActOnDefaultCtorInitializers(Res);
1126 // Late attributes are parsed in the same scope as the function body.
1127 if (LateParsedAttrs)
1128 ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1130 return ParseFunctionStatementBody(Res, BodyScope);
1133 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1134 /// types for a function with a K&R-style identifier list for arguments.
1135 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1136 // We know that the top-level of this declarator is a function.
1137 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1139 // Enter function-declaration scope, limiting any declarators to the
1140 // function prototype scope, including parameter declarators.
1141 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
1143 // Read all the argument declarations.
1144 while (isDeclarationSpecifier()) {
1145 SourceLocation DSStart = Tok.getLocation();
1147 // Parse the common declaration-specifiers piece.
1148 DeclSpec DS(AttrFactory);
1149 ParseDeclarationSpecifiers(DS);
1151 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1152 // least one declarator'.
1153 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
1154 // the declarations though. It's trivial to ignore them, really hard to do
1155 // anything else with them.
1156 if (Tok.is(tok::semi)) {
1157 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1162 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1164 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1165 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1166 Diag(DS.getStorageClassSpecLoc(),
1167 diag::err_invalid_storage_class_in_func_decl);
1168 DS.ClearStorageClassSpecs();
1170 if (DS.isThreadSpecified()) {
1171 Diag(DS.getThreadSpecLoc(),
1172 diag::err_invalid_storage_class_in_func_decl);
1173 DS.ClearStorageClassSpecs();
1176 // Parse the first declarator attached to this declspec.
1177 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1178 ParseDeclarator(ParmDeclarator);
1180 // Handle the full declarator list.
1182 // If attributes are present, parse them.
1183 MaybeParseGNUAttributes(ParmDeclarator);
1185 // Ask the actions module to compute the type for this declarator.
1187 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1190 // A missing identifier has already been diagnosed.
1191 ParmDeclarator.getIdentifier()) {
1193 // Scan the argument list looking for the correct param to apply this
1195 for (unsigned i = 0; ; ++i) {
1196 // C99 6.9.1p6: those declarators shall declare only identifiers from
1197 // the identifier list.
1198 if (i == FTI.NumArgs) {
1199 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1200 << ParmDeclarator.getIdentifier();
1204 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1205 // Reject redefinitions of parameters.
1206 if (FTI.ArgInfo[i].Param) {
1207 Diag(ParmDeclarator.getIdentifierLoc(),
1208 diag::err_param_redefinition)
1209 << ParmDeclarator.getIdentifier();
1211 FTI.ArgInfo[i].Param = Param;
1218 // If we don't have a comma, it is either the end of the list (a ';') or
1219 // an error, bail out.
1220 if (Tok.isNot(tok::comma))
1223 ParmDeclarator.clear();
1225 // Consume the comma.
1226 ParmDeclarator.setCommaLoc(ConsumeToken());
1228 // Parse the next declarator.
1229 ParseDeclarator(ParmDeclarator);
1232 if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1233 // Skip to end of block or statement
1234 SkipUntil(tok::semi, true);
1235 if (Tok.is(tok::semi))
1240 // The actions module must verify that all arguments were declared.
1241 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1245 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1246 /// allowed to be a wide string, and is not subject to character translation.
1248 /// [GNU] asm-string-literal:
1251 Parser::ExprResult Parser::ParseAsmStringLiteral() {
1252 switch (Tok.getKind()) {
1253 case tok::string_literal:
1255 case tok::utf8_string_literal:
1256 case tok::utf16_string_literal:
1257 case tok::utf32_string_literal:
1258 case tok::wide_string_literal: {
1259 SourceLocation L = Tok.getLocation();
1260 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1261 << (Tok.getKind() == tok::wide_string_literal)
1262 << SourceRange(L, L);
1266 Diag(Tok, diag::err_expected_string_literal);
1270 return ParseStringLiteralExpression();
1275 /// [GNU] simple-asm-expr:
1276 /// 'asm' '(' asm-string-literal ')'
1278 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1279 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1280 SourceLocation Loc = ConsumeToken();
1282 if (Tok.is(tok::kw_volatile)) {
1283 // Remove from the end of 'asm' to the end of 'volatile'.
1284 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1285 PP.getLocForEndOfToken(Tok.getLocation()));
1287 Diag(Tok, diag::warn_file_asm_volatile)
1288 << FixItHint::CreateRemoval(RemovalRange);
1292 BalancedDelimiterTracker T(*this, tok::l_paren);
1293 if (T.consumeOpen()) {
1294 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1298 ExprResult Result(ParseAsmStringLiteral());
1300 if (Result.isInvalid()) {
1301 SkipUntil(tok::r_paren, true, true);
1303 *EndLoc = Tok.getLocation();
1306 // Close the paren and get the location of the end bracket
1309 *EndLoc = T.getCloseLocation();
1315 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1316 /// cleanup pool so that it gets destroyed when parsing the current top level
1317 /// declaration is finished.
1318 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1319 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1320 TemplateIdAnnotation *
1321 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1325 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1326 // Push the current token back into the token stream (or revert it if it is
1327 // cached) and use an annotation scope token for current token.
1328 if (PP.isBacktrackEnabled())
1329 PP.RevertCachedTokens(1);
1332 Tok.setKind(tok::annot_cxxscope);
1333 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1334 Tok.setAnnotationRange(SS.getRange());
1336 // In case the tokens were cached, have Preprocessor replace them
1337 // with the annotation token. We don't need to do this if we've
1338 // just reverted back to a prior state.
1339 if (IsNewAnnotation)
1340 PP.AnnotateCachedTokens(Tok);
1343 /// \brief Attempt to classify the name at the current token position. This may
1344 /// form a type, scope or primary expression annotation, or replace the token
1345 /// with a typo-corrected keyword. This is only appropriate when the current
1346 /// name must refer to an entity which has already been declared.
1348 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1349 /// and might possibly have a dependent nested name specifier.
1350 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1351 /// no typo correction will be performed.
1352 Parser::AnnotatedNameKind
1353 Parser::TryAnnotateName(bool IsAddressOfOperand,
1354 CorrectionCandidateCallback *CCC) {
1355 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1357 const bool EnteringContext = false;
1358 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1361 if (getLangOpts().CPlusPlus &&
1362 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1365 if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1366 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1367 !WasScopeAnnotation))
1369 return ANK_Unresolved;
1372 IdentifierInfo *Name = Tok.getIdentifierInfo();
1373 SourceLocation NameLoc = Tok.getLocation();
1375 // FIXME: Move the tentative declaration logic into ClassifyName so we can
1376 // typo-correct to tentatively-declared identifiers.
1377 if (isTentativelyDeclared(Name)) {
1378 // Identifier has been tentatively declared, and thus cannot be resolved as
1379 // an expression. Fall back to annotating it as a type.
1380 if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1381 !WasScopeAnnotation))
1383 return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1386 Token Next = NextToken();
1388 // Look up and classify the identifier. We don't perform any typo-correction
1389 // after a scope specifier, because in general we can't recover from typos
1390 // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1391 // back into scope specifier parsing).
1392 Sema::NameClassification Classification
1393 = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1394 IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1396 switch (Classification.getKind()) {
1397 case Sema::NC_Error:
1400 case Sema::NC_Keyword:
1401 // The identifier was typo-corrected to a keyword.
1402 Tok.setIdentifierInfo(Name);
1403 Tok.setKind(Name->getTokenID());
1404 PP.TypoCorrectToken(Tok);
1405 if (SS.isNotEmpty())
1406 AnnotateScopeToken(SS, !WasScopeAnnotation);
1407 // We've "annotated" this as a keyword.
1410 case Sema::NC_Unknown:
1411 // It's not something we know about. Leave it unannotated.
1415 Tok.setKind(tok::annot_typename);
1416 setTypeAnnotation(Tok, Classification.getType());
1417 Tok.setAnnotationEndLoc(NameLoc);
1418 if (SS.isNotEmpty())
1419 Tok.setLocation(SS.getBeginLoc());
1420 PP.AnnotateCachedTokens(Tok);
1423 case Sema::NC_Expression:
1424 Tok.setKind(tok::annot_primary_expr);
1425 setExprAnnotation(Tok, Classification.getExpression());
1426 Tok.setAnnotationEndLoc(NameLoc);
1427 if (SS.isNotEmpty())
1428 Tok.setLocation(SS.getBeginLoc());
1429 PP.AnnotateCachedTokens(Tok);
1432 case Sema::NC_TypeTemplate:
1433 if (Next.isNot(tok::less)) {
1434 // This may be a type template being used as a template template argument.
1435 if (SS.isNotEmpty())
1436 AnnotateScopeToken(SS, !WasScopeAnnotation);
1437 return ANK_TemplateName;
1440 case Sema::NC_FunctionTemplate: {
1441 // We have a type or function template followed by '<'.
1444 Id.setIdentifier(Name, NameLoc);
1445 if (AnnotateTemplateIdToken(
1446 TemplateTy::make(Classification.getTemplateName()),
1447 Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1452 case Sema::NC_NestedNameSpecifier:
1453 llvm_unreachable("already parsed nested name specifier");
1456 // Unable to classify the name, but maybe we can annotate a scope specifier.
1457 if (SS.isNotEmpty())
1458 AnnotateScopeToken(SS, !WasScopeAnnotation);
1459 return ANK_Unresolved;
1462 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1463 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1464 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1465 /// with a single annotation token representing the typename or C++ scope
1467 /// This simplifies handling of C++ scope specifiers and allows efficient
1468 /// backtracking without the need to re-parse and resolve nested-names and
1470 /// It will mainly be called when we expect to treat identifiers as typenames
1471 /// (if they are typenames). For example, in C we do not expect identifiers
1472 /// inside expressions to be treated as typenames so it will not be called
1473 /// for expressions in C.
1474 /// The benefit for C/ObjC is that a typename will be annotated and
1475 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1476 /// will not be called twice, once to check whether we have a declaration
1477 /// specifier, and another one to get the actual type inside
1478 /// ParseDeclarationSpecifiers).
1480 /// This returns true if an error occurred.
1482 /// Note that this routine emits an error if you call it with ::new or ::delete
1483 /// as the current tokens, so only call it in contexts where these are invalid.
1484 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1485 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1486 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1487 || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1488 && "Cannot be a type or scope token!");
1490 if (Tok.is(tok::kw_typename)) {
1491 // Parse a C++ typename-specifier, e.g., "typename T::type".
1493 // typename-specifier:
1494 // 'typename' '::' [opt] nested-name-specifier identifier
1495 // 'typename' '::' [opt] nested-name-specifier template [opt]
1496 // simple-template-id
1497 SourceLocation TypenameLoc = ConsumeToken();
1499 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1500 /*EnteringContext=*/false,
1501 0, /*IsTypename*/true))
1504 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1505 Tok.is(tok::annot_decltype)) {
1506 // Attempt to recover by skipping the invalid 'typename'
1507 if (Tok.is(tok::annot_decltype) ||
1508 (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1509 Tok.isAnnotation())) {
1510 unsigned DiagID = diag::err_expected_qualified_after_typename;
1511 // MS compatibility: MSVC permits using known types with typename.
1512 // e.g. "typedef typename T* pointer_type"
1513 if (getLangOpts().MicrosoftExt)
1514 DiagID = diag::warn_expected_qualified_after_typename;
1515 Diag(Tok.getLocation(), DiagID);
1520 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1525 if (Tok.is(tok::identifier)) {
1526 // FIXME: check whether the next token is '<', first!
1527 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1528 *Tok.getIdentifierInfo(),
1530 } else if (Tok.is(tok::annot_template_id)) {
1531 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1532 if (TemplateId->Kind == TNK_Function_template) {
1533 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1534 << Tok.getAnnotationRange();
1538 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1539 TemplateId->NumArgs);
1541 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1542 TemplateId->TemplateKWLoc,
1543 TemplateId->Template,
1544 TemplateId->TemplateNameLoc,
1545 TemplateId->LAngleLoc,
1547 TemplateId->RAngleLoc);
1549 Diag(Tok, diag::err_expected_type_name_after_typename)
1554 SourceLocation EndLoc = Tok.getLastLoc();
1555 Tok.setKind(tok::annot_typename);
1556 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1557 Tok.setAnnotationEndLoc(EndLoc);
1558 Tok.setLocation(TypenameLoc);
1559 PP.AnnotateCachedTokens(Tok);
1563 // Remembers whether the token was originally a scope annotation.
1564 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1567 if (getLangOpts().CPlusPlus)
1568 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1571 return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1572 SS, !WasScopeAnnotation);
1575 /// \brief Try to annotate a type or scope token, having already parsed an
1576 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1577 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1578 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1582 if (Tok.is(tok::identifier)) {
1583 IdentifierInfo *CorrectedII = 0;
1584 // Determine whether the identifier is a type name.
1585 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1586 Tok.getLocation(), getCurScope(),
1588 NextToken().is(tok::period),
1590 /*IsCtorOrDtorName=*/false,
1591 /*NonTrivialTypeSourceInfo*/true,
1592 NeedType ? &CorrectedII : NULL)) {
1593 // A FixIt was applied as a result of typo correction
1595 Tok.setIdentifierInfo(CorrectedII);
1596 // This is a typename. Replace the current token in-place with an
1597 // annotation type token.
1598 Tok.setKind(tok::annot_typename);
1599 setTypeAnnotation(Tok, Ty);
1600 Tok.setAnnotationEndLoc(Tok.getLocation());
1601 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1602 Tok.setLocation(SS.getBeginLoc());
1604 // In case the tokens were cached, have Preprocessor replace
1605 // them with the annotation token.
1606 PP.AnnotateCachedTokens(Tok);
1610 if (!getLangOpts().CPlusPlus) {
1611 // If we're in C, we can't have :: tokens at all (the lexer won't return
1612 // them). If the identifier is not a type, then it can't be scope either,
1617 // If this is a template-id, annotate with a template-id or type token.
1618 if (NextToken().is(tok::less)) {
1619 TemplateTy Template;
1620 UnqualifiedId TemplateName;
1621 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1622 bool MemberOfUnknownSpecialization;
1623 if (TemplateNameKind TNK
1624 = Actions.isTemplateName(getCurScope(), SS,
1625 /*hasTemplateKeyword=*/false, TemplateName,
1626 /*ObjectType=*/ ParsedType(),
1628 Template, MemberOfUnknownSpecialization)) {
1629 // Consume the identifier.
1631 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1633 // If an unrecoverable error occurred, we need to return true here,
1634 // because the token stream is in a damaged state. We may not return
1635 // a valid identifier.
1641 // The current token, which is either an identifier or a
1642 // template-id, is not part of the annotation. Fall through to
1643 // push that token back into the stream and complete the C++ scope
1644 // specifier annotation.
1647 if (Tok.is(tok::annot_template_id)) {
1648 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1649 if (TemplateId->Kind == TNK_Type_template) {
1650 // A template-id that refers to a type was parsed into a
1651 // template-id annotation in a context where we weren't allowed
1652 // to produce a type annotation token. Update the template-id
1653 // annotation token to a type annotation token now.
1654 AnnotateTemplateIdTokenAsType();
1662 // A C++ scope specifier that isn't followed by a typename.
1663 AnnotateScopeToken(SS, IsNewScope);
1667 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1668 /// annotates C++ scope specifiers and template-ids. This returns
1669 /// true if there was an error that could not be recovered from.
1671 /// Note that this routine emits an error if you call it with ::new or ::delete
1672 /// as the current tokens, so only call it in contexts where these are invalid.
1673 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1674 assert(getLangOpts().CPlusPlus &&
1675 "Call sites of this function should be guarded by checking for C++");
1676 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1677 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1678 Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1681 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1686 AnnotateScopeToken(SS, true);
1690 bool Parser::isTokenEqualOrEqualTypo() {
1691 tok::TokenKind Kind = Tok.getKind();
1695 case tok::ampequal: // &=
1696 case tok::starequal: // *=
1697 case tok::plusequal: // +=
1698 case tok::minusequal: // -=
1699 case tok::exclaimequal: // !=
1700 case tok::slashequal: // /=
1701 case tok::percentequal: // %=
1702 case tok::lessequal: // <=
1703 case tok::lesslessequal: // <<=
1704 case tok::greaterequal: // >=
1705 case tok::greatergreaterequal: // >>=
1706 case tok::caretequal: // ^=
1707 case tok::pipeequal: // |=
1708 case tok::equalequal: // ==
1709 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1710 << getTokenSimpleSpelling(Kind)
1711 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1717 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1718 assert(Tok.is(tok::code_completion));
1719 PrevTokLocation = Tok.getLocation();
1721 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1722 if (S->getFlags() & Scope::FnScope) {
1723 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1725 return PrevTokLocation;
1728 if (S->getFlags() & Scope::ClassScope) {
1729 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1731 return PrevTokLocation;
1735 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1737 return PrevTokLocation;
1740 // Anchor the Parser::FieldCallback vtable to this translation unit.
1741 // We use a spurious method instead of the destructor because
1742 // destroying FieldCallbacks can actually be slightly
1743 // performance-sensitive.
1744 void Parser::FieldCallback::_anchor() {
1747 // Code-completion pass-through functions
1749 void Parser::CodeCompleteDirective(bool InConditional) {
1750 Actions.CodeCompletePreprocessorDirective(InConditional);
1753 void Parser::CodeCompleteInConditionalExclusion() {
1754 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1757 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1758 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1761 void Parser::CodeCompletePreprocessorExpression() {
1762 Actions.CodeCompletePreprocessorExpression();
1765 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1766 MacroInfo *MacroInfo,
1767 unsigned ArgumentIndex) {
1768 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1772 void Parser::CodeCompleteNaturalLanguage() {
1773 Actions.CodeCompleteNaturalLanguage();
1776 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1777 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1778 "Expected '__if_exists' or '__if_not_exists'");
1779 Result.IsIfExists = Tok.is(tok::kw___if_exists);
1780 Result.KeywordLoc = ConsumeToken();
1782 BalancedDelimiterTracker T(*this, tok::l_paren);
1783 if (T.consumeOpen()) {
1784 Diag(Tok, diag::err_expected_lparen_after)
1785 << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1789 // Parse nested-name-specifier.
1790 ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1791 /*EnteringContext=*/false);
1793 // Check nested-name specifier.
1794 if (Result.SS.isInvalid()) {
1799 // Parse the unqualified-id.
1800 SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1801 if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1802 TemplateKWLoc, Result.Name)) {
1807 if (T.consumeClose())
1810 // Check if the symbol exists.
1811 switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1812 Result.IsIfExists, Result.SS,
1814 case Sema::IER_Exists:
1815 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1818 case Sema::IER_DoesNotExist:
1819 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1822 case Sema::IER_Dependent:
1823 Result.Behavior = IEB_Dependent;
1826 case Sema::IER_Error:
1833 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1834 IfExistsCondition Result;
1835 if (ParseMicrosoftIfExistsCondition(Result))
1838 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1839 if (Braces.consumeOpen()) {
1840 Diag(Tok, diag::err_expected_lbrace);
1844 switch (Result.Behavior) {
1846 // Parse declarations below.
1850 llvm_unreachable("Cannot have a dependent external declaration");
1857 // Parse the declarations.
1858 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1859 ParsedAttributesWithRange attrs(AttrFactory);
1860 MaybeParseCXX0XAttributes(attrs);
1861 MaybeParseMicrosoftAttributes(attrs);
1862 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1863 if (Result && !getCurScope()->getParent())
1864 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1866 Braces.consumeClose();
1869 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1870 assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&
1871 "Improper start to module import");
1872 SourceLocation ImportLoc = ConsumeToken();
1874 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1876 // Parse the module path.
1878 if (!Tok.is(tok::identifier)) {
1879 if (Tok.is(tok::code_completion)) {
1880 Actions.CodeCompleteModuleImport(ImportLoc, Path);
1881 ConsumeCodeCompletionToken();
1882 SkipUntil(tok::semi);
1883 return DeclGroupPtrTy();
1886 Diag(Tok, diag::err_module_expected_ident);
1887 SkipUntil(tok::semi);
1888 return DeclGroupPtrTy();
1891 // Record this part of the module path.
1892 Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1895 if (Tok.is(tok::period)) {
1903 DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1904 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1905 if (Import.isInvalid())
1906 return DeclGroupPtrTy();
1908 return Actions.ConvertDeclToDeclGroup(Import.get());
1911 bool BalancedDelimiterTracker::diagnoseOverflow() {
1912 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1913 P.SkipUntil(tok::eof);
1917 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1919 tok::TokenKind SkipToToc ) {
1920 LOpen = P.Tok.getLocation();
1921 if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1924 if (getDepth() < MaxDepth)
1927 return diagnoseOverflow();
1930 bool BalancedDelimiterTracker::diagnoseMissingClose() {
1931 assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1933 const char *LHSName = "unknown";
1936 default: llvm_unreachable("Unexpected balanced token");
1937 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1938 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1939 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1942 P.Diag(LOpen, diag::note_matching) << LHSName;
1943 if (P.SkipUntil(Close, /*StopAtSemi*/ true, /*DontConsume*/ true))
1944 LClose = P.ConsumeAnyToken();
1948 void BalancedDelimiterTracker::skipToEnd() {
1949 P.SkipUntil(Close, false);