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;
26 Parser::Parser(Preprocessor &pp, Sema &actions)
27 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
28 GreaterThanIsOperator(true), ColonIsSacred(false),
29 InMessageExpression(false), TemplateParameterDepth(0) {
30 Tok.setKind(tok::eof);
33 ParenCount = BracketCount = BraceCount = 0;
36 // Add #pragma handlers. These are removed and destroyed in the
38 AlignHandler.reset(new PragmaAlignHandler(actions));
39 PP.AddPragmaHandler(AlignHandler.get());
41 GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler(actions));
42 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
44 OptionsHandler.reset(new PragmaOptionsHandler(actions));
45 PP.AddPragmaHandler(OptionsHandler.get());
47 PackHandler.reset(new PragmaPackHandler(actions));
48 PP.AddPragmaHandler(PackHandler.get());
50 MSStructHandler.reset(new PragmaMSStructHandler(actions));
51 PP.AddPragmaHandler(MSStructHandler.get());
53 UnusedHandler.reset(new PragmaUnusedHandler(actions, *this));
54 PP.AddPragmaHandler(UnusedHandler.get());
56 WeakHandler.reset(new PragmaWeakHandler(actions));
57 PP.AddPragmaHandler(WeakHandler.get());
59 FPContractHandler.reset(new PragmaFPContractHandler(actions, *this));
60 PP.AddPragmaHandler("STDC", FPContractHandler.get());
62 if (getLang().OpenCL) {
63 OpenCLExtensionHandler.reset(
64 new PragmaOpenCLExtensionHandler(actions, *this));
65 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
67 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
70 PP.setCodeCompletionHandler(*this);
73 /// If a crash happens while the parser is active, print out a line indicating
74 /// what the current token is.
75 void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
76 const Token &Tok = P.getCurToken();
77 if (Tok.is(tok::eof)) {
78 OS << "<eof> parser at end of file\n";
82 if (Tok.getLocation().isInvalid()) {
83 OS << "<unknown> parser at unknown location\n";
87 const Preprocessor &PP = P.getPreprocessor();
88 Tok.getLocation().print(OS, PP.getSourceManager());
89 if (Tok.isAnnotation())
90 OS << ": at annotation token \n";
92 OS << ": current parser token '" << PP.getSpelling(Tok) << "'\n";
96 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
97 return Diags.Report(Loc, DiagID);
100 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
101 return Diag(Tok.getLocation(), DiagID);
104 /// \brief Emits a diagnostic suggesting parentheses surrounding a
107 /// \param Loc The location where we'll emit the diagnostic.
108 /// \param Loc The kind of diagnostic to emit.
109 /// \param ParenRange Source range enclosing code that should be parenthesized.
110 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
111 SourceRange ParenRange) {
112 SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
113 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
114 // We can't display the parentheses, so just dig the
115 // warning/error and return.
121 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
122 << FixItHint::CreateInsertion(EndLoc, ")");
125 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
126 switch (ExpectedTok) {
127 case tok::semi: return Tok.is(tok::colon); // : for ;
128 default: return false;
132 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
133 /// input. If so, it is consumed and false is returned.
135 /// If the input is malformed, this emits the specified diagnostic. Next, if
136 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is
138 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
139 const char *Msg, tok::TokenKind SkipToTok) {
140 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
145 // Detect common single-character typos and resume.
146 if (IsCommonTypo(ExpectedTok, Tok)) {
147 SourceLocation Loc = Tok.getLocation();
150 << FixItHint::CreateReplacement(SourceRange(Loc),
151 getTokenSimpleSpelling(ExpectedTok));
154 // Pretend there wasn't a problem.
158 const char *Spelling = 0;
159 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
160 if (EndLoc.isValid() &&
161 (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
162 // Show what code to insert to fix this problem.
165 << FixItHint::CreateInsertion(EndLoc, Spelling);
167 Diag(Tok, DiagID) << Msg;
169 if (SkipToTok != tok::unknown)
170 SkipUntil(SkipToTok);
174 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
175 if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
180 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
181 NextToken().is(tok::semi)) {
182 Diag(Tok, diag::err_extraneous_token_before_semi)
183 << PP.getSpelling(Tok)
184 << FixItHint::CreateRemoval(Tok.getLocation());
185 ConsumeAnyToken(); // The ')' or ']'.
186 ConsumeToken(); // The ';'.
190 return ExpectAndConsume(tok::semi, DiagID);
193 //===----------------------------------------------------------------------===//
195 //===----------------------------------------------------------------------===//
197 /// SkipUntil - Read tokens until we get to the specified token, then consume
198 /// it (unless DontConsume is true). Because we cannot guarantee that the
199 /// token will ever occur, this skips to the next token, or to some likely
200 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';'
203 /// If SkipUntil finds the specified token, it returns true, otherwise it
205 bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
206 bool StopAtSemi, bool DontConsume,
207 bool StopAtCodeCompletion) {
208 // We always want this function to skip at least one token if the first token
209 // isn't T and if not at EOF.
210 bool isFirstTokenSkipped = true;
212 // If we found one of the tokens, stop and return true.
213 for (unsigned i = 0; i != NumToks; ++i) {
214 if (Tok.is(Toks[i])) {
216 // Noop, don't consume the token.
224 switch (Tok.getKind()) {
226 // Ran out of tokens.
229 case tok::code_completion:
230 if (!StopAtCodeCompletion)
235 // Recursively skip properly-nested parens.
237 SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
240 // Recursively skip properly-nested square brackets.
242 SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
245 // Recursively skip properly-nested braces.
247 SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
250 // Okay, we found a ']' or '}' or ')', which we think should be balanced.
251 // Since the user wasn't looking for this token (if they were, it would
252 // already be handled), this isn't balanced. If there is a LHS token at a
253 // higher level, we will assume that this matches the unbalanced token
254 // and return it. Otherwise, this is a spurious RHS token, which we skip.
256 if (ParenCount && !isFirstTokenSkipped)
257 return false; // Matches something.
261 if (BracketCount && !isFirstTokenSkipped)
262 return false; // Matches something.
266 if (BraceCount && !isFirstTokenSkipped)
267 return false; // Matches something.
271 case tok::string_literal:
272 case tok::wide_string_literal:
273 case tok::utf8_string_literal:
274 case tok::utf16_string_literal:
275 case tok::utf32_string_literal:
276 ConsumeStringToken();
291 isFirstTokenSkipped = false;
295 //===----------------------------------------------------------------------===//
296 // Scope manipulation
297 //===----------------------------------------------------------------------===//
299 /// EnterScope - Start a new scope.
300 void Parser::EnterScope(unsigned ScopeFlags) {
301 if (NumCachedScopes) {
302 Scope *N = ScopeCache[--NumCachedScopes];
303 N->Init(getCurScope(), ScopeFlags);
304 Actions.CurScope = N;
306 Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
310 /// ExitScope - Pop a scope off the scope stack.
311 void Parser::ExitScope() {
312 assert(getCurScope() && "Scope imbalance!");
314 // Inform the actions module that this scope is going away if there are any
316 if (!getCurScope()->decl_empty())
317 Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
319 Scope *OldScope = getCurScope();
320 Actions.CurScope = OldScope->getParent();
322 if (NumCachedScopes == ScopeCacheSize)
325 ScopeCache[NumCachedScopes++] = OldScope;
328 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
329 /// this object does nothing.
330 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
332 : CurScope(ManageFlags ? Self->getCurScope() : 0) {
334 OldFlags = CurScope->getFlags();
335 CurScope->setFlags(ScopeFlags);
339 /// Restore the flags for the current scope to what they were before this
340 /// object overrode them.
341 Parser::ParseScopeFlags::~ParseScopeFlags() {
343 CurScope->setFlags(OldFlags);
347 //===----------------------------------------------------------------------===//
348 // C99 6.9: External Definitions.
349 //===----------------------------------------------------------------------===//
352 // If we still have scopes active, delete the scope tree.
353 delete getCurScope();
354 Actions.CurScope = 0;
356 // Free the scope cache.
357 for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
358 delete ScopeCache[i];
360 // Free LateParsedTemplatedFunction nodes.
361 for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
362 it != LateParsedTemplateMap.end(); ++it)
365 // Remove the pragma handlers we installed.
366 PP.RemovePragmaHandler(AlignHandler.get());
367 AlignHandler.reset();
368 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
369 GCCVisibilityHandler.reset();
370 PP.RemovePragmaHandler(OptionsHandler.get());
371 OptionsHandler.reset();
372 PP.RemovePragmaHandler(PackHandler.get());
374 PP.RemovePragmaHandler(MSStructHandler.get());
375 MSStructHandler.reset();
376 PP.RemovePragmaHandler(UnusedHandler.get());
377 UnusedHandler.reset();
378 PP.RemovePragmaHandler(WeakHandler.get());
381 if (getLang().OpenCL) {
382 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
383 OpenCLExtensionHandler.reset();
384 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
387 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
388 FPContractHandler.reset();
389 PP.clearCodeCompletionHandler();
392 /// Initialize - Warm up the parser.
394 void Parser::Initialize() {
395 // Create the translation unit scope. Install it as the current scope.
396 assert(getCurScope() == 0 && "A scope is already active?");
397 EnterScope(Scope::DeclScope);
398 Actions.ActOnTranslationUnitScope(getCurScope());
400 // Prime the lexer look-ahead.
403 if (Tok.is(tok::eof) &&
404 !getLang().CPlusPlus) // Empty source file is an extension in C
405 Diag(Tok, diag::ext_empty_source_file);
407 // Initialization for Objective-C context sensitive keywords recognition.
408 // Referenced in Parser::ParseObjCTypeQualifierList.
409 if (getLang().ObjC1) {
410 ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
411 ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
412 ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
413 ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
414 ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
415 ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
418 Ident_instancetype = 0;
422 Ident_super = &PP.getIdentifierTable().get("super");
424 if (getLang().AltiVec) {
425 Ident_vector = &PP.getIdentifierTable().get("vector");
426 Ident_pixel = &PP.getIdentifierTable().get("pixel");
429 Ident_introduced = 0;
430 Ident_deprecated = 0;
432 Ident_unavailable = 0;
434 Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
435 Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
436 Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
438 if(getLang().Borland) {
439 Ident__exception_info = PP.getIdentifierInfo("_exception_info");
440 Ident___exception_info = PP.getIdentifierInfo("__exception_info");
441 Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");
442 Ident__exception_code = PP.getIdentifierInfo("_exception_code");
443 Ident___exception_code = PP.getIdentifierInfo("__exception_code");
444 Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");
445 Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");
446 Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
447 Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");
449 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
450 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
451 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
452 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
453 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
454 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
455 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
456 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
457 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
461 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
462 /// action tells us to. This returns true if the EOF was encountered.
463 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
464 DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool);
466 while (Tok.is(tok::annot_pragma_unused))
467 HandlePragmaUnused();
469 Result = DeclGroupPtrTy();
470 if (Tok.is(tok::eof)) {
471 // Late template parsing can begin.
472 if (getLang().DelayedTemplateParsing)
473 Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
475 Actions.ActOnEndOfTranslationUnit();
479 ParsedAttributesWithRange attrs(AttrFactory);
480 MaybeParseCXX0XAttributes(attrs);
481 MaybeParseMicrosoftAttributes(attrs);
483 Result = ParseExternalDeclaration(attrs);
487 /// ParseTranslationUnit:
488 /// translation-unit: [C99 6.9]
489 /// external-declaration
490 /// translation-unit external-declaration
491 void Parser::ParseTranslationUnit() {
495 while (!ParseTopLevelDecl(Res))
499 assert(getCurScope() == 0 && "Scope imbalance!");
502 /// ParseExternalDeclaration:
504 /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
505 /// function-definition
507 /// [C++0x] empty-declaration
508 /// [GNU] asm-definition
509 /// [GNU] __extension__ external-declaration
510 /// [OBJC] objc-class-definition
511 /// [OBJC] objc-class-declaration
512 /// [OBJC] objc-alias-declaration
513 /// [OBJC] objc-protocol-definition
514 /// [OBJC] objc-method-definition
516 /// [C++] linkage-specification
517 /// [GNU] asm-definition:
518 /// simple-asm-expr ';'
520 /// [C++0x] empty-declaration:
523 /// [C++0x/GNU] 'extern' 'template' declaration
524 Parser::DeclGroupPtrTy
525 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
526 ParsingDeclSpec *DS) {
527 DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool);
528 ParenBraceBracketBalancer BalancerRAIIObj(*this);
530 if (PP.isCodeCompletionReached()) {
532 return DeclGroupPtrTy();
535 Decl *SingleDecl = 0;
536 switch (Tok.getKind()) {
538 if (!getLang().CPlusPlus0x)
539 Diag(Tok, diag::ext_top_level_semi)
540 << FixItHint::CreateRemoval(Tok.getLocation());
543 // TODO: Invoke action for top-level semicolon.
544 return DeclGroupPtrTy();
546 Diag(Tok, diag::err_expected_external_declaration);
548 return DeclGroupPtrTy();
550 Diag(Tok, diag::err_expected_external_declaration);
551 return DeclGroupPtrTy();
552 case tok::kw___extension__: {
553 // __extension__ silences extension warnings in the subexpression.
554 ExtensionRAIIObject O(Diags); // Use RAII to do this.
556 return ParseExternalDeclaration(attrs);
559 ProhibitAttributes(attrs);
561 SourceLocation StartLoc = Tok.getLocation();
562 SourceLocation EndLoc;
563 ExprResult Result(ParseSimpleAsm(&EndLoc));
565 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
566 "top-level asm block");
568 if (Result.isInvalid())
569 return DeclGroupPtrTy();
570 SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
574 return ParseObjCAtDirectives();
578 if (!getLang().ObjC1) {
579 Diag(Tok, diag::err_expected_external_declaration);
581 return DeclGroupPtrTy();
583 SingleDecl = ParseObjCMethodDefinition();
585 case tok::code_completion:
586 Actions.CodeCompleteOrdinaryName(getCurScope(),
587 ObjCImpDecl? Sema::PCC_ObjCImplementation
588 : Sema::PCC_Namespace);
590 return DeclGroupPtrTy();
592 case tok::kw_namespace:
593 case tok::kw_typedef:
594 case tok::kw_template:
595 case tok::kw_export: // As in 'export template'
596 case tok::kw_static_assert:
597 case tok::kw__Static_assert:
598 // A function definition cannot start with a these keywords.
600 SourceLocation DeclEnd;
601 StmtVector Stmts(Actions);
602 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
606 // Parse (then ignore) 'static' prior to a template instantiation. This is
607 // a GCC extension that we intentionally do not support.
608 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
609 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
611 SourceLocation DeclEnd;
612 StmtVector Stmts(Actions);
613 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
618 if (getLang().CPlusPlus) {
619 tok::TokenKind NextKind = NextToken().getKind();
621 // Inline namespaces. Allowed as an extension even in C++03.
622 if (NextKind == tok::kw_namespace) {
623 SourceLocation DeclEnd;
624 StmtVector Stmts(Actions);
625 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
628 // Parse (then ignore) 'inline' prior to a template instantiation. This is
629 // a GCC extension that we intentionally do not support.
630 if (NextKind == tok::kw_template) {
631 Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
633 SourceLocation DeclEnd;
634 StmtVector Stmts(Actions);
635 return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
641 if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
643 SourceLocation ExternLoc = ConsumeToken();
644 SourceLocation TemplateLoc = ConsumeToken();
645 SourceLocation DeclEnd;
646 return Actions.ConvertDeclToDeclGroup(
647 ParseExplicitInstantiation(ExternLoc, TemplateLoc, DeclEnd));
649 // FIXME: Detect C++ linkage specifications here?
652 case tok::kw___if_exists:
653 case tok::kw___if_not_exists:
654 ParseMicrosoftIfExistsExternalDeclaration();
655 return DeclGroupPtrTy();
657 case tok::kw___import_module__:
658 return ParseModuleImport();
662 // We can't tell whether this is a function-definition or declaration yet.
664 DS->takeAttributesFrom(attrs);
665 return ParseDeclarationOrFunctionDefinition(*DS);
667 return ParseDeclarationOrFunctionDefinition(attrs);
671 // This routine returns a DeclGroup, if the thing we parsed only contains a
672 // single decl, convert it now.
673 return Actions.ConvertDeclToDeclGroup(SingleDecl);
676 /// \brief Determine whether the current token, if it occurs after a
677 /// declarator, continues a declaration or declaration list.
678 bool Parser::isDeclarationAfterDeclarator() {
679 // Check for '= delete' or '= default'
680 if (getLang().CPlusPlus && Tok.is(tok::equal)) {
681 const Token &KW = NextToken();
682 if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
686 return Tok.is(tok::equal) || // int X()= -> not a function def
687 Tok.is(tok::comma) || // int X(), -> not a function def
688 Tok.is(tok::semi) || // int X(); -> not a function def
689 Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def
690 Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def
691 (getLang().CPlusPlus &&
692 Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]
695 /// \brief Determine whether the current token, if it occurs after a
696 /// declarator, indicates the start of a function definition.
697 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
698 assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
699 if (Tok.is(tok::l_brace)) // int X() {}
702 // Handle K&R C argument lists: int X(f) int f; {}
703 if (!getLang().CPlusPlus &&
704 Declarator.getFunctionTypeInfo().isKNRPrototype())
705 return isDeclarationSpecifier();
707 if (getLang().CPlusPlus && Tok.is(tok::equal)) {
708 const Token &KW = NextToken();
709 return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
712 return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)
713 Tok.is(tok::kw_try); // X() try { ... }
716 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
717 /// a declaration. We can't tell which we have until we read up to the
718 /// compound-statement in function-definition. TemplateParams, if
719 /// non-NULL, provides the template parameters when we're parsing a
720 /// C++ template-declaration.
722 /// function-definition: [C99 6.9.1]
723 /// decl-specs declarator declaration-list[opt] compound-statement
724 /// [C90] function-definition: [C99 6.7.1] - implicit int result
725 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
727 /// declaration: [C99 6.7]
728 /// declaration-specifiers init-declarator-list[opt] ';'
729 /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]
730 /// [OMP] threadprivate-directive [TODO]
732 Parser::DeclGroupPtrTy
733 Parser::ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
734 AccessSpecifier AS) {
735 // Parse the common declaration-specifiers piece.
736 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
738 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
739 // declaration-specifiers init-declarator-list[opt] ';'
740 if (Tok.is(tok::semi)) {
742 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
743 DS.complete(TheDecl);
744 return Actions.ConvertDeclToDeclGroup(TheDecl);
747 // ObjC2 allows prefix attributes on class interfaces and protocols.
748 // FIXME: This still needs better diagnostics. We should only accept
749 // attributes here, no types, etc.
750 if (getLang().ObjC2 && Tok.is(tok::at)) {
751 SourceLocation AtLoc = ConsumeToken(); // the "@"
752 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
753 !Tok.isObjCAtKeyword(tok::objc_protocol)) {
754 Diag(Tok, diag::err_objc_unexpected_attr);
755 SkipUntil(tok::semi); // FIXME: better skip?
756 return DeclGroupPtrTy();
761 const char *PrevSpec = 0;
763 if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
764 Diag(AtLoc, DiagID) << PrevSpec;
767 if (Tok.isObjCAtKeyword(tok::objc_protocol))
768 TheDecl = ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
770 TheDecl = ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes());
771 return Actions.ConvertDeclToDeclGroup(TheDecl);
774 // If the declspec consisted only of 'extern' and we have a string
775 // literal following it, this must be a C++ linkage specifier like
777 if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
778 DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
779 DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
780 Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
781 return Actions.ConvertDeclToDeclGroup(TheDecl);
784 return ParseDeclGroup(DS, Declarator::FileContext, true);
787 Parser::DeclGroupPtrTy
788 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs,
789 AccessSpecifier AS) {
790 ParsingDeclSpec DS(*this);
791 DS.takeAttributesFrom(attrs);
792 // Must temporarily exit the objective-c container scope for
793 // parsing c constructs and re-enter objc container scope
795 ObjCDeclContextSwitch ObjCDC(*this);
797 return ParseDeclarationOrFunctionDefinition(DS, AS);
800 /// ParseFunctionDefinition - We parsed and verified that the specified
801 /// Declarator is well formed. If this is a K&R-style function, read the
802 /// parameters declaration-list, then start the compound-statement.
804 /// function-definition: [C99 6.9.1]
805 /// decl-specs declarator declaration-list[opt] compound-statement
806 /// [C90] function-definition: [C99 6.7.1] - implicit int result
807 /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement
808 /// [C++] function-definition: [C++ 8.4]
809 /// decl-specifier-seq[opt] declarator ctor-initializer[opt]
811 /// [C++] function-definition: [C++ 8.4]
812 /// decl-specifier-seq[opt] declarator function-try-block
814 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
815 const ParsedTemplateInfo &TemplateInfo) {
816 // Poison the SEH identifiers so they are flagged as illegal in function bodies
817 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
818 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
820 // If this is C90 and the declspecs were completely missing, fudge in an
821 // implicit int. We do this here because this is the only place where
822 // declaration-specifiers are completely optional in the grammar.
823 if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
824 const char *PrevSpec;
826 D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
827 D.getIdentifierLoc(),
829 D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
832 // If this declaration was formed with a K&R-style identifier list for the
833 // arguments, parse declarations for all of the args next.
834 // int foo(a,b) int a; float b; {}
835 if (FTI.isKNRPrototype())
836 ParseKNRParamDeclarations(D);
839 // We should have either an opening brace or, in a C++ constructor,
840 // we may have a colon.
841 if (Tok.isNot(tok::l_brace) &&
842 (!getLang().CPlusPlus ||
843 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
844 Tok.isNot(tok::equal)))) {
845 Diag(Tok, diag::err_expected_fn_body);
847 // Skip over garbage, until we get to '{'. Don't eat the '{'.
848 SkipUntil(tok::l_brace, true, true);
850 // If we didn't find the '{', bail out.
851 if (Tok.isNot(tok::l_brace))
855 // In delayed template parsing mode, for function template we consume the
856 // tokens and store them for late parsing at the end of the translation unit.
857 if (getLang().DelayedTemplateParsing &&
858 TemplateInfo.Kind == ParsedTemplateInfo::Template) {
859 MultiTemplateParamsArg TemplateParameterLists(Actions,
860 TemplateInfo.TemplateParams->data(),
861 TemplateInfo.TemplateParams->size());
863 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
864 Scope *ParentScope = getCurScope()->getParent();
866 D.setFunctionDefinition(true);
867 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
868 move(TemplateParameterLists));
870 D.getMutableDeclSpec().abort();
873 LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(this, DP);
875 FunctionDecl *FnD = 0;
876 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
877 FnD = FunTmpl->getTemplatedDecl();
879 FnD = cast<FunctionDecl>(DP);
880 Actions.CheckForFunctionRedefinition(FnD);
882 LateParsedTemplateMap[FnD] = LPT;
883 Actions.MarkAsLateParsedTemplate(FnD);
884 LexTemplateFunctionForLateParsing(LPT->Toks);
887 LexTemplateFunctionForLateParsing(Toks);
892 // Enter a scope for the function body.
893 ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
895 // Tell the actions module that we have entered a function definition with the
896 // specified Declarator for the function.
897 Decl *Res = TemplateInfo.TemplateParams?
898 Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
899 MultiTemplateParamsArg(Actions,
900 TemplateInfo.TemplateParams->data(),
901 TemplateInfo.TemplateParams->size()),
903 : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
905 // Break out of the ParsingDeclarator context before we parse the body.
908 // Break out of the ParsingDeclSpec context, too. This const_cast is
909 // safe because we're always the sole owner.
910 D.getMutableDeclSpec().abort();
912 if (Tok.is(tok::equal)) {
913 assert(getLang().CPlusPlus && "Only C++ function definitions have '='");
916 Actions.ActOnFinishFunctionBody(Res, 0, false);
919 SourceLocation KWLoc;
920 if (Tok.is(tok::kw_delete)) {
921 if (!getLang().CPlusPlus0x)
922 Diag(Tok, diag::warn_deleted_function_accepted_as_extension);
924 KWLoc = ConsumeToken();
925 Actions.SetDeclDeleted(Res, KWLoc);
927 } else if (Tok.is(tok::kw_default)) {
928 if (!getLang().CPlusPlus0x)
929 Diag(Tok, diag::warn_defaulted_function_accepted_as_extension);
931 KWLoc = ConsumeToken();
932 Actions.SetDeclDefaulted(Res, KWLoc);
934 llvm_unreachable("function definition after = not 'delete' or 'default'");
937 if (Tok.is(tok::comma)) {
938 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
940 SkipUntil(tok::semi);
942 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
943 Delete ? "delete" : "default", tok::semi);
949 if (Tok.is(tok::kw_try))
950 return ParseFunctionTryBlock(Res, BodyScope);
952 // If we have a colon, then we're probably parsing a C++
954 if (Tok.is(tok::colon)) {
955 ParseConstructorInitializer(Res);
957 // Recover from error.
958 if (!Tok.is(tok::l_brace)) {
960 Actions.ActOnFinishFunctionBody(Res, 0);
964 Actions.ActOnDefaultCtorInitializers(Res);
966 return ParseFunctionStatementBody(Res, BodyScope);
969 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
970 /// types for a function with a K&R-style identifier list for arguments.
971 void Parser::ParseKNRParamDeclarations(Declarator &D) {
972 // We know that the top-level of this declarator is a function.
973 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
975 // Enter function-declaration scope, limiting any declarators to the
976 // function prototype scope, including parameter declarators.
977 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope);
979 // Read all the argument declarations.
980 while (isDeclarationSpecifier()) {
981 SourceLocation DSStart = Tok.getLocation();
983 // Parse the common declaration-specifiers piece.
984 DeclSpec DS(AttrFactory);
985 ParseDeclarationSpecifiers(DS);
987 // C99 6.9.1p6: 'each declaration in the declaration list shall have at
988 // least one declarator'.
989 // NOTE: GCC just makes this an ext-warn. It's not clear what it does with
990 // the declarations though. It's trivial to ignore them, really hard to do
991 // anything else with them.
992 if (Tok.is(tok::semi)) {
993 Diag(DSStart, diag::err_declaration_does_not_declare_param);
998 // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1000 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1001 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1002 Diag(DS.getStorageClassSpecLoc(),
1003 diag::err_invalid_storage_class_in_func_decl);
1004 DS.ClearStorageClassSpecs();
1006 if (DS.isThreadSpecified()) {
1007 Diag(DS.getThreadSpecLoc(),
1008 diag::err_invalid_storage_class_in_func_decl);
1009 DS.ClearStorageClassSpecs();
1012 // Parse the first declarator attached to this declspec.
1013 Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1014 ParseDeclarator(ParmDeclarator);
1016 // Handle the full declarator list.
1018 // If attributes are present, parse them.
1019 MaybeParseGNUAttributes(ParmDeclarator);
1021 // Ask the actions module to compute the type for this declarator.
1023 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1026 // A missing identifier has already been diagnosed.
1027 ParmDeclarator.getIdentifier()) {
1029 // Scan the argument list looking for the correct param to apply this
1031 for (unsigned i = 0; ; ++i) {
1032 // C99 6.9.1p6: those declarators shall declare only identifiers from
1033 // the identifier list.
1034 if (i == FTI.NumArgs) {
1035 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1036 << ParmDeclarator.getIdentifier();
1040 if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1041 // Reject redefinitions of parameters.
1042 if (FTI.ArgInfo[i].Param) {
1043 Diag(ParmDeclarator.getIdentifierLoc(),
1044 diag::err_param_redefinition)
1045 << ParmDeclarator.getIdentifier();
1047 FTI.ArgInfo[i].Param = Param;
1054 // If we don't have a comma, it is either the end of the list (a ';') or
1055 // an error, bail out.
1056 if (Tok.isNot(tok::comma))
1059 // Consume the comma.
1062 // Parse the next declarator.
1063 ParmDeclarator.clear();
1064 ParseDeclarator(ParmDeclarator);
1067 if (Tok.is(tok::semi)) {
1070 Diag(Tok, diag::err_parse_error);
1071 // Skip to end of block or statement
1072 SkipUntil(tok::semi, true);
1073 if (Tok.is(tok::semi))
1078 // The actions module must verify that all arguments were declared.
1079 Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1083 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1084 /// allowed to be a wide string, and is not subject to character translation.
1086 /// [GNU] asm-string-literal:
1089 Parser::ExprResult Parser::ParseAsmStringLiteral() {
1090 if (!isTokenStringLiteral()) {
1091 Diag(Tok, diag::err_expected_string_literal);
1095 ExprResult Res(ParseStringLiteralExpression());
1096 if (Res.isInvalid()) return move(Res);
1098 // TODO: Diagnose: wide string literal in 'asm'
1105 /// [GNU] simple-asm-expr:
1106 /// 'asm' '(' asm-string-literal ')'
1108 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1109 assert(Tok.is(tok::kw_asm) && "Not an asm!");
1110 SourceLocation Loc = ConsumeToken();
1112 if (Tok.is(tok::kw_volatile)) {
1113 // Remove from the end of 'asm' to the end of 'volatile'.
1114 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1115 PP.getLocForEndOfToken(Tok.getLocation()));
1117 Diag(Tok, diag::warn_file_asm_volatile)
1118 << FixItHint::CreateRemoval(RemovalRange);
1122 BalancedDelimiterTracker T(*this, tok::l_paren);
1123 if (T.consumeOpen()) {
1124 Diag(Tok, diag::err_expected_lparen_after) << "asm";
1128 ExprResult Result(ParseAsmStringLiteral());
1130 if (Result.isInvalid()) {
1131 SkipUntil(tok::r_paren, true, true);
1133 *EndLoc = Tok.getLocation();
1136 // Close the paren and get the location of the end bracket
1139 *EndLoc = T.getCloseLocation();
1142 return move(Result);
1145 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1146 /// cleanup pool so that it gets destroyed when parsing the current top level
1147 /// declaration is finished.
1148 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1149 assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1150 TemplateIdAnnotation *
1151 Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1152 TopLevelDeclCleanupPool.delayMemberFunc< TemplateIdAnnotation,
1153 &TemplateIdAnnotation::Destroy>(Id);
1157 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1158 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1159 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1160 /// with a single annotation token representing the typename or C++ scope
1162 /// This simplifies handling of C++ scope specifiers and allows efficient
1163 /// backtracking without the need to re-parse and resolve nested-names and
1165 /// It will mainly be called when we expect to treat identifiers as typenames
1166 /// (if they are typenames). For example, in C we do not expect identifiers
1167 /// inside expressions to be treated as typenames so it will not be called
1168 /// for expressions in C.
1169 /// The benefit for C/ObjC is that a typename will be annotated and
1170 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1171 /// will not be called twice, once to check whether we have a declaration
1172 /// specifier, and another one to get the actual type inside
1173 /// ParseDeclarationSpecifiers).
1175 /// This returns true if an error occurred.
1177 /// Note that this routine emits an error if you call it with ::new or ::delete
1178 /// as the current tokens, so only call it in contexts where these are invalid.
1179 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1180 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1181 || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) &&
1182 "Cannot be a type or scope token!");
1184 if (Tok.is(tok::kw_typename)) {
1185 // Parse a C++ typename-specifier, e.g., "typename T::type".
1187 // typename-specifier:
1188 // 'typename' '::' [opt] nested-name-specifier identifier
1189 // 'typename' '::' [opt] nested-name-specifier template [opt]
1190 // simple-template-id
1191 SourceLocation TypenameLoc = ConsumeToken();
1193 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), false,
1194 0, /*IsTypename*/true))
1197 if (getLang().MicrosoftExt)
1198 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1200 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1205 if (Tok.is(tok::identifier)) {
1206 // FIXME: check whether the next token is '<', first!
1207 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1208 *Tok.getIdentifierInfo(),
1210 } else if (Tok.is(tok::annot_template_id)) {
1211 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1212 if (TemplateId->Kind == TNK_Function_template) {
1213 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1214 << Tok.getAnnotationRange();
1218 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
1219 TemplateId->getTemplateArgs(),
1220 TemplateId->NumArgs);
1222 Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1223 /*FIXME:*/SourceLocation(),
1224 TemplateId->Template,
1225 TemplateId->TemplateNameLoc,
1226 TemplateId->LAngleLoc,
1228 TemplateId->RAngleLoc);
1230 Diag(Tok, diag::err_expected_type_name_after_typename)
1235 SourceLocation EndLoc = Tok.getLastLoc();
1236 Tok.setKind(tok::annot_typename);
1237 setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1238 Tok.setAnnotationEndLoc(EndLoc);
1239 Tok.setLocation(TypenameLoc);
1240 PP.AnnotateCachedTokens(Tok);
1244 // Remembers whether the token was originally a scope annotation.
1245 bool wasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1248 if (getLang().CPlusPlus)
1249 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1252 if (Tok.is(tok::identifier)) {
1253 IdentifierInfo *CorrectedII = 0;
1254 // Determine whether the identifier is a type name.
1255 if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1256 Tok.getLocation(), getCurScope(),
1258 NextToken().is(tok::period),
1260 /*NonTrivialTypeSourceInfo*/true,
1261 NeedType ? &CorrectedII : NULL)) {
1262 // A FixIt was applied as a result of typo correction
1264 Tok.setIdentifierInfo(CorrectedII);
1265 // This is a typename. Replace the current token in-place with an
1266 // annotation type token.
1267 Tok.setKind(tok::annot_typename);
1268 setTypeAnnotation(Tok, Ty);
1269 Tok.setAnnotationEndLoc(Tok.getLocation());
1270 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1271 Tok.setLocation(SS.getBeginLoc());
1273 // In case the tokens were cached, have Preprocessor replace
1274 // them with the annotation token.
1275 PP.AnnotateCachedTokens(Tok);
1279 if (!getLang().CPlusPlus) {
1280 // If we're in C, we can't have :: tokens at all (the lexer won't return
1281 // them). If the identifier is not a type, then it can't be scope either,
1286 // If this is a template-id, annotate with a template-id or type token.
1287 if (NextToken().is(tok::less)) {
1288 TemplateTy Template;
1289 UnqualifiedId TemplateName;
1290 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1291 bool MemberOfUnknownSpecialization;
1292 if (TemplateNameKind TNK
1293 = Actions.isTemplateName(getCurScope(), SS,
1294 /*hasTemplateKeyword=*/false, TemplateName,
1295 /*ObjectType=*/ ParsedType(),
1297 Template, MemberOfUnknownSpecialization)) {
1298 // Consume the identifier.
1300 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName)) {
1301 // If an unrecoverable error occurred, we need to return true here,
1302 // because the token stream is in a damaged state. We may not return
1303 // a valid identifier.
1309 // The current token, which is either an identifier or a
1310 // template-id, is not part of the annotation. Fall through to
1311 // push that token back into the stream and complete the C++ scope
1312 // specifier annotation.
1315 if (Tok.is(tok::annot_template_id)) {
1316 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1317 if (TemplateId->Kind == TNK_Type_template) {
1318 // A template-id that refers to a type was parsed into a
1319 // template-id annotation in a context where we weren't allowed
1320 // to produce a type annotation token. Update the template-id
1321 // annotation token to a type annotation token now.
1322 AnnotateTemplateIdTokenAsType();
1330 // A C++ scope specifier that isn't followed by a typename.
1331 // Push the current token back into the token stream (or revert it if it is
1332 // cached) and use an annotation scope token for current token.
1333 if (PP.isBacktrackEnabled())
1334 PP.RevertCachedTokens(1);
1337 Tok.setKind(tok::annot_cxxscope);
1338 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1339 Tok.setAnnotationRange(SS.getRange());
1341 // In case the tokens were cached, have Preprocessor replace them
1342 // with the annotation token. We don't need to do this if we've
1343 // just reverted back to the state we were in before being called.
1344 if (!wasScopeAnnotation)
1345 PP.AnnotateCachedTokens(Tok);
1349 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1350 /// annotates C++ scope specifiers and template-ids. This returns
1351 /// true if the token was annotated or there was an error that could not be
1354 /// Note that this routine emits an error if you call it with ::new or ::delete
1355 /// as the current tokens, so only call it in contexts where these are invalid.
1356 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1357 assert(getLang().CPlusPlus &&
1358 "Call sites of this function should be guarded by checking for C++");
1359 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1360 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)))&&
1361 "Cannot be a type or scope token!");
1364 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1369 // Push the current token back into the token stream (or revert it if it is
1370 // cached) and use an annotation scope token for current token.
1371 if (PP.isBacktrackEnabled())
1372 PP.RevertCachedTokens(1);
1375 Tok.setKind(tok::annot_cxxscope);
1376 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1377 Tok.setAnnotationRange(SS.getRange());
1379 // In case the tokens were cached, have Preprocessor replace them with the
1380 // annotation token.
1381 PP.AnnotateCachedTokens(Tok);
1385 bool Parser::isTokenEqualOrMistypedEqualEqual(unsigned DiagID) {
1386 if (Tok.is(tok::equalequal)) {
1387 // We have '==' in a context that we would expect a '='.
1388 // The user probably made a typo, intending to type '='. Emit diagnostic,
1389 // fixit hint to turn '==' -> '=' and continue as if the user typed '='.
1391 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
1392 getTokenSimpleSpelling(tok::equal));
1396 return Tok.is(tok::equal);
1399 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1400 assert(Tok.is(tok::code_completion));
1401 PrevTokLocation = Tok.getLocation();
1403 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1404 if (S->getFlags() & Scope::FnScope) {
1405 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1407 return PrevTokLocation;
1410 if (S->getFlags() & Scope::ClassScope) {
1411 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1413 return PrevTokLocation;
1417 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1419 return PrevTokLocation;
1422 // Anchor the Parser::FieldCallback vtable to this translation unit.
1423 // We use a spurious method instead of the destructor because
1424 // destroying FieldCallbacks can actually be slightly
1425 // performance-sensitive.
1426 void Parser::FieldCallback::_anchor() {
1429 // Code-completion pass-through functions
1431 void Parser::CodeCompleteDirective(bool InConditional) {
1432 Actions.CodeCompletePreprocessorDirective(InConditional);
1435 void Parser::CodeCompleteInConditionalExclusion() {
1436 Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1439 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1440 Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1443 void Parser::CodeCompletePreprocessorExpression() {
1444 Actions.CodeCompletePreprocessorExpression();
1447 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1448 MacroInfo *MacroInfo,
1449 unsigned ArgumentIndex) {
1450 Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1454 void Parser::CodeCompleteNaturalLanguage() {
1455 Actions.CodeCompleteNaturalLanguage();
1458 bool Parser::ParseMicrosoftIfExistsCondition(bool& Result) {
1459 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1460 "Expected '__if_exists' or '__if_not_exists'");
1461 Token Condition = Tok;
1462 SourceLocation IfExistsLoc = ConsumeToken();
1464 BalancedDelimiterTracker T(*this, tok::l_paren);
1465 if (T.consumeOpen()) {
1466 Diag(Tok, diag::err_expected_lparen_after) << IfExistsLoc;
1467 SkipUntil(tok::semi);
1471 // Parse nested-name-specifier.
1473 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
1475 // Check nested-name specifier.
1476 if (SS.isInvalid()) {
1477 SkipUntil(tok::semi);
1481 // Parse the unqualified-id.
1483 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) {
1484 SkipUntil(tok::semi);
1489 if (T.getCloseLocation().isInvalid())
1492 // Check if the symbol exists.
1493 bool Exist = Actions.CheckMicrosoftIfExistsSymbol(SS, Name);
1495 Result = ((Condition.is(tok::kw___if_exists) && Exist) ||
1496 (Condition.is(tok::kw___if_not_exists) && !Exist));
1501 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1503 if (ParseMicrosoftIfExistsCondition(Result))
1506 if (Tok.isNot(tok::l_brace)) {
1507 Diag(Tok, diag::err_expected_lbrace);
1512 // Condition is false skip all inside the {}.
1514 SkipUntil(tok::r_brace, false);
1518 // Condition is true, parse the declaration.
1519 while (Tok.isNot(tok::r_brace)) {
1520 ParsedAttributesWithRange attrs(AttrFactory);
1521 MaybeParseCXX0XAttributes(attrs);
1522 MaybeParseMicrosoftAttributes(attrs);
1523 DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1524 if (Result && !getCurScope()->getParent())
1525 Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1528 if (Tok.isNot(tok::r_brace)) {
1529 Diag(Tok, diag::err_expected_rbrace);
1535 Parser::DeclGroupPtrTy Parser::ParseModuleImport() {
1536 assert(Tok.is(tok::kw___import_module__) &&
1537 "Improper start to module import");
1538 SourceLocation ImportLoc = ConsumeToken();
1540 // Parse the module name.
1541 if (!Tok.is(tok::identifier)) {
1542 Diag(Tok, diag::err_module_expected_ident);
1543 SkipUntil(tok::semi);
1544 return DeclGroupPtrTy();
1547 IdentifierInfo &ModuleName = *Tok.getIdentifierInfo();
1548 SourceLocation ModuleNameLoc = ConsumeToken();
1549 DeclResult Import = Actions.ActOnModuleImport(ImportLoc, ModuleName, ModuleNameLoc);
1550 ExpectAndConsumeSemi(diag::err_module_expected_semi);
1551 if (Import.isInvalid())
1552 return DeclGroupPtrTy();
1554 return Actions.ConvertDeclToDeclGroup(Import.get());
1557 bool Parser::BalancedDelimiterTracker::consumeOpen() {
1558 // Try to consume the token we are holding
1559 if (P.Tok.is(Kind)) {
1560 P.QuantityTracker.push(Kind);
1562 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
1563 LOpen = P.ConsumeAnyToken();
1566 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1567 P.SkipUntil(tok::eof);
1573 bool Parser::BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1575 tok::TokenKind SkipToToc ) {
1576 LOpen = P.Tok.getLocation();
1577 if (!P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc)) {
1578 P.QuantityTracker.push(Kind);
1580 if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
1583 P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
1584 P.SkipUntil(tok::eof);
1590 bool Parser::BalancedDelimiterTracker::consumeClose() {
1591 if (P.Tok.is(Close)) {
1592 LClose = P.ConsumeAnyToken();
1594 P.QuantityTracker.pop(Kind);
1599 const char *LHSName = "unknown";
1600 diag::kind DID = diag::err_parse_error;
1603 case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1604 case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1605 case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1606 case tok::greater: LHSName = "<"; DID = diag::err_expected_greater; break;
1607 case tok::greatergreatergreater:
1608 LHSName = "<<<"; DID = diag::err_expected_ggg; break;
1611 P.Diag(LOpen, diag::note_matching) << LHSName;
1612 if (P.SkipUntil(Close))
1613 LClose = P.Tok.getLocation();