1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
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 Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/PrettyDeclStackTrace.h"
20 #include "RAIIObjectsForParser.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringSwitch.h"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // C99 6.7: Declarations.
28 //===----------------------------------------------------------------------===//
31 /// type-name: [C99 6.7.6]
32 /// specifier-qualifier-list abstract-declarator[opt]
34 /// Called type-id in C++.
35 TypeResult Parser::ParseTypeName(SourceRange *Range,
36 Declarator::TheContext Context,
39 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
41 // Parse the common declaration-specifiers piece.
42 DeclSpec DS(AttrFactory);
43 ParseSpecifierQualifierList(DS, AS, DSC);
45 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
47 // Parse the abstract-declarator, if present.
48 Declarator DeclaratorInfo(DS, Context);
49 ParseDeclarator(DeclaratorInfo);
51 *Range = DeclaratorInfo.getSourceRange();
53 if (DeclaratorInfo.isInvalidType())
56 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
60 /// isAttributeLateParsed - Return true if the attribute has arguments that
61 /// require late parsing.
62 static bool isAttributeLateParsed(const IdentifierInfo &II) {
63 return llvm::StringSwitch<bool>(II.getName())
64 #include "clang/Parse/AttrLateParsed.inc"
69 /// ParseGNUAttributes - Parse a non-empty attributes list.
73 /// attributes attribute
76 /// '__attribute__' '(' '(' attribute-list ')' ')'
78 /// [GNU] attribute-list:
80 /// attribute_list ',' attrib
85 /// attrib-name '(' identifier ')'
86 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
87 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
89 /// [GNU] attrib-name:
95 /// FIXME: The GCC grammar/code for this construct implies we need two
96 /// token lookahead. Comment from gcc: "If they start with an identifier
97 /// which is followed by a comma or close parenthesis, then the arguments
98 /// start with that identifier; otherwise they are an expression list."
100 /// GCC does not require the ',' between attribs in an attribute-list.
102 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
103 /// any attributes that don't work (based on my limited testing). Most
104 /// attributes are very simple in practice. Until we find a bug, I don't see
105 /// a pressing need to implement the 2 token lookahead.
107 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
108 SourceLocation *endLoc,
109 LateParsedAttrList *LateAttrs) {
110 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
112 while (Tok.is(tok::kw___attribute)) {
114 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
116 SkipUntil(tok::r_paren, true); // skip until ) or ;
119 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
120 SkipUntil(tok::r_paren, true); // skip until ) or ;
123 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
124 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
125 Tok.is(tok::comma)) {
126 if (Tok.is(tok::comma)) {
127 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
131 // we have an identifier or declaration specifier (const, int, etc.)
132 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
133 SourceLocation AttrNameLoc = ConsumeToken();
135 if (Tok.is(tok::l_paren)) {
136 // handle "parameterized" attributes
137 if (LateAttrs && isAttributeLateParsed(*AttrName)) {
138 LateParsedAttribute *LA =
139 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
140 LateAttrs->push_back(LA);
142 // Attributes in a class are parsed at the end of the class, along
143 // with other late-parsed declarations.
144 if (!ClassStack.empty())
145 getCurrentClass().LateParsedDeclarations.push_back(LA);
147 // consume everything up to and including the matching right parens
148 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
152 Eof.setLocation(Tok.getLocation());
153 LA->Toks.push_back(Eof);
155 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc);
158 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
159 0, SourceLocation(), 0, 0);
162 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
163 SkipUntil(tok::r_paren, false);
164 SourceLocation Loc = Tok.getLocation();
165 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
166 SkipUntil(tok::r_paren, false);
174 /// Parse the arguments to a parameterized GNU attribute
175 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
176 SourceLocation AttrNameLoc,
177 ParsedAttributes &Attrs,
178 SourceLocation *EndLoc) {
180 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
182 // Availability attributes have their own grammar.
183 if (AttrName->isStr("availability")) {
184 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
187 // Thread safety attributes fit into the FIXME case above, so we
188 // just parse the arguments as a list of expressions
189 if (IsThreadSafetyAttribute(AttrName->getName())) {
190 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
194 ConsumeParen(); // ignore the left paren loc for now
196 IdentifierInfo *ParmName = 0;
197 SourceLocation ParmLoc;
198 bool BuiltinType = false;
200 switch (Tok.getKind()) {
202 case tok::kw_wchar_t:
203 case tok::kw_char16_t:
204 case tok::kw_char32_t:
209 case tok::kw___int64:
210 case tok::kw___int128:
212 case tok::kw_unsigned:
217 // __attribute__(( vec_type_hint(char) ))
218 // FIXME: Don't just discard the builtin type token.
223 case tok::identifier:
224 ParmName = Tok.getIdentifierInfo();
225 ParmLoc = ConsumeToken();
232 ExprVector ArgExprs(Actions);
235 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
237 if (ParmLoc.isValid())
240 // Parse the non-empty comma-separated list of expressions.
242 ExprResult ArgExpr(ParseAssignmentExpression());
243 if (ArgExpr.isInvalid()) {
244 SkipUntil(tok::r_paren);
247 ArgExprs.push_back(ArgExpr.release());
248 if (Tok.isNot(tok::comma))
250 ConsumeToken(); // Eat the comma, move to the next argument
253 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
254 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
256 while (Tok.is(tok::identifier)) {
258 if (Tok.is(tok::greater))
260 if (Tok.is(tok::comma)) {
265 if (Tok.isNot(tok::greater))
266 Diag(Tok, diag::err_iboutletcollection_with_protocol);
267 SkipUntil(tok::r_paren, false, true); // skip until ')'
271 SourceLocation RParen = Tok.getLocation();
272 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
273 AttributeList *attr =
274 Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc,
275 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
276 if (BuiltinType && attr->getKind() == AttributeList::AT_iboutletcollection)
277 Diag(Tok, diag::err_iboutletcollection_builtintype);
282 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
284 /// [MS] decl-specifier:
285 /// __declspec ( extended-decl-modifier-seq )
287 /// [MS] extended-decl-modifier-seq:
288 /// extended-decl-modifier[opt]
289 /// extended-decl-modifier extended-decl-modifier-seq
291 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
292 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
295 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
297 SkipUntil(tok::r_paren, true); // skip until ) or ;
301 while (Tok.getIdentifierInfo()) {
302 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
303 SourceLocation AttrNameLoc = ConsumeToken();
305 // FIXME: Remove this when we have proper __declspec(property()) support.
306 // Just skip everything inside property().
307 if (AttrName->getName() == "property") {
309 SkipUntil(tok::r_paren);
311 if (Tok.is(tok::l_paren)) {
313 // FIXME: This doesn't parse __declspec(property(get=get_func_name))
315 ExprResult ArgExpr(ParseAssignmentExpression());
316 if (!ArgExpr.isInvalid()) {
317 Expr *ExprList = ArgExpr.take();
318 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
319 SourceLocation(), &ExprList, 1, true);
321 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
322 SkipUntil(tok::r_paren, false);
324 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
325 0, SourceLocation(), 0, 0, true);
328 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
329 SkipUntil(tok::r_paren, false);
333 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
334 // Treat these like attributes
335 // FIXME: Allow Sema to distinguish between these and real attributes!
336 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
337 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
338 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
339 Tok.is(tok::kw___ptr32) ||
340 Tok.is(tok::kw___unaligned)) {
341 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
342 SourceLocation AttrNameLoc = ConsumeToken();
343 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
344 Tok.is(tok::kw___ptr32))
345 // FIXME: Support these properly!
347 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
348 SourceLocation(), 0, 0, true);
352 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
353 // Treat these like attributes
354 while (Tok.is(tok::kw___pascal)) {
355 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
356 SourceLocation AttrNameLoc = ConsumeToken();
357 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
358 SourceLocation(), 0, 0, true);
362 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
363 // Treat these like attributes
364 while (Tok.is(tok::kw___kernel)) {
365 SourceLocation AttrNameLoc = ConsumeToken();
366 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
367 AttrNameLoc, 0, AttrNameLoc, 0,
368 SourceLocation(), 0, 0, false);
372 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
373 SourceLocation Loc = Tok.getLocation();
374 switch(Tok.getKind()) {
375 // OpenCL qualifiers:
376 case tok::kw___private:
377 case tok::kw_private:
378 DS.getAttributes().addNewInteger(
379 Actions.getASTContext(),
380 PP.getIdentifierInfo("address_space"), Loc, 0);
383 case tok::kw___global:
384 DS.getAttributes().addNewInteger(
385 Actions.getASTContext(),
386 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
389 case tok::kw___local:
390 DS.getAttributes().addNewInteger(
391 Actions.getASTContext(),
392 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
395 case tok::kw___constant:
396 DS.getAttributes().addNewInteger(
397 Actions.getASTContext(),
398 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
401 case tok::kw___read_only:
402 DS.getAttributes().addNewInteger(
403 Actions.getASTContext(),
404 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
407 case tok::kw___write_only:
408 DS.getAttributes().addNewInteger(
409 Actions.getASTContext(),
410 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
413 case tok::kw___read_write:
414 DS.getAttributes().addNewInteger(
415 Actions.getASTContext(),
416 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
422 /// \brief Parse a version number.
426 /// simple-integer ',' simple-integer
427 /// simple-integer ',' simple-integer ',' simple-integer
428 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
429 Range = Tok.getLocation();
431 if (!Tok.is(tok::numeric_constant)) {
432 Diag(Tok, diag::err_expected_version);
433 SkipUntil(tok::comma, tok::r_paren, true, true, true);
434 return VersionTuple();
437 // Parse the major (and possibly minor and subminor) versions, which
438 // are stored in the numeric constant. We utilize a quirk of the
439 // lexer, which is that it handles something like 1.2.3 as a single
440 // numeric constant, rather than two separate tokens.
441 SmallString<512> Buffer;
442 Buffer.resize(Tok.getLength()+1);
443 const char *ThisTokBegin = &Buffer[0];
445 // Get the spelling of the token, which eliminates trigraphs, etc.
446 bool Invalid = false;
447 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
449 return VersionTuple();
451 // Parse the major version.
452 unsigned AfterMajor = 0;
454 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
455 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
459 if (AfterMajor == 0) {
460 Diag(Tok, diag::err_expected_version);
461 SkipUntil(tok::comma, tok::r_paren, true, true, true);
462 return VersionTuple();
465 if (AfterMajor == ActualLength) {
468 // We only had a single version component.
470 Diag(Tok, diag::err_zero_version);
471 return VersionTuple();
474 return VersionTuple(Major);
477 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
478 Diag(Tok, diag::err_expected_version);
479 SkipUntil(tok::comma, tok::r_paren, true, true, true);
480 return VersionTuple();
483 // Parse the minor version.
484 unsigned AfterMinor = AfterMajor + 1;
486 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
487 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
491 if (AfterMinor == ActualLength) {
494 // We had major.minor.
495 if (Major == 0 && Minor == 0) {
496 Diag(Tok, diag::err_zero_version);
497 return VersionTuple();
500 return VersionTuple(Major, Minor);
503 // If what follows is not a '.', we have a problem.
504 if (ThisTokBegin[AfterMinor] != '.') {
505 Diag(Tok, diag::err_expected_version);
506 SkipUntil(tok::comma, tok::r_paren, true, true, true);
507 return VersionTuple();
510 // Parse the subminor version.
511 unsigned AfterSubminor = AfterMinor + 1;
512 unsigned Subminor = 0;
513 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
514 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
518 if (AfterSubminor != ActualLength) {
519 Diag(Tok, diag::err_expected_version);
520 SkipUntil(tok::comma, tok::r_paren, true, true, true);
521 return VersionTuple();
524 return VersionTuple(Major, Minor, Subminor);
527 /// \brief Parse the contents of the "availability" attribute.
529 /// availability-attribute:
530 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
535 /// version-arg-list:
537 /// version-arg ',' version-arg-list
540 /// 'introduced' '=' version
541 /// 'deprecated' '=' version
542 /// 'obsoleted' = version
545 /// 'message' '=' <string>
546 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
547 SourceLocation AvailabilityLoc,
548 ParsedAttributes &attrs,
549 SourceLocation *endLoc) {
550 SourceLocation PlatformLoc;
551 IdentifierInfo *Platform = 0;
553 enum { Introduced, Deprecated, Obsoleted, Unknown };
554 AvailabilityChange Changes[Unknown];
555 ExprResult MessageExpr;
558 BalancedDelimiterTracker T(*this, tok::l_paren);
559 if (T.consumeOpen()) {
560 Diag(Tok, diag::err_expected_lparen);
564 // Parse the platform name,
565 if (Tok.isNot(tok::identifier)) {
566 Diag(Tok, diag::err_availability_expected_platform);
567 SkipUntil(tok::r_paren);
570 Platform = Tok.getIdentifierInfo();
571 PlatformLoc = ConsumeToken();
573 // Parse the ',' following the platform name.
574 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
577 // If we haven't grabbed the pointers for the identifiers
578 // "introduced", "deprecated", and "obsoleted", do so now.
579 if (!Ident_introduced) {
580 Ident_introduced = PP.getIdentifierInfo("introduced");
581 Ident_deprecated = PP.getIdentifierInfo("deprecated");
582 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
583 Ident_unavailable = PP.getIdentifierInfo("unavailable");
584 Ident_message = PP.getIdentifierInfo("message");
587 // Parse the set of introductions/deprecations/removals.
588 SourceLocation UnavailableLoc;
590 if (Tok.isNot(tok::identifier)) {
591 Diag(Tok, diag::err_availability_expected_change);
592 SkipUntil(tok::r_paren);
595 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
596 SourceLocation KeywordLoc = ConsumeToken();
598 if (Keyword == Ident_unavailable) {
599 if (UnavailableLoc.isValid()) {
600 Diag(KeywordLoc, diag::err_availability_redundant)
601 << Keyword << SourceRange(UnavailableLoc);
603 UnavailableLoc = KeywordLoc;
605 if (Tok.isNot(tok::comma))
612 if (Tok.isNot(tok::equal)) {
613 Diag(Tok, diag::err_expected_equal_after)
615 SkipUntil(tok::r_paren);
619 if (Keyword == Ident_message) {
620 if (!isTokenStringLiteral()) {
621 Diag(Tok, diag::err_expected_string_literal);
622 SkipUntil(tok::r_paren);
625 MessageExpr = ParseStringLiteralExpression();
629 SourceRange VersionRange;
630 VersionTuple Version = ParseVersionTuple(VersionRange);
632 if (Version.empty()) {
633 SkipUntil(tok::r_paren);
638 if (Keyword == Ident_introduced)
640 else if (Keyword == Ident_deprecated)
642 else if (Keyword == Ident_obsoleted)
647 if (Index < Unknown) {
648 if (!Changes[Index].KeywordLoc.isInvalid()) {
649 Diag(KeywordLoc, diag::err_availability_redundant)
651 << SourceRange(Changes[Index].KeywordLoc,
652 Changes[Index].VersionRange.getEnd());
655 Changes[Index].KeywordLoc = KeywordLoc;
656 Changes[Index].Version = Version;
657 Changes[Index].VersionRange = VersionRange;
659 Diag(KeywordLoc, diag::err_availability_unknown_change)
660 << Keyword << VersionRange;
663 if (Tok.isNot(tok::comma))
670 if (T.consumeClose())
674 *endLoc = T.getCloseLocation();
676 // The 'unavailable' availability cannot be combined with any other
677 // availability changes. Make sure that hasn't happened.
678 if (UnavailableLoc.isValid()) {
679 bool Complained = false;
680 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
681 if (Changes[Index].KeywordLoc.isValid()) {
683 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
684 << SourceRange(Changes[Index].KeywordLoc,
685 Changes[Index].VersionRange.getEnd());
689 // Clear out the availability.
690 Changes[Index] = AvailabilityChange();
695 // Record this attribute
696 attrs.addNew(&Availability,
697 SourceRange(AvailabilityLoc, T.getCloseLocation()),
699 Platform, PlatformLoc,
703 UnavailableLoc, MessageExpr.take(),
708 // Late Parsed Attributes:
709 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
711 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
713 void Parser::LateParsedClass::ParseLexedAttributes() {
714 Self->ParseLexedAttributes(*Class);
717 void Parser::LateParsedAttribute::ParseLexedAttributes() {
718 Self->ParseLexedAttribute(*this, true, false);
721 /// Wrapper class which calls ParseLexedAttribute, after setting up the
722 /// scope appropriately.
723 void Parser::ParseLexedAttributes(ParsingClass &Class) {
724 // Deal with templates
725 // FIXME: Test cases to make sure this does the right thing for templates.
726 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
727 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
729 if (HasTemplateScope)
730 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
732 // Set or update the scope flags.
733 bool AlreadyHasClassScope = Class.TopLevelClass;
734 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
735 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
736 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
738 // Enter the scope of nested classes
739 if (!AlreadyHasClassScope)
740 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
741 Class.TagOrTemplate);
743 // Allow 'this' within late-parsed attributes.
744 Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate,
747 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
748 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
752 if (!AlreadyHasClassScope)
753 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
754 Class.TagOrTemplate);
758 /// \brief Parse all attributes in LAs, and attach them to Decl D.
759 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
760 bool EnterScope, bool OnDefinition) {
761 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
763 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
770 /// \brief Finish parsing an attribute for which parsing was delayed.
771 /// This will be called at the end of parsing a class declaration
772 /// for each LateParsedAttribute. We consume the saved tokens and
773 /// create an attribute with the arguments filled in. We add this
774 /// to the Attribute list for the decl.
775 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
776 bool EnterScope, bool OnDefinition) {
777 // Save the current token position.
778 SourceLocation OrigLoc = Tok.getLocation();
780 // Append the current token at the end of the new token stream so that it
782 LA.Toks.push_back(Tok);
783 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
784 // Consume the previously pushed token.
787 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
788 Diag(Tok, diag::warn_attribute_on_function_definition)
789 << LA.AttrName.getName();
792 ParsedAttributes Attrs(AttrFactory);
793 SourceLocation endLoc;
795 if (LA.Decls.size() == 1) {
796 Decl *D = LA.Decls[0];
798 // If the Decl is templatized, add template parameters to scope.
799 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
800 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
801 if (HasTemplateScope)
802 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
804 // If the Decl is on a function, add function parameters to the scope.
805 bool HasFunctionScope = EnterScope && D->isFunctionOrFunctionTemplate();
806 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionScope);
807 if (HasFunctionScope)
808 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
810 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
812 if (HasFunctionScope) {
813 Actions.ActOnExitFunctionContext();
814 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
816 if (HasTemplateScope) {
819 } else if (LA.Decls.size() > 0) {
820 // If there are multiple decls, then the decl cannot be within the
822 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
824 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
827 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
828 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
831 if (Tok.getLocation() != OrigLoc) {
832 // Due to a parsing error, we either went over the cached tokens or
833 // there are still cached tokens left, so we skip the leftover tokens.
834 // Since this is an uncommon situation that should be avoided, use the
835 // expensive isBeforeInTranslationUnit call.
836 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
838 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
843 /// \brief Wrapper around a case statement checking if AttrName is
844 /// one of the thread safety attributes
845 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
846 return llvm::StringSwitch<bool>(AttrName)
847 .Case("guarded_by", true)
848 .Case("guarded_var", true)
849 .Case("pt_guarded_by", true)
850 .Case("pt_guarded_var", true)
851 .Case("lockable", true)
852 .Case("scoped_lockable", true)
853 .Case("no_thread_safety_analysis", true)
854 .Case("acquired_after", true)
855 .Case("acquired_before", true)
856 .Case("exclusive_lock_function", true)
857 .Case("shared_lock_function", true)
858 .Case("exclusive_trylock_function", true)
859 .Case("shared_trylock_function", true)
860 .Case("unlock_function", true)
861 .Case("lock_returned", true)
862 .Case("locks_excluded", true)
863 .Case("exclusive_locks_required", true)
864 .Case("shared_locks_required", true)
868 /// \brief Parse the contents of thread safety attributes. These
869 /// should always be parsed as an expression list.
871 /// We need to special case the parsing due to the fact that if the first token
872 /// of the first argument is an identifier, the main parse loop will store
873 /// that token as a "parameter" and the rest of
874 /// the arguments will be added to a list of "arguments". However,
875 /// subsequent tokens in the first argument are lost. We instead parse each
876 /// argument as an expression and add all arguments to the list of "arguments".
877 /// In future, we will take advantage of this special case to also
878 /// deal with some argument scoping issues here (for example, referring to a
879 /// function parameter in the attribute on that function).
880 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
881 SourceLocation AttrNameLoc,
882 ParsedAttributes &Attrs,
883 SourceLocation *EndLoc) {
884 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
886 BalancedDelimiterTracker T(*this, tok::l_paren);
889 ExprVector ArgExprs(Actions);
890 bool ArgExprsOk = true;
892 // now parse the list of expressions
893 while (Tok.isNot(tok::r_paren)) {
894 ExprResult ArgExpr(ParseAssignmentExpression());
895 if (ArgExpr.isInvalid()) {
900 ArgExprs.push_back(ArgExpr.release());
902 if (Tok.isNot(tok::comma))
904 ConsumeToken(); // Eat the comma, move to the next argument
907 if (ArgExprsOk && !T.consumeClose()) {
908 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
909 ArgExprs.take(), ArgExprs.size());
912 *EndLoc = T.getCloseLocation();
915 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
916 /// of a C++11 attribute-specifier in a location where an attribute is not
917 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
920 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
921 /// this doesn't appear to actually be an attribute-specifier, and the caller
922 /// should try to parse it.
923 bool Parser::DiagnoseProhibitedCXX11Attribute() {
924 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
926 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
927 case CAK_NotAttributeSpecifier:
928 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
931 case CAK_InvalidAttributeSpecifier:
932 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
935 case CAK_AttributeSpecifier:
936 // Parse and discard the attributes.
937 SourceLocation BeginLoc = ConsumeBracket();
939 SkipUntil(tok::r_square, /*StopAtSemi*/ false);
940 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
941 SourceLocation EndLoc = ConsumeBracket();
942 Diag(BeginLoc, diag::err_attributes_not_allowed)
943 << SourceRange(BeginLoc, EndLoc);
946 llvm_unreachable("All cases handled above.");
949 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
950 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
954 /// ParseDeclaration - Parse a full 'declaration', which consists of
955 /// declaration-specifiers, some number of declarators, and a semicolon.
956 /// 'Context' should be a Declarator::TheContext value. This returns the
957 /// location of the semicolon in DeclEnd.
959 /// declaration: [C99 6.7]
960 /// block-declaration ->
961 /// simple-declaration
963 /// [C++] template-declaration
964 /// [C++] namespace-definition
965 /// [C++] using-directive
966 /// [C++] using-declaration
967 /// [C++11/C11] static_assert-declaration
968 /// others... [FIXME]
970 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
972 SourceLocation &DeclEnd,
973 ParsedAttributesWithRange &attrs) {
974 ParenBraceBracketBalancer BalancerRAIIObj(*this);
975 // Must temporarily exit the objective-c container scope for
976 // parsing c none objective-c decls.
977 ObjCDeclContextSwitch ObjCDC(*this);
979 Decl *SingleDecl = 0;
981 switch (Tok.getKind()) {
982 case tok::kw_template:
984 ProhibitAttributes(attrs);
985 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
988 // Could be the start of an inline namespace. Allowed as an ext in C++03.
989 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
990 ProhibitAttributes(attrs);
991 SourceLocation InlineLoc = ConsumeToken();
992 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
995 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
997 case tok::kw_namespace:
998 ProhibitAttributes(attrs);
999 SingleDecl = ParseNamespace(Context, DeclEnd);
1002 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1003 DeclEnd, attrs, &OwnedType);
1005 case tok::kw_static_assert:
1006 case tok::kw__Static_assert:
1007 ProhibitAttributes(attrs);
1008 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1011 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1014 // This routine returns a DeclGroup, if the thing we parsed only contains a
1015 // single decl, convert it now. Alias declarations can also declare a type;
1016 // include that too if it is present.
1017 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1020 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1021 /// declaration-specifiers init-declarator-list[opt] ';'
1022 ///[C90/C++]init-declarator-list ';' [TODO]
1023 /// [OMP] threadprivate-directive [TODO]
1025 /// for-range-declaration: [C++0x 6.5p1: stmt.ranged]
1026 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1028 /// If RequireSemi is false, this does not check for a ';' at the end of the
1029 /// declaration. If it is true, it checks for and eats it.
1031 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1032 /// of a simple-declaration. If we find that we are, we also parse the
1033 /// for-range-initializer, and place it here.
1034 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
1036 SourceLocation &DeclEnd,
1037 ParsedAttributes &attrs,
1039 ForRangeInit *FRI) {
1040 // Parse the common declaration-specifiers piece.
1041 ParsingDeclSpec DS(*this);
1042 DS.takeAttributesFrom(attrs);
1044 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1045 getDeclSpecContextFromDeclaratorContext(Context));
1047 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1048 // declaration-specifiers init-declarator-list[opt] ';'
1049 if (Tok.is(tok::semi)) {
1050 if (RequireSemi) ConsumeToken();
1051 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1053 DS.complete(TheDecl);
1054 return Actions.ConvertDeclToDeclGroup(TheDecl);
1057 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1060 /// Returns true if this might be the start of a declarator, or a common typo
1061 /// for a declarator.
1062 bool Parser::MightBeDeclarator(unsigned Context) {
1063 switch (Tok.getKind()) {
1064 case tok::annot_cxxscope:
1065 case tok::annot_template_id:
1067 case tok::code_completion:
1068 case tok::coloncolon:
1070 case tok::kw___attribute:
1071 case tok::kw_operator:
1078 return getLangOpts().CPlusPlus;
1080 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1081 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x &&
1082 NextToken().is(tok::l_square);
1084 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1085 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1087 case tok::identifier:
1088 switch (NextToken().getKind()) {
1089 case tok::code_completion:
1090 case tok::coloncolon:
1093 case tok::equalequal: // Might be a typo for '='.
1094 case tok::kw_alignas:
1096 case tok::kw___attribute:
1108 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1109 // and in block scope it's probably a label. Inside a class definition,
1110 // this is a bit-field.
1111 return Context == Declarator::MemberContext ||
1112 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1114 case tok::identifier: // Possible virt-specifier.
1115 return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken());
1126 /// Skip until we reach something which seems like a sensible place to pick
1127 /// up parsing after a malformed declaration. This will sometimes stop sooner
1128 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1129 void Parser::SkipMalformedDecl() {
1131 switch (Tok.getKind()) {
1133 // Skip until matching }, then stop. We've probably skipped over
1134 // a malformed class or function definition or similar.
1136 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1137 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1138 // This declaration isn't over yet. Keep skipping.
1141 if (Tok.is(tok::semi))
1147 SkipUntil(tok::r_square, /*StopAtSemi*/false);
1152 SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1162 case tok::kw_inline:
1163 // 'inline namespace' at the start of a line is almost certainly
1164 // a good place to pick back up parsing.
1165 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace))
1169 case tok::kw_namespace:
1170 // 'namespace' at the start of a line is almost certainly a good
1171 // place to pick back up parsing.
1172 if (Tok.isAtStartOfLine())
1187 /// ParseDeclGroup - Having concluded that this is either a function
1188 /// definition or a group of object declarations, actually parse the
1190 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1192 bool AllowFunctionDefinitions,
1193 SourceLocation *DeclEnd,
1194 ForRangeInit *FRI) {
1195 // Parse the first declarator.
1196 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1199 // Bail out if the first declarator didn't seem well-formed.
1200 if (!D.hasName() && !D.mayOmitIdentifier()) {
1201 SkipMalformedDecl();
1202 return DeclGroupPtrTy();
1205 // Save late-parsed attributes for now; they need to be parsed in the
1206 // appropriate function scope after the function Decl has been constructed.
1207 LateParsedAttrList LateParsedAttrs;
1208 if (D.isFunctionDeclarator())
1209 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1211 // Check to see if we have a function *definition* which must have a body.
1212 if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
1213 // Look at the next token to make sure that this isn't a function
1214 // declaration. We have to check this because __attribute__ might be the
1215 // start of a function definition in GCC-extended K&R C.
1216 !isDeclarationAfterDeclarator()) {
1218 if (isStartOfFunctionDefinition(D)) {
1219 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1220 Diag(Tok, diag::err_function_declared_typedef);
1222 // Recover by treating the 'typedef' as spurious.
1223 DS.ClearStorageClassSpecs();
1227 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1228 return Actions.ConvertDeclToDeclGroup(TheDecl);
1231 if (isDeclarationSpecifier()) {
1232 // If there is an invalid declaration specifier right after the function
1233 // prototype, then we must be in a missing semicolon case where this isn't
1234 // actually a body. Just fall through into the code that handles it as a
1235 // prototype, and let the top-level code handle the erroneous declspec
1236 // where it would otherwise expect a comma or semicolon.
1238 Diag(Tok, diag::err_expected_fn_body);
1239 SkipUntil(tok::semi);
1240 return DeclGroupPtrTy();
1244 if (ParseAsmAttributesAfterDeclarator(D))
1245 return DeclGroupPtrTy();
1247 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1248 // must parse and analyze the for-range-initializer before the declaration is
1250 if (FRI && Tok.is(tok::colon)) {
1251 FRI->ColonLoc = ConsumeToken();
1252 if (Tok.is(tok::l_brace))
1253 FRI->RangeExpr = ParseBraceInitializer();
1255 FRI->RangeExpr = ParseExpression();
1256 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1257 Actions.ActOnCXXForRangeDecl(ThisDecl);
1258 Actions.FinalizeDeclaration(ThisDecl);
1259 D.complete(ThisDecl);
1260 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
1263 SmallVector<Decl *, 8> DeclsInGroup;
1264 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1265 if (LateParsedAttrs.size() > 0)
1266 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1267 D.complete(FirstDecl);
1269 DeclsInGroup.push_back(FirstDecl);
1271 bool ExpectSemi = Context != Declarator::ForContext;
1273 // If we don't have a comma, it is either the end of the list (a ';') or an
1275 while (Tok.is(tok::comma)) {
1276 SourceLocation CommaLoc = ConsumeToken();
1278 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1279 // This comma was followed by a line-break and something which can't be
1280 // the start of a declarator. The comma was probably a typo for a
1282 Diag(CommaLoc, diag::err_expected_semi_declaration)
1283 << FixItHint::CreateReplacement(CommaLoc, ";");
1288 // Parse the next declarator.
1290 D.setCommaLoc(CommaLoc);
1292 // Accept attributes in an init-declarator. In the first declarator in a
1293 // declaration, these would be part of the declspec. In subsequent
1294 // declarators, they become part of the declarator itself, so that they
1295 // don't apply to declarators after *this* one. Examples:
1296 // short __attribute__((common)) var; -> declspec
1297 // short var __attribute__((common)); -> declarator
1298 // short x, __attribute__((common)) var; -> declarator
1299 MaybeParseGNUAttributes(D);
1302 if (!D.isInvalidType()) {
1303 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1304 D.complete(ThisDecl);
1306 DeclsInGroup.push_back(ThisDecl);
1311 *DeclEnd = Tok.getLocation();
1314 ExpectAndConsume(tok::semi,
1315 Context == Declarator::FileContext
1316 ? diag::err_invalid_token_after_toplevel_declarator
1317 : diag::err_expected_semi_declaration)) {
1318 // Okay, there was no semicolon and one was expected. If we see a
1319 // declaration specifier, just assume it was missing and continue parsing.
1320 // Otherwise things are very confused and we skip to recover.
1321 if (!isDeclarationSpecifier()) {
1322 SkipUntil(tok::r_brace, true, true);
1323 if (Tok.is(tok::semi))
1328 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
1329 DeclsInGroup.data(),
1330 DeclsInGroup.size());
1333 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1334 /// declarator. Returns true on an error.
1335 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1336 // If a simple-asm-expr is present, parse it.
1337 if (Tok.is(tok::kw_asm)) {
1339 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1340 if (AsmLabel.isInvalid()) {
1341 SkipUntil(tok::semi, true, true);
1345 D.setAsmLabel(AsmLabel.release());
1349 MaybeParseGNUAttributes(D);
1353 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1354 /// declarator'. This method parses the remainder of the declaration
1355 /// (including any attributes or initializer, among other things) and
1356 /// finalizes the declaration.
1358 /// init-declarator: [C99 6.7]
1360 /// declarator '=' initializer
1361 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1362 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1363 /// [C++] declarator initializer[opt]
1365 /// [C++] initializer:
1366 /// [C++] '=' initializer-clause
1367 /// [C++] '(' expression-list ')'
1368 /// [C++0x] '=' 'default' [TODO]
1369 /// [C++0x] '=' 'delete'
1370 /// [C++0x] braced-init-list
1372 /// According to the standard grammar, =default and =delete are function
1373 /// definitions, but that definitely doesn't fit with the parser here.
1375 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1376 const ParsedTemplateInfo &TemplateInfo) {
1377 if (ParseAsmAttributesAfterDeclarator(D))
1380 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1383 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1384 const ParsedTemplateInfo &TemplateInfo) {
1385 // Inform the current actions module that we just parsed this declarator.
1387 switch (TemplateInfo.Kind) {
1388 case ParsedTemplateInfo::NonTemplate:
1389 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1392 case ParsedTemplateInfo::Template:
1393 case ParsedTemplateInfo::ExplicitSpecialization:
1394 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1395 MultiTemplateParamsArg(Actions,
1396 TemplateInfo.TemplateParams->data(),
1397 TemplateInfo.TemplateParams->size()),
1401 case ParsedTemplateInfo::ExplicitInstantiation: {
1403 = Actions.ActOnExplicitInstantiation(getCurScope(),
1404 TemplateInfo.ExternLoc,
1405 TemplateInfo.TemplateLoc,
1407 if (ThisRes.isInvalid()) {
1408 SkipUntil(tok::semi, true, true);
1412 ThisDecl = ThisRes.get();
1417 bool TypeContainsAuto =
1418 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
1420 // Parse declarator '=' initializer.
1421 // If a '==' or '+=' is found, suggest a fixit to '='.
1422 if (isTokenEqualOrEqualTypo()) {
1424 if (Tok.is(tok::kw_delete)) {
1425 if (D.isFunctionDeclarator())
1426 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1429 Diag(ConsumeToken(), diag::err_deleted_non_function);
1430 } else if (Tok.is(tok::kw_default)) {
1431 if (D.isFunctionDeclarator())
1432 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1435 Diag(ConsumeToken(), diag::err_default_special_members);
1437 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1439 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1442 if (Tok.is(tok::code_completion)) {
1443 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1448 ExprResult Init(ParseInitializer());
1450 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1451 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1455 if (Init.isInvalid()) {
1456 SkipUntil(tok::comma, true, true);
1457 Actions.ActOnInitializerError(ThisDecl);
1459 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1460 /*DirectInit=*/false, TypeContainsAuto);
1462 } else if (Tok.is(tok::l_paren)) {
1463 // Parse C++ direct initializer: '(' expression-list ')'
1464 BalancedDelimiterTracker T(*this, tok::l_paren);
1467 ExprVector Exprs(Actions);
1468 CommaLocsTy CommaLocs;
1470 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1472 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1475 if (ParseExpressionList(Exprs, CommaLocs)) {
1476 SkipUntil(tok::r_paren);
1478 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1479 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1486 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1487 "Unexpected number of commas!");
1489 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1490 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1494 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1495 T.getCloseLocation(),
1497 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1498 /*DirectInit=*/true, TypeContainsAuto);
1500 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
1501 // Parse C++0x braced-init-list.
1502 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1504 if (D.getCXXScopeSpec().isSet()) {
1506 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1509 ExprResult Init(ParseBraceInitializer());
1511 if (D.getCXXScopeSpec().isSet()) {
1512 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1516 if (Init.isInvalid()) {
1517 Actions.ActOnInitializerError(ThisDecl);
1519 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1520 /*DirectInit=*/true, TypeContainsAuto);
1523 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1526 Actions.FinalizeDeclaration(ThisDecl);
1531 /// ParseSpecifierQualifierList
1532 /// specifier-qualifier-list:
1533 /// type-specifier specifier-qualifier-list[opt]
1534 /// type-qualifier specifier-qualifier-list[opt]
1535 /// [GNU] attributes specifier-qualifier-list[opt]
1537 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1538 DeclSpecContext DSC) {
1539 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1540 /// parse declaration-specifiers and complain about extra stuff.
1541 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1542 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1544 // Validate declspec for type-name.
1545 unsigned Specs = DS.getParsedSpecifiers();
1546 if (DSC == DSC_type_specifier && !DS.hasTypeSpecifier()) {
1547 Diag(Tok, diag::err_expected_type);
1548 DS.SetTypeSpecError();
1549 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1550 !DS.hasAttributes()) {
1551 Diag(Tok, diag::err_typename_requires_specqual);
1552 if (!DS.hasTypeSpecifier())
1553 DS.SetTypeSpecError();
1556 // Issue diagnostic and remove storage class if present.
1557 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1558 if (DS.getStorageClassSpecLoc().isValid())
1559 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1561 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1562 DS.ClearStorageClassSpecs();
1565 // Issue diagnostic and remove function specfier if present.
1566 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1567 if (DS.isInlineSpecified())
1568 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1569 if (DS.isVirtualSpecified())
1570 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1571 if (DS.isExplicitSpecified())
1572 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1573 DS.ClearFunctionSpecs();
1576 // Issue diagnostic and remove constexpr specfier if present.
1577 if (DS.isConstexprSpecified()) {
1578 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1579 DS.ClearConstexprSpec();
1583 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1584 /// specified token is valid after the identifier in a declarator which
1585 /// immediately follows the declspec. For example, these things are valid:
1587 /// int x [ 4]; // direct-declarator
1588 /// int x ( int y); // direct-declarator
1589 /// int(int x ) // direct-declarator
1590 /// int x ; // simple-declaration
1591 /// int x = 17; // init-declarator-list
1592 /// int x , y; // init-declarator-list
1593 /// int x __asm__ ("foo"); // init-declarator-list
1594 /// int x : 4; // struct-declarator
1595 /// int x { 5}; // C++'0x unified initializers
1597 /// This is not, because 'x' does not immediately follow the declspec (though
1598 /// ')' happens to be valid anyway).
1601 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1602 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1603 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1604 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1608 /// ParseImplicitInt - This method is called when we have an non-typename
1609 /// identifier in a declspec (which normally terminates the decl spec) when
1610 /// the declspec has no type specifier. In this case, the declspec is either
1611 /// malformed or is "implicit int" (in K&R and C89).
1613 /// This method handles diagnosing this prettily and returns false if the
1614 /// declspec is done being processed. If it recovers and thinks there may be
1615 /// other pieces of declspec after it, it returns true.
1617 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1618 const ParsedTemplateInfo &TemplateInfo,
1619 AccessSpecifier AS, DeclSpecContext DSC) {
1620 assert(Tok.is(tok::identifier) && "should have identifier");
1622 SourceLocation Loc = Tok.getLocation();
1623 // If we see an identifier that is not a type name, we normally would
1624 // parse it as the identifer being declared. However, when a typename
1625 // is typo'd or the definition is not included, this will incorrectly
1626 // parse the typename as the identifier name and fall over misparsing
1627 // later parts of the diagnostic.
1629 // As such, we try to do some look-ahead in cases where this would
1630 // otherwise be an "implicit-int" case to see if this is invalid. For
1631 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
1632 // an identifier with implicit int, we'd get a parse error because the
1633 // next token is obviously invalid for a type. Parse these as a case
1634 // with an invalid type specifier.
1635 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1637 // Since we know that this either implicit int (which is rare) or an
1638 // error, do lookahead to try to do better recovery. This never applies within
1639 // a type specifier.
1640 // FIXME: Don't bail out here in languages with no implicit int (like
1641 // C++ with no -fms-extensions). This is much more likely to be an undeclared
1642 // type or typo than a use of implicit int.
1643 if (DSC != DSC_type_specifier &&
1644 isValidAfterIdentifierInDeclarator(NextToken())) {
1645 // If this token is valid for implicit int, e.g. "static x = 4", then
1646 // we just avoid eating the identifier, so it will be parsed as the
1647 // identifier in the declarator.
1651 // Otherwise, if we don't consume this token, we are going to emit an
1652 // error anyway. Try to recover from various common problems. Check
1653 // to see if this was a reference to a tag name without a tag specified.
1654 // This is a common problem in C (saying 'foo' instead of 'struct foo').
1656 // C++ doesn't need this, and isTagName doesn't take SS.
1658 const char *TagName = 0, *FixitTagName = 0;
1659 tok::TokenKind TagKind = tok::unknown;
1661 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1663 case DeclSpec::TST_enum:
1664 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
1665 case DeclSpec::TST_union:
1666 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1667 case DeclSpec::TST_struct:
1668 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1669 case DeclSpec::TST_class:
1670 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1674 Diag(Loc, diag::err_use_of_tag_name_without_tag)
1675 << Tok.getIdentifierInfo() << TagName << getLangOpts().CPlusPlus
1676 << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
1678 // Parse this as a tag as if the missing tag were present.
1679 if (TagKind == tok::kw_enum)
1680 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
1682 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
1683 /*EnteringContext*/ false, DSC_normal);
1688 // This is almost certainly an invalid type name. Let the action emit a
1689 // diagnostic and attempt to recover.
1691 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1692 getCurScope(), SS, T)) {
1693 // The action emitted a diagnostic, so we don't have to.
1695 // The action has suggested that the type T could be used. Set that as
1696 // the type in the declaration specifiers, consume the would-be type
1697 // name token, and we're done.
1698 const char *PrevSpec;
1700 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1701 DS.SetRangeEnd(Tok.getLocation());
1704 // There may be other declaration specifiers after this.
1708 // Fall through; the action had no suggestion for us.
1710 // The action did not emit a diagnostic, so emit one now.
1712 if (SS) R = SS->getRange();
1713 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1716 // Mark this as an error.
1717 DS.SetTypeSpecError();
1718 DS.SetRangeEnd(Tok.getLocation());
1721 // TODO: Could inject an invalid typedef decl in an enclosing scope to
1722 // avoid rippling error messages on subsequent uses of the same type,
1723 // could be useful if #include was forgotten.
1727 /// \brief Determine the declaration specifier context from the declarator
1730 /// \param Context the declarator context, which is one of the
1731 /// Declarator::TheContext enumerator values.
1732 Parser::DeclSpecContext
1733 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1734 if (Context == Declarator::MemberContext)
1736 if (Context == Declarator::FileContext)
1737 return DSC_top_level;
1738 if (Context == Declarator::TrailingReturnContext)
1739 return DSC_trailing;
1743 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
1745 /// FIXME: Simply returns an alignof() expression if the argument is a
1746 /// type. Ideally, the type should be propagated directly into Sema.
1749 /// [C11] constant-expression
1750 /// [C++0x] type-id ...[opt]
1751 /// [C++0x] assignment-expression ...[opt]
1752 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
1753 SourceLocation &EllipsisLoc) {
1755 if (isTypeIdInParens()) {
1756 SourceLocation TypeLoc = Tok.getLocation();
1757 ParsedType Ty = ParseTypeName().get();
1758 SourceRange TypeRange(Start, Tok.getLocation());
1759 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
1760 Ty.getAsOpaquePtr(), TypeRange);
1762 ER = ParseConstantExpression();
1764 if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
1765 EllipsisLoc = ConsumeToken();
1770 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
1771 /// attribute to Attrs.
1773 /// alignment-specifier:
1774 /// [C11] '_Alignas' '(' type-id ')'
1775 /// [C11] '_Alignas' '(' constant-expression ')'
1776 /// [C++0x] 'alignas' '(' type-id ...[opt] ')'
1777 /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
1778 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
1779 SourceLocation *endLoc) {
1780 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
1781 "Not an alignment-specifier!");
1783 SourceLocation KWLoc = Tok.getLocation();
1786 BalancedDelimiterTracker T(*this, tok::l_paren);
1787 if (T.expectAndConsume(diag::err_expected_lparen))
1790 SourceLocation EllipsisLoc;
1791 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
1792 if (ArgExpr.isInvalid()) {
1793 SkipUntil(tok::r_paren);
1799 *endLoc = T.getCloseLocation();
1801 // FIXME: Handle pack-expansions here.
1802 if (EllipsisLoc.isValid()) {
1803 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
1807 ExprVector ArgExprs(Actions);
1808 ArgExprs.push_back(ArgExpr.release());
1809 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
1810 0, T.getOpenLocation(), ArgExprs.take(), 1, false, true);
1813 /// ParseDeclarationSpecifiers
1814 /// declaration-specifiers: [C99 6.7]
1815 /// storage-class-specifier declaration-specifiers[opt]
1816 /// type-specifier declaration-specifiers[opt]
1817 /// [C99] function-specifier declaration-specifiers[opt]
1818 /// [C11] alignment-specifier declaration-specifiers[opt]
1819 /// [GNU] attributes declaration-specifiers[opt]
1820 /// [Clang] '__module_private__' declaration-specifiers[opt]
1822 /// storage-class-specifier: [C99 6.7.1]
1829 /// [GNU] '__thread'
1830 /// function-specifier: [C99 6.7.4]
1833 /// [C++] 'explicit'
1834 /// [OpenCL] '__kernel'
1835 /// 'friend': [C++ dcl.friend]
1836 /// 'constexpr': [C++0x dcl.constexpr]
1839 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1840 const ParsedTemplateInfo &TemplateInfo,
1842 DeclSpecContext DSContext,
1843 LateParsedAttrList *LateAttrs) {
1844 if (DS.getSourceRange().isInvalid()) {
1845 DS.SetRangeStart(Tok.getLocation());
1846 DS.SetRangeEnd(Tok.getLocation());
1849 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
1851 bool isInvalid = false;
1852 const char *PrevSpec = 0;
1853 unsigned DiagID = 0;
1855 SourceLocation Loc = Tok.getLocation();
1857 switch (Tok.getKind()) {
1860 // [C++0x] decl-specifier-seq: decl-specifier attribute-specifier-seq[opt]
1861 MaybeParseCXX0XAttributes(DS.getAttributes());
1863 // If this is not a declaration specifier token, we're done reading decl
1864 // specifiers. First verify that DeclSpec's are consistent.
1865 DS.Finish(Diags, PP);
1868 case tok::code_completion: {
1869 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1870 if (DS.hasTypeSpecifier()) {
1871 bool AllowNonIdentifiers
1872 = (getCurScope()->getFlags() & (Scope::ControlScope |
1874 Scope::TemplateParamScope |
1875 Scope::FunctionPrototypeScope |
1876 Scope::AtCatchScope)) == 0;
1877 bool AllowNestedNameSpecifiers
1878 = DSContext == DSC_top_level ||
1879 (DSContext == DSC_class && DS.isFriendSpecified());
1881 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1882 AllowNonIdentifiers,
1883 AllowNestedNameSpecifiers);
1884 return cutOffParsing();
1887 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1888 CCC = Sema::PCC_LocalDeclarationSpecifiers;
1889 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1890 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1891 : Sema::PCC_Template;
1892 else if (DSContext == DSC_class)
1893 CCC = Sema::PCC_Class;
1894 else if (CurParsedObjCImpl)
1895 CCC = Sema::PCC_ObjCImplementation;
1897 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1898 return cutOffParsing();
1901 case tok::coloncolon: // ::foo::bar
1902 // C++ scope specifier. Annotate and loop, or bail out on error.
1903 if (TryAnnotateCXXScopeToken(true)) {
1904 if (!DS.hasTypeSpecifier())
1905 DS.SetTypeSpecError();
1906 goto DoneWithDeclSpec;
1908 if (Tok.is(tok::coloncolon)) // ::new or ::delete
1909 goto DoneWithDeclSpec;
1912 case tok::annot_cxxscope: {
1913 if (DS.hasTypeSpecifier())
1914 goto DoneWithDeclSpec;
1917 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1918 Tok.getAnnotationRange(),
1921 // We are looking for a qualified typename.
1922 Token Next = NextToken();
1923 if (Next.is(tok::annot_template_id) &&
1924 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1925 ->Kind == TNK_Type_template) {
1926 // We have a qualified template-id, e.g., N::A<int>
1928 // C++ [class.qual]p2:
1929 // In a lookup in which the constructor is an acceptable lookup
1930 // result and the nested-name-specifier nominates a class C:
1932 // - if the name specified after the
1933 // nested-name-specifier, when looked up in C, is the
1934 // injected-class-name of C (Clause 9), or
1936 // - if the name specified after the nested-name-specifier
1937 // is the same as the identifier or the
1938 // simple-template-id's template-name in the last
1939 // component of the nested-name-specifier,
1941 // the name is instead considered to name the constructor of
1944 // Thus, if the template-name is actually the constructor
1945 // name, then the code is ill-formed; this interpretation is
1946 // reinforced by the NAD status of core issue 635.
1947 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1948 if ((DSContext == DSC_top_level ||
1949 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1951 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1952 if (isConstructorDeclarator()) {
1953 // The user meant this to be an out-of-line constructor
1954 // definition, but template arguments are not allowed
1955 // there. Just allow this as a constructor; we'll
1956 // complain about it later.
1957 goto DoneWithDeclSpec;
1960 // The user meant this to name a type, but it actually names
1961 // a constructor with some extraneous template
1962 // arguments. Complain, then parse it as a type as the user
1964 Diag(TemplateId->TemplateNameLoc,
1965 diag::err_out_of_line_template_id_names_constructor)
1966 << TemplateId->Name;
1969 DS.getTypeSpecScope() = SS;
1970 ConsumeToken(); // The C++ scope.
1971 assert(Tok.is(tok::annot_template_id) &&
1972 "ParseOptionalCXXScopeSpecifier not working");
1973 AnnotateTemplateIdTokenAsType();
1977 if (Next.is(tok::annot_typename)) {
1978 DS.getTypeSpecScope() = SS;
1979 ConsumeToken(); // The C++ scope.
1980 if (Tok.getAnnotationValue()) {
1981 ParsedType T = getTypeAnnotation(Tok);
1982 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1983 Tok.getAnnotationEndLoc(),
1984 PrevSpec, DiagID, T);
1987 DS.SetTypeSpecError();
1988 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1989 ConsumeToken(); // The typename
1992 if (Next.isNot(tok::identifier))
1993 goto DoneWithDeclSpec;
1995 // If we're in a context where the identifier could be a class name,
1996 // check whether this is a constructor declaration.
1997 if ((DSContext == DSC_top_level ||
1998 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1999 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2001 if (isConstructorDeclarator())
2002 goto DoneWithDeclSpec;
2004 // As noted in C++ [class.qual]p2 (cited above), when the name
2005 // of the class is qualified in a context where it could name
2006 // a constructor, its a constructor name. However, we've
2007 // looked at the declarator, and the user probably meant this
2008 // to be a type. Complain that it isn't supposed to be treated
2009 // as a type, then proceed to parse it as a type.
2010 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2011 << Next.getIdentifierInfo();
2014 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2017 false, false, ParsedType(),
2018 /*IsCtorOrDtorName=*/false,
2019 /*NonTrivialSourceInfo=*/true);
2021 // If the referenced identifier is not a type, then this declspec is
2022 // erroneous: We already checked about that it has no type specifier, and
2023 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2026 ConsumeToken(); // Eat the scope spec so the identifier is current.
2027 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue;
2028 goto DoneWithDeclSpec;
2031 DS.getTypeSpecScope() = SS;
2032 ConsumeToken(); // The C++ scope.
2034 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2039 DS.SetRangeEnd(Tok.getLocation());
2040 ConsumeToken(); // The typename.
2045 case tok::annot_typename: {
2046 if (Tok.getAnnotationValue()) {
2047 ParsedType T = getTypeAnnotation(Tok);
2048 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2051 DS.SetTypeSpecError();
2056 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2057 ConsumeToken(); // The typename
2059 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2060 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2061 // Objective-C interface.
2062 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2063 ParseObjCProtocolQualifiers(DS);
2068 case tok::kw___is_signed:
2069 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2070 // typically treats it as a trait. If we see __is_signed as it appears
2071 // in libstdc++, e.g.,
2073 // static const bool __is_signed;
2075 // then treat __is_signed as an identifier rather than as a keyword.
2076 if (DS.getTypeSpecType() == TST_bool &&
2077 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2078 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2079 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2080 Tok.setKind(tok::identifier);
2083 // We're done with the declaration-specifiers.
2084 goto DoneWithDeclSpec;
2087 case tok::kw_decltype:
2088 case tok::identifier: {
2089 // In C++, check to see if this is a scope specifier like foo::bar::, if
2090 // so handle it as such. This is important for ctor parsing.
2091 if (getLangOpts().CPlusPlus) {
2092 if (TryAnnotateCXXScopeToken(true)) {
2093 if (!DS.hasTypeSpecifier())
2094 DS.SetTypeSpecError();
2095 goto DoneWithDeclSpec;
2097 if (!Tok.is(tok::identifier))
2101 // This identifier can only be a typedef name if we haven't already seen
2102 // a type-specifier. Without this check we misparse:
2103 // typedef int X; struct Y { short X; }; as 'short int'.
2104 if (DS.hasTypeSpecifier())
2105 goto DoneWithDeclSpec;
2107 // Check for need to substitute AltiVec keyword tokens.
2108 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2111 ParsedType TypeRep =
2112 Actions.getTypeName(*Tok.getIdentifierInfo(),
2113 Tok.getLocation(), getCurScope());
2115 // If this is not a typedef name, don't parse it as part of the declspec,
2116 // it must be an implicit int or an error.
2118 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
2119 goto DoneWithDeclSpec;
2122 // If we're in a context where the identifier could be a class name,
2123 // check whether this is a constructor declaration.
2124 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2125 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2126 isConstructorDeclarator())
2127 goto DoneWithDeclSpec;
2129 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2134 DS.SetRangeEnd(Tok.getLocation());
2135 ConsumeToken(); // The identifier
2137 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2138 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2139 // Objective-C interface.
2140 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2141 ParseObjCProtocolQualifiers(DS);
2143 // Need to support trailing type qualifiers (e.g. "id<p> const").
2144 // If a type specifier follows, it will be diagnosed elsewhere.
2149 case tok::annot_template_id: {
2150 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2151 if (TemplateId->Kind != TNK_Type_template) {
2152 // This template-id does not refer to a type name, so we're
2153 // done with the type-specifiers.
2154 goto DoneWithDeclSpec;
2157 // If we're in a context where the template-id could be a
2158 // constructor name or specialization, check whether this is a
2159 // constructor declaration.
2160 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2161 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2162 isConstructorDeclarator())
2163 goto DoneWithDeclSpec;
2165 // Turn the template-id annotation token into a type annotation
2166 // token, then try again to parse it as a type-specifier.
2167 AnnotateTemplateIdTokenAsType();
2171 // GNU attributes support.
2172 case tok::kw___attribute:
2173 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2176 // Microsoft declspec support.
2177 case tok::kw___declspec:
2178 ParseMicrosoftDeclSpec(DS.getAttributes());
2181 // Microsoft single token adornments.
2182 case tok::kw___forceinline:
2183 // FIXME: Add handling here!
2186 case tok::kw___ptr64:
2187 case tok::kw___ptr32:
2189 case tok::kw___cdecl:
2190 case tok::kw___stdcall:
2191 case tok::kw___fastcall:
2192 case tok::kw___thiscall:
2193 case tok::kw___unaligned:
2194 ParseMicrosoftTypeAttributes(DS.getAttributes());
2197 // Borland single token adornments.
2198 case tok::kw___pascal:
2199 ParseBorlandTypeAttributes(DS.getAttributes());
2202 // OpenCL single token adornments.
2203 case tok::kw___kernel:
2204 ParseOpenCLAttributes(DS.getAttributes());
2207 // storage-class-specifier
2208 case tok::kw_typedef:
2209 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2212 case tok::kw_extern:
2213 if (DS.isThreadSpecified())
2214 Diag(Tok, diag::ext_thread_before) << "extern";
2215 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2218 case tok::kw___private_extern__:
2219 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2220 Loc, PrevSpec, DiagID);
2222 case tok::kw_static:
2223 if (DS.isThreadSpecified())
2224 Diag(Tok, diag::ext_thread_before) << "static";
2225 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2229 if (getLangOpts().CPlusPlus0x) {
2230 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2231 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2234 Diag(Tok, diag::ext_auto_storage_class)
2235 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2237 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2240 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2243 case tok::kw_register:
2244 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2247 case tok::kw_mutable:
2248 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2251 case tok::kw___thread:
2252 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
2255 // function-specifier
2256 case tok::kw_inline:
2257 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2259 case tok::kw_virtual:
2260 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2262 case tok::kw_explicit:
2263 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2266 // alignment-specifier
2267 case tok::kw__Alignas:
2268 if (!getLangOpts().C11)
2269 Diag(Tok, diag::ext_c11_alignas);
2270 ParseAlignmentSpecifier(DS.getAttributes());
2274 case tok::kw_friend:
2275 if (DSContext == DSC_class)
2276 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2278 PrevSpec = ""; // not actually used by the diagnostic
2279 DiagID = diag::err_friend_invalid_in_context;
2285 case tok::kw___module_private__:
2286 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2290 case tok::kw_constexpr:
2291 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2296 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2300 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2301 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2304 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2307 case tok::kw___int64:
2308 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2311 case tok::kw_signed:
2312 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2315 case tok::kw_unsigned:
2316 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2319 case tok::kw__Complex:
2320 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2323 case tok::kw__Imaginary:
2324 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2328 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2332 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2336 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2339 case tok::kw___int128:
2340 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2344 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2348 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2351 case tok::kw_double:
2352 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2355 case tok::kw_wchar_t:
2356 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2359 case tok::kw_char16_t:
2360 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2363 case tok::kw_char32_t:
2364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2369 if (Tok.is(tok::kw_bool) &&
2370 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2371 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2372 PrevSpec = ""; // Not used by the diagnostic.
2373 DiagID = diag::err_bool_redeclaration;
2374 // For better error recovery.
2375 Tok.setKind(tok::identifier);
2378 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2382 case tok::kw__Decimal32:
2383 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2386 case tok::kw__Decimal64:
2387 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2390 case tok::kw__Decimal128:
2391 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2394 case tok::kw___vector:
2395 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2397 case tok::kw___pixel:
2398 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2400 case tok::kw___unknown_anytype:
2401 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
2407 case tok::kw_struct:
2408 case tok::kw_union: {
2409 tok::TokenKind Kind = Tok.getKind();
2411 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
2412 EnteringContext, DSContext);
2419 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
2424 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
2427 case tok::kw_volatile:
2428 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2431 case tok::kw_restrict:
2432 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2436 // C++ typename-specifier:
2437 case tok::kw_typename:
2438 if (TryAnnotateTypeOrScopeToken()) {
2439 DS.SetTypeSpecError();
2440 goto DoneWithDeclSpec;
2442 if (!Tok.is(tok::kw_typename))
2446 // GNU typeof support.
2447 case tok::kw_typeof:
2448 ParseTypeofSpecifier(DS);
2451 case tok::annot_decltype:
2452 ParseDecltypeSpecifier(DS);
2455 case tok::kw___underlying_type:
2456 ParseUnderlyingTypeSpecifier(DS);
2459 case tok::kw__Atomic:
2460 ParseAtomicSpecifier(DS);
2463 // OpenCL qualifiers:
2464 case tok::kw_private:
2465 if (!getLangOpts().OpenCL)
2466 goto DoneWithDeclSpec;
2467 case tok::kw___private:
2468 case tok::kw___global:
2469 case tok::kw___local:
2470 case tok::kw___constant:
2471 case tok::kw___read_only:
2472 case tok::kw___write_only:
2473 case tok::kw___read_write:
2474 ParseOpenCLQualifiers(DS);
2478 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
2479 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
2480 // but we support it.
2481 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
2482 goto DoneWithDeclSpec;
2484 if (!ParseObjCProtocolQualifiers(DS))
2485 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
2486 << FixItHint::CreateInsertion(Loc, "id")
2487 << SourceRange(Loc, DS.getSourceRange().getEnd());
2489 // Need to support trailing type qualifiers (e.g. "id<p> const").
2490 // If a type specifier follows, it will be diagnosed elsewhere.
2493 // If the specifier wasn't legal, issue a diagnostic.
2495 assert(PrevSpec && "Method did not return previous specifier!");
2498 if (DiagID == diag::ext_duplicate_declspec)
2500 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2502 Diag(Tok, DiagID) << PrevSpec;
2505 DS.SetRangeEnd(Tok.getLocation());
2506 if (DiagID != diag::err_bool_redeclaration)
2511 /// ParseStructDeclaration - Parse a struct declaration without the terminating
2514 /// struct-declaration:
2515 /// specifier-qualifier-list struct-declarator-list
2516 /// [GNU] __extension__ struct-declaration
2517 /// [GNU] specifier-qualifier-list
2518 /// struct-declarator-list:
2519 /// struct-declarator
2520 /// struct-declarator-list ',' struct-declarator
2521 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
2522 /// struct-declarator:
2524 /// [GNU] declarator attributes[opt]
2525 /// declarator[opt] ':' constant-expression
2526 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
2529 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2531 if (Tok.is(tok::kw___extension__)) {
2532 // __extension__ silences extension warnings in the subexpression.
2533 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2535 return ParseStructDeclaration(DS, Fields);
2538 // Parse the common specifier-qualifiers-list piece.
2539 ParseSpecifierQualifierList(DS);
2541 // If there are no declarators, this is a free-standing declaration
2542 // specifier. Let the actions module cope with it.
2543 if (Tok.is(tok::semi)) {
2544 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2548 // Read struct-declarators until we find the semicolon.
2549 bool FirstDeclarator = true;
2550 SourceLocation CommaLoc;
2552 ParsingDeclRAIIObject PD(*this);
2553 FieldDeclarator DeclaratorInfo(DS);
2554 DeclaratorInfo.D.setCommaLoc(CommaLoc);
2556 // Attributes are only allowed here on successive declarators.
2557 if (!FirstDeclarator)
2558 MaybeParseGNUAttributes(DeclaratorInfo.D);
2560 /// struct-declarator: declarator
2561 /// struct-declarator: declarator[opt] ':' constant-expression
2562 if (Tok.isNot(tok::colon)) {
2563 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2564 ColonProtectionRAIIObject X(*this);
2565 ParseDeclarator(DeclaratorInfo.D);
2568 if (Tok.is(tok::colon)) {
2570 ExprResult Res(ParseConstantExpression());
2571 if (Res.isInvalid())
2572 SkipUntil(tok::semi, true, true);
2574 DeclaratorInfo.BitfieldSize = Res.release();
2577 // If attributes exist after the declarator, parse them.
2578 MaybeParseGNUAttributes(DeclaratorInfo.D);
2580 // We're done with this declarator; invoke the callback.
2581 Decl *D = Fields.invoke(DeclaratorInfo);
2584 // If we don't have a comma, it is either the end of the list (a ';')
2585 // or an error, bail out.
2586 if (Tok.isNot(tok::comma))
2589 // Consume the comma.
2590 CommaLoc = ConsumeToken();
2592 FirstDeclarator = false;
2596 /// ParseStructUnionBody
2597 /// struct-contents:
2598 /// struct-declaration-list
2600 /// [GNU] "struct-declaration-list" without terminatoring ';'
2601 /// struct-declaration-list:
2602 /// struct-declaration
2603 /// struct-declaration-list struct-declaration
2604 /// [OBC] '@' 'defs' '(' class-name ')'
2606 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2607 unsigned TagType, Decl *TagDecl) {
2608 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2609 "parsing struct/union body");
2611 BalancedDelimiterTracker T(*this, tok::l_brace);
2612 if (T.consumeOpen())
2615 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2616 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2618 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2620 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
2621 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
2622 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
2625 SmallVector<Decl *, 32> FieldDecls;
2627 // While we still have something to read, read the declarations in the struct.
2628 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2629 // Each iteration of this loop reads one struct-declaration.
2631 // Check for extraneous top-level semicolon.
2632 if (Tok.is(tok::semi)) {
2633 Diag(Tok, diag::ext_extra_struct_semi)
2634 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2635 << FixItHint::CreateRemoval(Tok.getLocation());
2640 // Parse all the comma separated declarators.
2641 DeclSpec DS(AttrFactory);
2643 if (!Tok.is(tok::at)) {
2644 struct CFieldCallback : FieldCallback {
2647 SmallVectorImpl<Decl *> &FieldDecls;
2649 CFieldCallback(Parser &P, Decl *TagDecl,
2650 SmallVectorImpl<Decl *> &FieldDecls) :
2651 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2653 virtual Decl *invoke(FieldDeclarator &FD) {
2654 // Install the declarator into the current TagDecl.
2655 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2656 FD.D.getDeclSpec().getSourceRange().getBegin(),
2657 FD.D, FD.BitfieldSize);
2658 FieldDecls.push_back(Field);
2661 } Callback(*this, TagDecl, FieldDecls);
2663 ParseStructDeclaration(DS, Callback);
2664 } else { // Handle @defs
2666 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2667 Diag(Tok, diag::err_unexpected_at);
2668 SkipUntil(tok::semi, true);
2672 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2673 if (!Tok.is(tok::identifier)) {
2674 Diag(Tok, diag::err_expected_ident);
2675 SkipUntil(tok::semi, true);
2678 SmallVector<Decl *, 16> Fields;
2679 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2680 Tok.getIdentifierInfo(), Fields);
2681 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2683 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2686 if (Tok.is(tok::semi)) {
2688 } else if (Tok.is(tok::r_brace)) {
2689 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2692 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2693 // Skip to end of block or statement to avoid ext-warning on extra ';'.
2694 SkipUntil(tok::r_brace, true, true);
2695 // If we stopped at a ';', eat it.
2696 if (Tok.is(tok::semi)) ConsumeToken();
2702 ParsedAttributes attrs(AttrFactory);
2703 // If attributes exist after struct contents, parse them.
2704 MaybeParseGNUAttributes(attrs);
2706 Actions.ActOnFields(getCurScope(),
2707 RecordLoc, TagDecl, FieldDecls,
2708 T.getOpenLocation(), T.getCloseLocation(),
2711 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2712 T.getCloseLocation());
2715 /// ParseEnumSpecifier
2716 /// enum-specifier: [C99 6.7.2.2]
2717 /// 'enum' identifier[opt] '{' enumerator-list '}'
2718 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2719 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2720 /// '}' attributes[opt]
2721 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
2723 /// 'enum' identifier
2724 /// [GNU] 'enum' attributes[opt] identifier
2726 /// [C++11] enum-head '{' enumerator-list[opt] '}'
2727 /// [C++11] enum-head '{' enumerator-list ',' '}'
2729 /// enum-head: [C++11]
2730 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
2731 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
2732 /// identifier enum-base[opt]
2734 /// enum-key: [C++11]
2739 /// enum-base: [C++11]
2740 /// ':' type-specifier-seq
2742 /// [C++] elaborated-type-specifier:
2743 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
2745 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2746 const ParsedTemplateInfo &TemplateInfo,
2747 AccessSpecifier AS, DeclSpecContext DSC) {
2748 // Parse the tag portion of this.
2749 if (Tok.is(tok::code_completion)) {
2750 // Code completion for an enum name.
2751 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2752 return cutOffParsing();
2755 SourceLocation ScopedEnumKWLoc;
2756 bool IsScopedUsingClassTag = false;
2758 if (getLangOpts().CPlusPlus0x &&
2759 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2760 Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
2761 IsScopedUsingClassTag = Tok.is(tok::kw_class);
2762 ScopedEnumKWLoc = ConsumeToken();
2765 // C++11 [temp.explicit]p12: The usual access controls do not apply to names
2766 // used to specify explicit instantiations. We extend this to also cover
2767 // explicit specializations.
2768 Sema::SuppressAccessChecksRAII SuppressAccess(Actions,
2769 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2770 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2772 // If attributes exist after tag, parse them.
2773 ParsedAttributes attrs(AttrFactory);
2774 MaybeParseGNUAttributes(attrs);
2776 // If declspecs exist after tag, parse them.
2777 while (Tok.is(tok::kw___declspec))
2778 ParseMicrosoftDeclSpec(attrs);
2780 // Enum definitions should not be parsed in a trailing-return-type.
2781 bool AllowDeclaration = DSC != DSC_trailing;
2783 bool AllowFixedUnderlyingType = AllowDeclaration &&
2784 (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
2785 getLangOpts().ObjC2);
2787 CXXScopeSpec &SS = DS.getTypeSpecScope();
2788 if (getLangOpts().CPlusPlus) {
2789 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
2790 // if a fixed underlying type is allowed.
2791 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
2793 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2794 /*EnteringContext=*/false))
2797 if (SS.isSet() && Tok.isNot(tok::identifier)) {
2798 Diag(Tok, diag::err_expected_ident);
2799 if (Tok.isNot(tok::l_brace)) {
2800 // Has no name and is not a definition.
2801 // Skip the rest of this declarator, up until the comma or semicolon.
2802 SkipUntil(tok::comma, true);
2808 // Must have either 'enum name' or 'enum {...}'.
2809 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2810 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
2811 Diag(Tok, diag::err_expected_ident_lbrace);
2813 // Skip the rest of this declarator, up until the comma or semicolon.
2814 SkipUntil(tok::comma, true);
2818 // If an identifier is present, consume and remember it.
2819 IdentifierInfo *Name = 0;
2820 SourceLocation NameLoc;
2821 if (Tok.is(tok::identifier)) {
2822 Name = Tok.getIdentifierInfo();
2823 NameLoc = ConsumeToken();
2826 if (!Name && ScopedEnumKWLoc.isValid()) {
2827 // C++0x 7.2p2: The optional identifier shall not be omitted in the
2828 // declaration of a scoped enumeration.
2829 Diag(Tok, diag::err_scoped_enum_missing_identifier);
2830 ScopedEnumKWLoc = SourceLocation();
2831 IsScopedUsingClassTag = false;
2834 // Stop suppressing access control now we've parsed the enum name.
2835 SuppressAccess.done();
2837 TypeResult BaseType;
2839 // Parse the fixed underlying type.
2840 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2841 bool PossibleBitfield = false;
2842 if (getCurScope()->getFlags() & Scope::ClassScope) {
2843 // If we're in class scope, this can either be an enum declaration with
2844 // an underlying type, or a declaration of a bitfield member. We try to
2845 // use a simple disambiguation scheme first to catch the common cases
2846 // (integer literal, sizeof); if it's still ambiguous, we then consider
2847 // anything that's a simple-type-specifier followed by '(' as an
2848 // expression. This suffices because function types are not valid
2849 // underlying types anyway.
2850 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2851 // If the next token starts an expression, we know we're parsing a
2852 // bit-field. This is the common case.
2853 if (TPR == TPResult::True())
2854 PossibleBitfield = true;
2855 // If the next token starts a type-specifier-seq, it may be either a
2856 // a fixed underlying type or the start of a function-style cast in C++;
2857 // lookahead one more token to see if it's obvious that we have a
2858 // fixed underlying type.
2859 else if (TPR == TPResult::False() &&
2860 GetLookAheadToken(2).getKind() == tok::semi) {
2864 // We have the start of a type-specifier-seq, so we have to perform
2865 // tentative parsing to determine whether we have an expression or a
2867 TentativeParsingAction TPA(*this);
2872 // If we see a type specifier followed by an open-brace, we have an
2873 // ambiguity between an underlying type and a C++11 braced
2874 // function-style cast. Resolve this by always treating it as an
2876 // FIXME: The standard is not entirely clear on how to disambiguate in
2878 if ((getLangOpts().CPlusPlus &&
2879 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
2880 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
2881 // We'll parse this as a bitfield later.
2882 PossibleBitfield = true;
2885 // We have a type-specifier-seq.
2894 if (!PossibleBitfield) {
2896 BaseType = ParseTypeName(&Range);
2898 if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2)
2899 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2901 if (getLangOpts().CPlusPlus0x)
2902 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
2906 // There are four options here. If we have 'friend enum foo;' then this is a
2907 // friend declaration, and cannot have an accompanying definition. If we have
2908 // 'enum foo;', then this is a forward declaration. If we have
2909 // 'enum foo {...' then this is a definition. Otherwise we have something
2910 // like 'enum foo xyz', a reference.
2912 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2913 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
2914 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
2916 Sema::TagUseKind TUK;
2917 if (DS.isFriendSpecified())
2918 TUK = Sema::TUK_Friend;
2919 else if (!AllowDeclaration)
2920 TUK = Sema::TUK_Reference;
2921 else if (Tok.is(tok::l_brace))
2922 TUK = Sema::TUK_Definition;
2923 else if (Tok.is(tok::semi) && DSC != DSC_type_specifier)
2924 TUK = Sema::TUK_Declaration;
2926 TUK = Sema::TUK_Reference;
2928 MultiTemplateParamsArg TParams;
2929 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2930 TUK != Sema::TUK_Reference) {
2931 if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
2932 // Skip the rest of this declarator, up until the comma or semicolon.
2933 Diag(Tok, diag::err_enum_template);
2934 SkipUntil(tok::comma, true);
2938 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2939 // Enumerations can't be explicitly instantiated.
2940 DS.SetTypeSpecError();
2941 Diag(StartLoc, diag::err_explicit_instantiation_enum);
2945 assert(TemplateInfo.TemplateParams && "no template parameters");
2946 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
2947 TemplateInfo.TemplateParams->size());
2950 if (!Name && TUK != Sema::TUK_Definition) {
2951 Diag(Tok, diag::err_enumerator_unnamed_no_def);
2953 // Skip the rest of this declarator, up until the comma or semicolon.
2954 SkipUntil(tok::comma, true);
2959 bool IsDependent = false;
2960 const char *PrevSpec = 0;
2962 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2963 StartLoc, SS, Name, NameLoc, attrs.getList(),
2964 AS, DS.getModulePrivateSpecLoc(), TParams,
2965 Owned, IsDependent, ScopedEnumKWLoc,
2966 IsScopedUsingClassTag, BaseType);
2969 // This enum has a dependent nested-name-specifier. Handle it as a
2972 DS.SetTypeSpecError();
2973 Diag(Tok, diag::err_expected_type_name_after_typename);
2977 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2978 TUK, SS, Name, StartLoc,
2980 if (Type.isInvalid()) {
2981 DS.SetTypeSpecError();
2985 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2986 NameLoc.isValid() ? NameLoc : StartLoc,
2987 PrevSpec, DiagID, Type.get()))
2988 Diag(StartLoc, DiagID) << PrevSpec;
2994 // The action failed to produce an enumeration tag. If this is a
2995 // definition, consume the entire definition.
2996 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
2998 SkipUntil(tok::r_brace);
3001 DS.SetTypeSpecError();
3005 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3006 if (TUK == Sema::TUK_Friend) {
3007 Diag(Tok, diag::err_friend_decl_defines_type)
3008 << SourceRange(DS.getFriendSpecLoc());
3010 SkipUntil(tok::r_brace);
3012 ParseEnumBody(StartLoc, TagDecl);
3016 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3017 NameLoc.isValid() ? NameLoc : StartLoc,
3018 PrevSpec, DiagID, TagDecl, Owned))
3019 Diag(StartLoc, DiagID) << PrevSpec;
3022 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3023 /// enumerator-list:
3025 /// enumerator-list ',' enumerator
3027 /// enumeration-constant
3028 /// enumeration-constant '=' constant-expression
3029 /// enumeration-constant:
3032 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3033 // Enter the scope of the enum body and start the definition.
3034 ParseScope EnumScope(this, Scope::DeclScope);
3035 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3037 BalancedDelimiterTracker T(*this, tok::l_brace);
3040 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3041 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3042 Diag(Tok, diag::error_empty_enum);
3044 SmallVector<Decl *, 32> EnumConstantDecls;
3046 Decl *LastEnumConstDecl = 0;
3048 // Parse the enumerator-list.
3049 while (Tok.is(tok::identifier)) {
3050 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3051 SourceLocation IdentLoc = ConsumeToken();
3053 // If attributes exist after the enumerator, parse them.
3054 ParsedAttributes attrs(AttrFactory);
3055 MaybeParseGNUAttributes(attrs);
3057 SourceLocation EqualLoc;
3058 ExprResult AssignedVal;
3059 ParsingDeclRAIIObject PD(*this);
3061 if (Tok.is(tok::equal)) {
3062 EqualLoc = ConsumeToken();
3063 AssignedVal = ParseConstantExpression();
3064 if (AssignedVal.isInvalid())
3065 SkipUntil(tok::comma, tok::r_brace, true, true);
3068 // Install the enumerator constant into EnumDecl.
3069 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3072 attrs.getList(), EqualLoc,
3073 AssignedVal.release());
3074 PD.complete(EnumConstDecl);
3076 EnumConstantDecls.push_back(EnumConstDecl);
3077 LastEnumConstDecl = EnumConstDecl;
3079 if (Tok.is(tok::identifier)) {
3080 // We're missing a comma between enumerators.
3081 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3082 Diag(Loc, diag::err_enumerator_list_missing_comma)
3083 << FixItHint::CreateInsertion(Loc, ", ");
3087 if (Tok.isNot(tok::comma))
3089 SourceLocation CommaLoc = ConsumeToken();
3091 if (Tok.isNot(tok::identifier)) {
3092 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
3093 Diag(CommaLoc, diag::ext_enumerator_list_comma)
3094 << getLangOpts().CPlusPlus
3095 << FixItHint::CreateRemoval(CommaLoc);
3096 else if (getLangOpts().CPlusPlus0x)
3097 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3098 << FixItHint::CreateRemoval(CommaLoc);
3105 // If attributes exist after the identifier list, parse them.
3106 ParsedAttributes attrs(AttrFactory);
3107 MaybeParseGNUAttributes(attrs);
3109 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3110 EnumDecl, EnumConstantDecls.data(),
3111 EnumConstantDecls.size(), getCurScope(),
3115 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3116 T.getCloseLocation());
3119 /// isTypeSpecifierQualifier - Return true if the current token could be the
3120 /// start of a type-qualifier-list.
3121 bool Parser::isTypeQualifier() const {
3122 switch (Tok.getKind()) {
3123 default: return false;
3125 // type-qualifier only in OpenCL
3126 case tok::kw_private:
3127 return getLangOpts().OpenCL;
3131 case tok::kw_volatile:
3132 case tok::kw_restrict:
3133 case tok::kw___private:
3134 case tok::kw___local:
3135 case tok::kw___global:
3136 case tok::kw___constant:
3137 case tok::kw___read_only:
3138 case tok::kw___read_write:
3139 case tok::kw___write_only:
3144 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3145 /// is definitely a type-specifier. Return false if it isn't part of a type
3146 /// specifier or if we're not sure.
3147 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3148 switch (Tok.getKind()) {
3149 default: return false;
3153 case tok::kw___int64:
3154 case tok::kw___int128:
3155 case tok::kw_signed:
3156 case tok::kw_unsigned:
3157 case tok::kw__Complex:
3158 case tok::kw__Imaginary:
3161 case tok::kw_wchar_t:
3162 case tok::kw_char16_t:
3163 case tok::kw_char32_t:
3167 case tok::kw_double:
3170 case tok::kw__Decimal32:
3171 case tok::kw__Decimal64:
3172 case tok::kw__Decimal128:
3173 case tok::kw___vector:
3175 // struct-or-union-specifier (C99) or class-specifier (C++)
3177 case tok::kw_struct:
3183 case tok::annot_typename:
3188 /// isTypeSpecifierQualifier - Return true if the current token could be the
3189 /// start of a specifier-qualifier-list.
3190 bool Parser::isTypeSpecifierQualifier() {
3191 switch (Tok.getKind()) {
3192 default: return false;
3194 case tok::identifier: // foo::bar
3195 if (TryAltiVecVectorToken())
3198 case tok::kw_typename: // typename T::type
3199 // Annotate typenames and C++ scope specifiers. If we get one, just
3200 // recurse to handle whatever we get.
3201 if (TryAnnotateTypeOrScopeToken())
3203 if (Tok.is(tok::identifier))
3205 return isTypeSpecifierQualifier();
3207 case tok::coloncolon: // ::foo::bar
3208 if (NextToken().is(tok::kw_new) || // ::new
3209 NextToken().is(tok::kw_delete)) // ::delete
3212 if (TryAnnotateTypeOrScopeToken())
3214 return isTypeSpecifierQualifier();
3216 // GNU attributes support.
3217 case tok::kw___attribute:
3218 // GNU typeof support.
3219 case tok::kw_typeof:
3224 case tok::kw___int64:
3225 case tok::kw___int128:
3226 case tok::kw_signed:
3227 case tok::kw_unsigned:
3228 case tok::kw__Complex:
3229 case tok::kw__Imaginary:
3232 case tok::kw_wchar_t:
3233 case tok::kw_char16_t:
3234 case tok::kw_char32_t:
3238 case tok::kw_double:
3241 case tok::kw__Decimal32:
3242 case tok::kw__Decimal64:
3243 case tok::kw__Decimal128:
3244 case tok::kw___vector:
3246 // struct-or-union-specifier (C99) or class-specifier (C++)
3248 case tok::kw_struct:
3255 case tok::kw_volatile:
3256 case tok::kw_restrict:
3259 case tok::annot_typename:
3262 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3264 return getLangOpts().ObjC1;
3266 case tok::kw___cdecl:
3267 case tok::kw___stdcall:
3268 case tok::kw___fastcall:
3269 case tok::kw___thiscall:
3271 case tok::kw___ptr64:
3272 case tok::kw___ptr32:
3273 case tok::kw___pascal:
3274 case tok::kw___unaligned:
3276 case tok::kw___private:
3277 case tok::kw___local:
3278 case tok::kw___global:
3279 case tok::kw___constant:
3280 case tok::kw___read_only:
3281 case tok::kw___read_write:
3282 case tok::kw___write_only:
3286 case tok::kw_private:
3287 return getLangOpts().OpenCL;
3290 case tok::kw__Atomic:
3295 /// isDeclarationSpecifier() - Return true if the current token is part of a
3296 /// declaration specifier.
3298 /// \param DisambiguatingWithExpression True to indicate that the purpose of
3299 /// this check is to disambiguate between an expression and a declaration.
3300 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
3301 switch (Tok.getKind()) {
3302 default: return false;
3304 case tok::kw_private:
3305 return getLangOpts().OpenCL;
3307 case tok::identifier: // foo::bar
3308 // Unfortunate hack to support "Class.factoryMethod" notation.
3309 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
3311 if (TryAltiVecVectorToken())
3314 case tok::kw_decltype: // decltype(T())::type
3315 case tok::kw_typename: // typename T::type
3316 // Annotate typenames and C++ scope specifiers. If we get one, just
3317 // recurse to handle whatever we get.
3318 if (TryAnnotateTypeOrScopeToken())
3320 if (Tok.is(tok::identifier))
3323 // If we're in Objective-C and we have an Objective-C class type followed
3324 // by an identifier and then either ':' or ']', in a place where an
3325 // expression is permitted, then this is probably a class message send
3326 // missing the initial '['. In this case, we won't consider this to be
3327 // the start of a declaration.
3328 if (DisambiguatingWithExpression &&
3329 isStartOfObjCClassMessageMissingOpenBracket())
3332 return isDeclarationSpecifier();
3334 case tok::coloncolon: // ::foo::bar
3335 if (NextToken().is(tok::kw_new) || // ::new
3336 NextToken().is(tok::kw_delete)) // ::delete
3339 // Annotate typenames and C++ scope specifiers. If we get one, just
3340 // recurse to handle whatever we get.
3341 if (TryAnnotateTypeOrScopeToken())
3343 return isDeclarationSpecifier();
3345 // storage-class-specifier
3346 case tok::kw_typedef:
3347 case tok::kw_extern:
3348 case tok::kw___private_extern__:
3349 case tok::kw_static:
3351 case tok::kw_register:
3352 case tok::kw___thread:
3355 case tok::kw___module_private__:
3360 case tok::kw___int64:
3361 case tok::kw___int128:
3362 case tok::kw_signed:
3363 case tok::kw_unsigned:
3364 case tok::kw__Complex:
3365 case tok::kw__Imaginary:
3368 case tok::kw_wchar_t:
3369 case tok::kw_char16_t:
3370 case tok::kw_char32_t:
3375 case tok::kw_double:
3378 case tok::kw__Decimal32:
3379 case tok::kw__Decimal64:
3380 case tok::kw__Decimal128:
3381 case tok::kw___vector:
3383 // struct-or-union-specifier (C99) or class-specifier (C++)
3385 case tok::kw_struct:
3392 case tok::kw_volatile:
3393 case tok::kw_restrict:
3395 // function-specifier
3396 case tok::kw_inline:
3397 case tok::kw_virtual:
3398 case tok::kw_explicit:
3400 // static_assert-declaration
3401 case tok::kw__Static_assert:
3403 // GNU typeof support.
3404 case tok::kw_typeof:
3407 case tok::kw___attribute:
3411 case tok::annot_decltype:
3415 case tok::kw__Atomic:
3418 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3420 return getLangOpts().ObjC1;
3423 case tok::annot_typename:
3424 return !DisambiguatingWithExpression ||
3425 !isStartOfObjCClassMessageMissingOpenBracket();
3427 case tok::kw___declspec:
3428 case tok::kw___cdecl:
3429 case tok::kw___stdcall:
3430 case tok::kw___fastcall:
3431 case tok::kw___thiscall:
3433 case tok::kw___ptr64:
3434 case tok::kw___ptr32:
3435 case tok::kw___forceinline:
3436 case tok::kw___pascal:
3437 case tok::kw___unaligned:
3439 case tok::kw___private:
3440 case tok::kw___local:
3441 case tok::kw___global:
3442 case tok::kw___constant:
3443 case tok::kw___read_only:
3444 case tok::kw___read_write:
3445 case tok::kw___write_only:
3451 bool Parser::isConstructorDeclarator() {
3452 TentativeParsingAction TPA(*this);
3454 // Parse the C++ scope specifier.
3456 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3457 /*EnteringContext=*/true)) {
3462 // Parse the constructor name.
3463 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3464 // We already know that we have a constructor name; just consume
3472 // Current class name must be followed by a left parenthesis.
3473 if (Tok.isNot(tok::l_paren)) {
3479 // A right parenthesis, or ellipsis followed by a right parenthesis signals
3480 // that we have a constructor.
3481 if (Tok.is(tok::r_paren) ||
3482 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
3487 // If we need to, enter the specified scope.
3488 DeclaratorScopeObj DeclScopeObj(*this, SS);
3489 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3490 DeclScopeObj.EnterDeclaratorScope();
3492 // Optionally skip Microsoft attributes.
3493 ParsedAttributes Attrs(AttrFactory);
3494 MaybeParseMicrosoftAttributes(Attrs);
3496 // Check whether the next token(s) are part of a declaration
3497 // specifier, in which case we have the start of a parameter and,
3498 // therefore, we know that this is a constructor.
3499 bool IsConstructor = false;
3500 if (isDeclarationSpecifier())
3501 IsConstructor = true;
3502 else if (Tok.is(tok::identifier) ||
3503 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
3504 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
3505 // This might be a parenthesized member name, but is more likely to
3506 // be a constructor declaration with an invalid argument type. Keep
3508 if (Tok.is(tok::annot_cxxscope))
3512 // If this is not a constructor, we must be parsing a declarator,
3513 // which must have one of the following syntactic forms (see the
3514 // grammar extract at the start of ParseDirectDeclarator):
3515 switch (Tok.getKind()) {
3520 // C(X [ [attribute]]);
3521 case tok::coloncolon:
3526 // Assume this isn't a constructor, rather than assuming it's a
3527 // constructor with an unnamed parameter of an ill-formed type.
3531 IsConstructor = true;
3537 return IsConstructor;
3540 /// ParseTypeQualifierListOpt
3541 /// type-qualifier-list: [C99 6.7.5]
3543 /// [vendor] attributes
3544 /// [ only if VendorAttributesAllowed=true ]
3545 /// type-qualifier-list type-qualifier
3546 /// [vendor] type-qualifier-list attributes
3547 /// [ only if VendorAttributesAllowed=true ]
3548 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
3549 /// [ only if CXX0XAttributesAllowed=true ]
3550 /// Note: vendor can be GNU, MS, etc.
3552 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3553 bool VendorAttributesAllowed,
3554 bool CXX11AttributesAllowed) {
3555 if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
3556 isCXX11AttributeSpecifier()) {
3557 ParsedAttributesWithRange attrs(AttrFactory);
3558 ParseCXX11Attributes(attrs);
3559 DS.takeAttributesFrom(attrs);
3562 SourceLocation EndLoc;
3565 bool isInvalid = false;
3566 const char *PrevSpec = 0;
3567 unsigned DiagID = 0;
3568 SourceLocation Loc = Tok.getLocation();
3570 switch (Tok.getKind()) {
3571 case tok::code_completion:
3572 Actions.CodeCompleteTypeQualifiers(DS);
3573 return cutOffParsing();
3576 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
3579 case tok::kw_volatile:
3580 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3583 case tok::kw_restrict:
3584 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3588 // OpenCL qualifiers:
3589 case tok::kw_private:
3590 if (!getLangOpts().OpenCL)
3591 goto DoneWithTypeQuals;
3592 case tok::kw___private:
3593 case tok::kw___global:
3594 case tok::kw___local:
3595 case tok::kw___constant:
3596 case tok::kw___read_only:
3597 case tok::kw___write_only:
3598 case tok::kw___read_write:
3599 ParseOpenCLQualifiers(DS);
3603 case tok::kw___ptr64:
3604 case tok::kw___ptr32:
3605 case tok::kw___cdecl:
3606 case tok::kw___stdcall:
3607 case tok::kw___fastcall:
3608 case tok::kw___thiscall:
3609 case tok::kw___unaligned:
3610 if (VendorAttributesAllowed) {
3611 ParseMicrosoftTypeAttributes(DS.getAttributes());
3614 goto DoneWithTypeQuals;
3615 case tok::kw___pascal:
3616 if (VendorAttributesAllowed) {
3617 ParseBorlandTypeAttributes(DS.getAttributes());
3620 goto DoneWithTypeQuals;
3621 case tok::kw___attribute:
3622 if (VendorAttributesAllowed) {
3623 ParseGNUAttributes(DS.getAttributes());
3624 continue; // do *not* consume the next token!
3626 // otherwise, FALL THROUGH!
3629 // If this is not a type-qualifier token, we're done reading type
3630 // qualifiers. First verify that DeclSpec's are consistent.
3631 DS.Finish(Diags, PP);
3632 if (EndLoc.isValid())
3633 DS.SetRangeEnd(EndLoc);
3637 // If the specifier combination wasn't legal, issue a diagnostic.
3639 assert(PrevSpec && "Method did not return previous specifier!");
3640 Diag(Tok, DiagID) << PrevSpec;
3642 EndLoc = ConsumeToken();
3647 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3649 void Parser::ParseDeclarator(Declarator &D) {
3650 /// This implements the 'declarator' production in the C grammar, then checks
3651 /// for well-formedness and issues diagnostics.
3652 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3655 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
3656 if (Kind == tok::star || Kind == tok::caret)
3659 // We parse rvalue refs in C++03, because otherwise the errors are scary.
3660 if (!Lang.CPlusPlus)
3663 return Kind == tok::amp || Kind == tok::ampamp;
3666 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3667 /// is parsed by the function passed to it. Pass null, and the direct-declarator
3668 /// isn't parsed at all, making this function effectively parse the C++
3669 /// ptr-operator production.
3671 /// If the grammar of this construct is extended, matching changes must also be
3672 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
3673 /// isConstructorDeclarator.
3675 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3676 /// [C] pointer[opt] direct-declarator
3677 /// [C++] direct-declarator
3678 /// [C++] ptr-operator declarator
3680 /// pointer: [C99 6.7.5]
3681 /// '*' type-qualifier-list[opt]
3682 /// '*' type-qualifier-list[opt] pointer
3685 /// '*' cv-qualifier-seq[opt]
3688 /// [GNU] '&' restrict[opt] attributes[opt]
3689 /// [GNU?] '&&' restrict[opt] attributes[opt]
3690 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3691 void Parser::ParseDeclaratorInternal(Declarator &D,
3692 DirectDeclParseFunction DirectDeclParser) {
3693 if (Diags.hasAllExtensionsSilenced())
3696 // C++ member pointers start with a '::' or a nested-name.
3697 // Member pointers get special handling, since there's no place for the
3698 // scope spec in the generic path below.
3699 if (getLangOpts().CPlusPlus &&
3700 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3701 Tok.is(tok::annot_cxxscope))) {
3702 bool EnteringContext = D.getContext() == Declarator::FileContext ||
3703 D.getContext() == Declarator::MemberContext;
3705 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
3707 if (SS.isNotEmpty()) {
3708 if (Tok.isNot(tok::star)) {
3709 // The scope spec really belongs to the direct-declarator.
3710 D.getCXXScopeSpec() = SS;
3711 if (DirectDeclParser)
3712 (this->*DirectDeclParser)(D);
3716 SourceLocation Loc = ConsumeToken();
3718 DeclSpec DS(AttrFactory);
3719 ParseTypeQualifierListOpt(DS);
3720 D.ExtendWithDeclSpec(DS);
3722 // Recurse to parse whatever is left.
3723 ParseDeclaratorInternal(D, DirectDeclParser);
3725 // Sema will have to catch (syntactically invalid) pointers into global
3726 // scope. It has to catch pointers into namespace scope anyway.
3727 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3730 /* Don't replace range end. */SourceLocation());
3735 tok::TokenKind Kind = Tok.getKind();
3736 // Not a pointer, C++ reference, or block.
3737 if (!isPtrOperatorToken(Kind, getLangOpts())) {
3738 if (DirectDeclParser)
3739 (this->*DirectDeclParser)(D);
3743 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3744 // '&&' -> rvalue reference
3745 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
3748 if (Kind == tok::star || Kind == tok::caret) {
3750 DeclSpec DS(AttrFactory);
3752 // FIXME: GNU attributes are not allowed here in a new-type-id.
3753 ParseTypeQualifierListOpt(DS);
3754 D.ExtendWithDeclSpec(DS);
3756 // Recursively parse the declarator.
3757 ParseDeclaratorInternal(D, DirectDeclParser);
3758 if (Kind == tok::star)
3759 // Remember that we parsed a pointer type, and remember the type-quals.
3760 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3761 DS.getConstSpecLoc(),
3762 DS.getVolatileSpecLoc(),
3763 DS.getRestrictSpecLoc()),
3767 // Remember that we parsed a Block type, and remember the type-quals.
3768 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3774 DeclSpec DS(AttrFactory);
3776 // Complain about rvalue references in C++03, but then go on and build
3778 if (Kind == tok::ampamp)
3779 Diag(Loc, getLangOpts().CPlusPlus0x ?
3780 diag::warn_cxx98_compat_rvalue_reference :
3781 diag::ext_rvalue_reference);
3783 // GNU-style and C++11 attributes are allowed here, as is restrict.
3784 ParseTypeQualifierListOpt(DS);
3785 D.ExtendWithDeclSpec(DS);
3787 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3788 // cv-qualifiers are introduced through the use of a typedef or of a
3789 // template type argument, in which case the cv-qualifiers are ignored.
3790 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3791 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3792 Diag(DS.getConstSpecLoc(),
3793 diag::err_invalid_reference_qualifier_application) << "const";
3794 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3795 Diag(DS.getVolatileSpecLoc(),
3796 diag::err_invalid_reference_qualifier_application) << "volatile";
3799 // Recursively parse the declarator.
3800 ParseDeclaratorInternal(D, DirectDeclParser);
3802 if (D.getNumTypeObjects() > 0) {
3803 // C++ [dcl.ref]p4: There shall be no references to references.
3804 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3805 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3806 if (const IdentifierInfo *II = D.getIdentifier())
3807 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3810 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3813 // Once we've complained about the reference-to-reference, we
3814 // can go ahead and build the (technically ill-formed)
3815 // declarator: reference collapsing will take care of it.
3819 // Remember that we parsed a reference type. It doesn't have type-quals.
3820 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3827 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
3828 SourceLocation EllipsisLoc) {
3829 if (EllipsisLoc.isValid()) {
3830 FixItHint Insertion;
3831 if (!D.getEllipsisLoc().isValid()) {
3832 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
3833 D.setEllipsisLoc(EllipsisLoc);
3835 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
3836 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
3840 /// ParseDirectDeclarator
3841 /// direct-declarator: [C99 6.7.5]
3842 /// [C99] identifier
3843 /// '(' declarator ')'
3844 /// [GNU] '(' attributes declarator ')'
3845 /// [C90] direct-declarator '[' constant-expression[opt] ']'
3846 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3847 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3848 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3849 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
3850 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
3851 /// attribute-specifier-seq[opt]
3852 /// direct-declarator '(' parameter-type-list ')'
3853 /// direct-declarator '(' identifier-list[opt] ')'
3854 /// [GNU] direct-declarator '(' parameter-forward-declarations
3855 /// parameter-type-list[opt] ')'
3856 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
3857 /// cv-qualifier-seq[opt] exception-specification[opt]
3858 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
3859 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
3860 /// ref-qualifier[opt] exception-specification[opt]
3861 /// [C++] declarator-id
3862 /// [C++11] declarator-id attribute-specifier-seq[opt]
3864 /// declarator-id: [C++ 8]
3865 /// '...'[opt] id-expression
3866 /// '::'[opt] nested-name-specifier[opt] type-name
3868 /// id-expression: [C++ 5.1]
3872 /// unqualified-id: [C++ 5.1]
3874 /// operator-function-id
3875 /// conversion-function-id
3879 /// Note, any additional constructs added here may need corresponding changes
3880 /// in isConstructorDeclarator.
3881 void Parser::ParseDirectDeclarator(Declarator &D) {
3882 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3884 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
3885 // ParseDeclaratorInternal might already have parsed the scope.
3886 if (D.getCXXScopeSpec().isEmpty()) {
3887 bool EnteringContext = D.getContext() == Declarator::FileContext ||
3888 D.getContext() == Declarator::MemberContext;
3889 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
3893 if (D.getCXXScopeSpec().isValid()) {
3894 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3895 // Change the declaration context for name lookup, until this function
3896 // is exited (and the declarator has been parsed).
3897 DeclScopeObj.EnterDeclaratorScope();
3900 // C++0x [dcl.fct]p14:
3901 // There is a syntactic ambiguity when an ellipsis occurs at the end
3902 // of a parameter-declaration-clause without a preceding comma. In
3903 // this case, the ellipsis is parsed as part of the
3904 // abstract-declarator if the type of the parameter names a template
3905 // parameter pack that has not been expanded; otherwise, it is parsed
3906 // as part of the parameter-declaration-clause.
3907 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
3908 !((D.getContext() == Declarator::PrototypeContext ||
3909 D.getContext() == Declarator::BlockLiteralContext) &&
3910 NextToken().is(tok::r_paren) &&
3911 !Actions.containsUnexpandedParameterPacks(D))) {
3912 SourceLocation EllipsisLoc = ConsumeToken();
3913 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
3914 // The ellipsis was put in the wrong place. Recover, and explain to
3915 // the user what they should have done.
3917 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
3920 D.setEllipsisLoc(EllipsisLoc);
3922 // The ellipsis can't be followed by a parenthesized declarator. We
3923 // check for that in ParseParenDeclarator, after we have disambiguated
3924 // the l_paren token.
3927 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3928 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3929 // We found something that indicates the start of an unqualified-id.
3930 // Parse that unqualified-id.
3931 bool AllowConstructorName;
3932 if (D.getDeclSpec().hasTypeSpecifier())
3933 AllowConstructorName = false;
3934 else if (D.getCXXScopeSpec().isSet())
3935 AllowConstructorName =
3936 (D.getContext() == Declarator::FileContext ||
3937 (D.getContext() == Declarator::MemberContext &&
3938 D.getDeclSpec().isFriendSpecified()));
3940 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3942 SourceLocation TemplateKWLoc;
3943 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3944 /*EnteringContext=*/true,
3945 /*AllowDestructorName=*/true,
3946 AllowConstructorName,
3950 // Once we're past the identifier, if the scope was bad, mark the
3951 // whole declarator bad.
3952 D.getCXXScopeSpec().isInvalid()) {
3953 D.SetIdentifier(0, Tok.getLocation());
3954 D.setInvalidType(true);
3956 // Parsed the unqualified-id; update range information and move along.
3957 if (D.getSourceRange().getBegin().isInvalid())
3958 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3959 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3961 goto PastIdentifier;
3963 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3964 assert(!getLangOpts().CPlusPlus &&
3965 "There's a C++-specific check for tok::identifier above");
3966 assert(Tok.getIdentifierInfo() && "Not an identifier?");
3967 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3969 goto PastIdentifier;
3972 if (Tok.is(tok::l_paren)) {
3973 // direct-declarator: '(' declarator ')'
3974 // direct-declarator: '(' attributes declarator ')'
3975 // Example: 'char (*X)' or 'int (*XX)(void)'
3976 ParseParenDeclarator(D);
3978 // If the declarator was parenthesized, we entered the declarator
3979 // scope when parsing the parenthesized declarator, then exited
3980 // the scope already. Re-enter the scope, if we need to.
3981 if (D.getCXXScopeSpec().isSet()) {
3982 // If there was an error parsing parenthesized declarator, declarator
3983 // scope may have been entered before. Don't do it again.
3984 if (!D.isInvalidType() &&
3985 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3986 // Change the declaration context for name lookup, until this function
3987 // is exited (and the declarator has been parsed).
3988 DeclScopeObj.EnterDeclaratorScope();
3990 } else if (D.mayOmitIdentifier()) {
3991 // This could be something simple like "int" (in which case the declarator
3992 // portion is empty), if an abstract-declarator is allowed.
3993 D.SetIdentifier(0, Tok.getLocation());
3995 if (D.getContext() == Declarator::MemberContext)
3996 Diag(Tok, diag::err_expected_member_name_or_semi)
3997 << D.getDeclSpec().getSourceRange();
3998 else if (getLangOpts().CPlusPlus)
3999 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4001 Diag(Tok, diag::err_expected_ident_lparen);
4002 D.SetIdentifier(0, Tok.getLocation());
4003 D.setInvalidType(true);
4007 assert(D.isPastIdentifier() &&
4008 "Haven't past the location of the identifier yet?");
4010 // Don't parse attributes unless we have parsed an unparenthesized name.
4011 if (D.hasName() && !D.getNumTypeObjects())
4012 MaybeParseCXX0XAttributes(D);
4015 if (Tok.is(tok::l_paren)) {
4016 // Enter function-declaration scope, limiting any declarators to the
4017 // function prototype scope, including parameter declarators.
4018 ParseScope PrototypeScope(this,
4019 Scope::FunctionPrototypeScope|Scope::DeclScope);
4020 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4021 // In such a case, check if we actually have a function declarator; if it
4022 // is not, the declarator has been fully parsed.
4023 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4024 // When not in file scope, warn for ambiguous function declarators, just
4025 // in case the author intended it as a variable definition.
4026 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
4027 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
4030 ParsedAttributes attrs(AttrFactory);
4031 BalancedDelimiterTracker T(*this, tok::l_paren);
4033 ParseFunctionDeclarator(D, attrs, T);
4034 PrototypeScope.Exit();
4035 } else if (Tok.is(tok::l_square)) {
4036 ParseBracketDeclarator(D);
4043 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4044 /// only called before the identifier, so these are most likely just grouping
4045 /// parens for precedence. If we find that these are actually function
4046 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4048 /// direct-declarator:
4049 /// '(' declarator ')'
4050 /// [GNU] '(' attributes declarator ')'
4051 /// direct-declarator '(' parameter-type-list ')'
4052 /// direct-declarator '(' identifier-list[opt] ')'
4053 /// [GNU] direct-declarator '(' parameter-forward-declarations
4054 /// parameter-type-list[opt] ')'
4056 void Parser::ParseParenDeclarator(Declarator &D) {
4057 BalancedDelimiterTracker T(*this, tok::l_paren);
4060 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4062 // Eat any attributes before we look at whether this is a grouping or function
4063 // declarator paren. If this is a grouping paren, the attribute applies to
4064 // the type being built up, for example:
4065 // int (__attribute__(()) *x)(long y)
4066 // If this ends up not being a grouping paren, the attribute applies to the
4067 // first argument, for example:
4068 // int (__attribute__(()) int x)
4069 // In either case, we need to eat any attributes to be able to determine what
4070 // sort of paren this is.
4072 ParsedAttributes attrs(AttrFactory);
4073 bool RequiresArg = false;
4074 if (Tok.is(tok::kw___attribute)) {
4075 ParseGNUAttributes(attrs);
4077 // We require that the argument list (if this is a non-grouping paren) be
4078 // present even if the attribute list was empty.
4081 // Eat any Microsoft extensions.
4082 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
4083 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
4084 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
4085 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
4086 ParseMicrosoftTypeAttributes(attrs);
4088 // Eat any Borland extensions.
4089 if (Tok.is(tok::kw___pascal))
4090 ParseBorlandTypeAttributes(attrs);
4092 // If we haven't past the identifier yet (or where the identifier would be
4093 // stored, if this is an abstract declarator), then this is probably just
4094 // grouping parens. However, if this could be an abstract-declarator, then
4095 // this could also be the start of function arguments (consider 'void()').
4098 if (!D.mayOmitIdentifier()) {
4099 // If this can't be an abstract-declarator, this *must* be a grouping
4100 // paren, because we haven't seen the identifier yet.
4102 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
4103 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4104 NextToken().is(tok::r_paren)) || // C++ int(...)
4105 isDeclarationSpecifier() || // 'int(int)' is a function.
4106 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
4107 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4108 // considered to be a type, not a K&R identifier-list.
4111 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4115 // If this is a grouping paren, handle:
4116 // direct-declarator: '(' declarator ')'
4117 // direct-declarator: '(' attributes declarator ')'
4119 SourceLocation EllipsisLoc = D.getEllipsisLoc();
4120 D.setEllipsisLoc(SourceLocation());
4122 bool hadGroupingParens = D.hasGroupingParens();
4123 D.setGroupingParens(true);
4124 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4127 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4128 T.getCloseLocation()),
4129 attrs, T.getCloseLocation());
4131 D.setGroupingParens(hadGroupingParens);
4133 // An ellipsis cannot be placed outside parentheses.
4134 if (EllipsisLoc.isValid())
4135 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4140 // Okay, if this wasn't a grouping paren, it must be the start of a function
4141 // argument list. Recognize that this declarator will never have an
4142 // identifier (and remember where it would have been), then call into
4143 // ParseFunctionDeclarator to handle of argument list.
4144 D.SetIdentifier(0, Tok.getLocation());
4146 // Enter function-declaration scope, limiting any declarators to the
4147 // function prototype scope, including parameter declarators.
4148 ParseScope PrototypeScope(this,
4149 Scope::FunctionPrototypeScope|Scope::DeclScope);
4150 ParseFunctionDeclarator(D, attrs, T, RequiresArg);
4151 PrototypeScope.Exit();
4154 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
4155 /// declarator D up to a paren, which indicates that we are parsing function
4158 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
4159 /// immediately after the open paren - they should be considered to be the
4160 /// first argument of a parameter.
4162 /// If RequiresArg is true, then the first argument of the function is required
4163 /// to be present and required to not be an identifier list.
4165 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4166 /// (C++11) ref-qualifier[opt], exception-specification[opt],
4167 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4169 /// [C++11] exception-specification:
4170 /// dynamic-exception-specification
4171 /// noexcept-specification
4173 void Parser::ParseFunctionDeclarator(Declarator &D,
4174 ParsedAttributes &FirstArgAttrs,
4175 BalancedDelimiterTracker &Tracker,
4177 assert(getCurScope()->isFunctionPrototypeScope() &&
4178 "Should call from a Function scope");
4179 // lparen is already consumed!
4180 assert(D.isPastIdentifier() && "Should not call before identifier!");
4182 // This should be true when the function has typed arguments.
4183 // Otherwise, it is treated as a K&R-style function.
4184 bool HasProto = false;
4185 // Build up an array of information about the parsed arguments.
4186 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4187 // Remember where we see an ellipsis, if any.
4188 SourceLocation EllipsisLoc;
4190 DeclSpec DS(AttrFactory);
4191 bool RefQualifierIsLValueRef = true;
4192 SourceLocation RefQualifierLoc;
4193 SourceLocation ConstQualifierLoc;
4194 SourceLocation VolatileQualifierLoc;
4195 ExceptionSpecificationType ESpecType = EST_None;
4196 SourceRange ESpecRange;
4197 SmallVector<ParsedType, 2> DynamicExceptions;
4198 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4199 ExprResult NoexceptExpr;
4200 ParsedAttributes FnAttrs(AttrFactory);
4201 ParsedType TrailingReturnType;
4203 Actions.ActOnStartFunctionDeclarator();
4205 SourceLocation EndLoc;
4206 if (isFunctionDeclaratorIdentifierList()) {
4208 Diag(Tok, diag::err_argument_required_after_attribute);
4210 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
4212 Tracker.consumeClose();
4213 EndLoc = Tracker.getCloseLocation();
4215 if (Tok.isNot(tok::r_paren))
4216 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
4217 else if (RequiresArg)
4218 Diag(Tok, diag::err_argument_required_after_attribute);
4220 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
4222 // If we have the closing ')', eat it.
4223 Tracker.consumeClose();
4224 EndLoc = Tracker.getCloseLocation();
4226 if (getLangOpts().CPlusPlus) {
4227 // FIXME: Accept these components in any order, and produce fixits to
4228 // correct the order if the user gets it wrong. Ideally we should deal
4229 // with the virt-specifier-seq and pure-specifier in the same way.
4231 // Parse cv-qualifier-seq[opt].
4232 ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
4233 if (!DS.getSourceRange().getEnd().isInvalid()) {
4234 EndLoc = DS.getSourceRange().getEnd();
4235 ConstQualifierLoc = DS.getConstSpecLoc();
4236 VolatileQualifierLoc = DS.getVolatileSpecLoc();
4239 // Parse ref-qualifier[opt].
4240 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
4241 Diag(Tok, getLangOpts().CPlusPlus0x ?
4242 diag::warn_cxx98_compat_ref_qualifier :
4243 diag::ext_ref_qualifier);
4245 RefQualifierIsLValueRef = Tok.is(tok::amp);
4246 RefQualifierLoc = ConsumeToken();
4247 EndLoc = RefQualifierLoc;
4250 // C++11 [expr.prim.general]p3:
4251 // If a declaration declares a member function or member function
4252 // template of a class X, the expression this is a prvalue of type
4253 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4254 // and the end of the function-definition, member-declarator, or
4256 bool IsCXX11MemberFunction =
4257 getLangOpts().CPlusPlus0x &&
4258 (D.getContext() == Declarator::MemberContext ||
4259 (D.getContext() == Declarator::FileContext &&
4260 D.getCXXScopeSpec().isValid() &&
4261 Actions.CurContext->isRecord()));
4262 Sema::CXXThisScopeRAII ThisScope(Actions,
4263 dyn_cast<CXXRecordDecl>(Actions.CurContext),
4264 DS.getTypeQualifiers(),
4265 IsCXX11MemberFunction);
4267 // Parse exception-specification[opt].
4268 ESpecType = tryParseExceptionSpecification(ESpecRange,
4270 DynamicExceptionRanges,
4272 if (ESpecType != EST_None)
4273 EndLoc = ESpecRange.getEnd();
4275 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
4276 // after the exception-specification.
4277 MaybeParseCXX0XAttributes(FnAttrs);
4279 // Parse trailing-return-type[opt].
4280 if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
4281 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
4283 TrailingReturnType = ParseTrailingReturnType(Range).get();
4284 if (Range.getEnd().isValid())
4285 EndLoc = Range.getEnd();
4290 // Remember that we parsed a function type, and remember the attributes.
4291 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
4292 /*isVariadic=*/EllipsisLoc.isValid(),
4294 ParamInfo.data(), ParamInfo.size(),
4295 DS.getTypeQualifiers(),
4296 RefQualifierIsLValueRef,
4297 RefQualifierLoc, ConstQualifierLoc,
4298 VolatileQualifierLoc,
4299 /*MutableLoc=*/SourceLocation(),
4300 ESpecType, ESpecRange.getBegin(),
4301 DynamicExceptions.data(),
4302 DynamicExceptionRanges.data(),
4303 DynamicExceptions.size(),
4304 NoexceptExpr.isUsable() ?
4305 NoexceptExpr.get() : 0,
4306 Tracker.getOpenLocation(),
4308 TrailingReturnType),
4311 Actions.ActOnEndFunctionDeclarator();
4314 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
4315 /// identifier list form for a K&R-style function: void foo(a,b,c)
4317 /// Note that identifier-lists are only allowed for normal declarators, not for
4318 /// abstract-declarators.
4319 bool Parser::isFunctionDeclaratorIdentifierList() {
4320 return !getLangOpts().CPlusPlus
4321 && Tok.is(tok::identifier)
4322 && !TryAltiVecVectorToken()
4323 // K&R identifier lists can't have typedefs as identifiers, per C99
4325 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
4326 // Identifier lists follow a really simple grammar: the identifiers can
4327 // be followed *only* by a ", identifier" or ")". However, K&R
4328 // identifier lists are really rare in the brave new modern world, and
4329 // it is very common for someone to typo a type in a non-K&R style
4330 // list. If we are presented with something like: "void foo(intptr x,
4331 // float y)", we don't want to start parsing the function declarator as
4332 // though it is a K&R style declarator just because intptr is an
4335 // To handle this, we check to see if the token after the first
4336 // identifier is a "," or ")". Only then do we parse it as an
4338 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
4341 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
4342 /// we found a K&R-style identifier list instead of a typed parameter list.
4344 /// After returning, ParamInfo will hold the parsed parameters.
4346 /// identifier-list: [C99 6.7.5]
4348 /// identifier-list ',' identifier
4350 void Parser::ParseFunctionDeclaratorIdentifierList(
4352 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
4353 // If there was no identifier specified for the declarator, either we are in
4354 // an abstract-declarator, or we are in a parameter declarator which was found
4355 // to be abstract. In abstract-declarators, identifier lists are not valid:
4357 if (!D.getIdentifier())
4358 Diag(Tok, diag::ext_ident_list_in_param);
4360 // Maintain an efficient lookup of params we have seen so far.
4361 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
4364 // If this isn't an identifier, report the error and skip until ')'.
4365 if (Tok.isNot(tok::identifier)) {
4366 Diag(Tok, diag::err_expected_ident);
4367 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
4368 // Forget we parsed anything.
4373 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
4375 // Reject 'typedef int y; int test(x, y)', but continue parsing.
4376 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4377 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4379 // Verify that the argument identifier has not already been mentioned.
4380 if (!ParamsSoFar.insert(ParmII)) {
4381 Diag(Tok, diag::err_param_redefinition) << ParmII;
4383 // Remember this identifier in ParamInfo.
4384 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4389 // Eat the identifier.
4392 // The list continues if we see a comma.
4393 if (Tok.isNot(tok::comma))
4399 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
4400 /// after the opening parenthesis. This function will not parse a K&R-style
4401 /// identifier list.
4403 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
4404 /// caller parsed those arguments immediately after the open paren - they should
4405 /// be considered to be part of the first parameter.
4407 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
4408 /// be the location of the ellipsis, if any was parsed.
4410 /// parameter-type-list: [C99 6.7.5]
4412 /// parameter-list ',' '...'
4413 /// [C++] parameter-list '...'
4415 /// parameter-list: [C99 6.7.5]
4416 /// parameter-declaration
4417 /// parameter-list ',' parameter-declaration
4419 /// parameter-declaration: [C99 6.7.5]
4420 /// declaration-specifiers declarator
4421 /// [C++] declaration-specifiers declarator '=' assignment-expression
4422 /// [C++11] initializer-clause
4423 /// [GNU] declaration-specifiers declarator attributes
4424 /// declaration-specifiers abstract-declarator[opt]
4425 /// [C++] declaration-specifiers abstract-declarator[opt]
4426 /// '=' assignment-expression
4427 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
4428 /// [C++11] attribute-specifier-seq parameter-declaration
4430 void Parser::ParseParameterDeclarationClause(
4432 ParsedAttributes &FirstArgAttrs,
4433 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
4434 SourceLocation &EllipsisLoc) {
4437 if (Tok.is(tok::ellipsis)) {
4438 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
4439 // before deciding this was a parameter-declaration-clause.
4440 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4444 // Parse the declaration-specifiers.
4445 // Just use the ParsingDeclaration "scope" of the declarator.
4446 DeclSpec DS(AttrFactory);
4448 // Parse any C++11 attributes.
4449 MaybeParseCXX0XAttributes(DS.getAttributes());
4451 // Skip any Microsoft attributes before a param.
4452 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
4453 ParseMicrosoftAttributes(DS.getAttributes());
4455 SourceLocation DSStart = Tok.getLocation();
4457 // If the caller parsed attributes for the first argument, add them now.
4458 // Take them so that we only apply the attributes to the first parameter.
4459 // FIXME: If we can leave the attributes in the token stream somehow, we can
4460 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
4462 DS.takeAttributesFrom(FirstArgAttrs);
4464 ParseDeclarationSpecifiers(DS);
4466 // Parse the declarator. This is "PrototypeContext", because we must
4467 // accept either 'declarator' or 'abstract-declarator' here.
4468 Declarator ParmDecl(DS, Declarator::PrototypeContext);
4469 ParseDeclarator(ParmDecl);
4471 // Parse GNU attributes, if present.
4472 MaybeParseGNUAttributes(ParmDecl);
4474 // Remember this parsed parameter in ParamInfo.
4475 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
4477 // DefArgToks is used when the parsing of default arguments needs
4479 CachedTokens *DefArgToks = 0;
4481 // If no parameter was specified, verify that *something* was specified,
4482 // otherwise we have a missing type and identifier.
4483 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
4484 ParmDecl.getNumTypeObjects() == 0) {
4485 // Completely missing, emit error.
4486 Diag(DSStart, diag::err_missing_param);
4488 // Otherwise, we have something. Add it and let semantic analysis try
4489 // to grok it and add the result to the ParamInfo we are building.
4491 // Inform the actions module about the parameter declarator, so it gets
4492 // added to the current scope.
4493 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
4495 // Parse the default argument, if any. We parse the default
4496 // arguments in all dialects; the semantic analysis in
4497 // ActOnParamDefaultArgument will reject the default argument in
4499 if (Tok.is(tok::equal)) {
4500 SourceLocation EqualLoc = Tok.getLocation();
4502 // Parse the default argument
4503 if (D.getContext() == Declarator::MemberContext) {
4504 // If we're inside a class definition, cache the tokens
4505 // corresponding to the default argument. We'll actually parse
4506 // them when we see the end of the class definition.
4507 // FIXME: Can we use a smart pointer for Toks?
4508 DefArgToks = new CachedTokens;
4510 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
4511 /*StopAtSemi=*/true,
4512 /*ConsumeFinalToken=*/false)) {
4515 Actions.ActOnParamDefaultArgumentError(Param);
4517 // Mark the end of the default argument so that we know when to
4518 // stop when we parse it later on.
4520 DefArgEnd.startToken();
4521 DefArgEnd.setKind(tok::cxx_defaultarg_end);
4522 DefArgEnd.setLocation(Tok.getLocation());
4523 DefArgToks->push_back(DefArgEnd);
4524 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
4525 (*DefArgToks)[1].getLocation());
4531 // The argument isn't actually potentially evaluated unless it is
4533 EnterExpressionEvaluationContext Eval(Actions,
4534 Sema::PotentiallyEvaluatedIfUsed,
4537 ExprResult DefArgResult;
4538 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
4539 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
4540 DefArgResult = ParseBraceInitializer();
4542 DefArgResult = ParseAssignmentExpression();
4543 if (DefArgResult.isInvalid()) {
4544 Actions.ActOnParamDefaultArgumentError(Param);
4545 SkipUntil(tok::comma, tok::r_paren, true, true);
4547 // Inform the actions module about the default argument
4548 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
4549 DefArgResult.take());
4554 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4555 ParmDecl.getIdentifierLoc(), Param,
4559 // If the next token is a comma, consume it and keep reading arguments.
4560 if (Tok.isNot(tok::comma)) {
4561 if (Tok.is(tok::ellipsis)) {
4562 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4564 if (!getLangOpts().CPlusPlus) {
4565 // We have ellipsis without a preceding ',', which is ill-formed
4566 // in C. Complain and provide the fix.
4567 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
4568 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
4575 // Consume the comma.
4581 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4582 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4583 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4584 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4585 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4586 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4587 /// attribute-specifier-seq[opt]
4588 void Parser::ParseBracketDeclarator(Declarator &D) {
4589 if (CheckProhibitedCXX11Attribute())
4592 BalancedDelimiterTracker T(*this, tok::l_square);
4595 // C array syntax has many features, but by-far the most common is [] and [4].
4596 // This code does a fast path to handle some of the most obvious cases.
4597 if (Tok.getKind() == tok::r_square) {
4599 ParsedAttributes attrs(AttrFactory);
4600 MaybeParseCXX0XAttributes(attrs);
4602 // Remember that we parsed the empty array type.
4603 ExprResult NumElements;
4604 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4605 T.getOpenLocation(),
4606 T.getCloseLocation()),
4607 attrs, T.getCloseLocation());
4609 } else if (Tok.getKind() == tok::numeric_constant &&
4610 GetLookAheadToken(1).is(tok::r_square)) {
4611 // [4] is very common. Parse the numeric constant expression.
4612 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
4616 ParsedAttributes attrs(AttrFactory);
4617 MaybeParseCXX0XAttributes(attrs);
4619 // Remember that we parsed a array type, and remember its features.
4620 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4622 T.getOpenLocation(),
4623 T.getCloseLocation()),
4624 attrs, T.getCloseLocation());
4628 // If valid, this location is the position where we read the 'static' keyword.
4629 SourceLocation StaticLoc;
4630 if (Tok.is(tok::kw_static))
4631 StaticLoc = ConsumeToken();
4633 // If there is a type-qualifier-list, read it now.
4634 // Type qualifiers in an array subscript are a C99 feature.
4635 DeclSpec DS(AttrFactory);
4636 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4638 // If we haven't already read 'static', check to see if there is one after the
4639 // type-qualifier-list.
4640 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4641 StaticLoc = ConsumeToken();
4643 // Handle "direct-declarator [ type-qual-list[opt] * ]".
4644 bool isStar = false;
4645 ExprResult NumElements;
4647 // Handle the case where we have '[*]' as the array size. However, a leading
4648 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
4649 // the the token after the star is a ']'. Since stars in arrays are
4650 // infrequent, use of lookahead is not costly here.
4651 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4652 ConsumeToken(); // Eat the '*'.
4654 if (StaticLoc.isValid()) {
4655 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4656 StaticLoc = SourceLocation(); // Drop the static.
4659 } else if (Tok.isNot(tok::r_square)) {
4660 // Note, in C89, this production uses the constant-expr production instead
4661 // of assignment-expr. The only difference is that assignment-expr allows
4662 // things like '=' and '*='. Sema rejects these in C89 mode because they
4663 // are not i-c-e's, so we don't need to distinguish between the two here.
4665 // Parse the constant-expression or assignment-expression now (depending
4667 if (getLangOpts().CPlusPlus) {
4668 NumElements = ParseConstantExpression();
4670 EnterExpressionEvaluationContext Unevaluated(Actions,
4671 Sema::ConstantEvaluated);
4672 NumElements = ParseAssignmentExpression();
4676 // If there was an error parsing the assignment-expression, recover.
4677 if (NumElements.isInvalid()) {
4678 D.setInvalidType(true);
4679 // If the expression was invalid, skip it.
4680 SkipUntil(tok::r_square);
4686 ParsedAttributes attrs(AttrFactory);
4687 MaybeParseCXX0XAttributes(attrs);
4689 // Remember that we parsed a array type, and remember its features.
4690 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4691 StaticLoc.isValid(), isStar,
4692 NumElements.release(),
4693 T.getOpenLocation(),
4694 T.getCloseLocation()),
4695 attrs, T.getCloseLocation());
4698 /// [GNU] typeof-specifier:
4699 /// typeof ( expressions )
4700 /// typeof ( type-name )
4701 /// [GNU/C++] typeof unary-expression
4703 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4704 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4706 SourceLocation StartLoc = ConsumeToken();
4708 const bool hasParens = Tok.is(tok::l_paren);
4710 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
4714 SourceRange CastRange;
4715 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4718 DS.setTypeofParensRange(CastRange);
4720 if (CastRange.getEnd().isInvalid())
4721 // FIXME: Not accurate, the range gets one token more than it should.
4722 DS.SetRangeEnd(Tok.getLocation());
4724 DS.SetRangeEnd(CastRange.getEnd());
4728 DS.SetTypeSpecError();
4732 const char *PrevSpec = 0;
4734 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4735 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4737 Diag(StartLoc, DiagID) << PrevSpec;
4741 // If we get here, the operand to the typeof was an expresion.
4742 if (Operand.isInvalid()) {
4743 DS.SetTypeSpecError();
4747 // We might need to transform the operand if it is potentially evaluated.
4748 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
4749 if (Operand.isInvalid()) {
4750 DS.SetTypeSpecError();
4754 const char *PrevSpec = 0;
4756 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4757 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4758 DiagID, Operand.get()))
4759 Diag(StartLoc, DiagID) << PrevSpec;
4762 /// [C11] atomic-specifier:
4763 /// _Atomic ( type-name )
4765 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
4766 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
4768 SourceLocation StartLoc = ConsumeToken();
4769 BalancedDelimiterTracker T(*this, tok::l_paren);
4770 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
4771 SkipUntil(tok::r_paren);
4775 TypeResult Result = ParseTypeName();
4776 if (Result.isInvalid()) {
4777 SkipUntil(tok::r_paren);
4784 if (T.getCloseLocation().isInvalid())
4787 DS.setTypeofParensRange(T.getRange());
4788 DS.SetRangeEnd(T.getCloseLocation());
4790 const char *PrevSpec = 0;
4792 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
4793 DiagID, Result.release()))
4794 Diag(StartLoc, DiagID) << PrevSpec;
4798 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4799 /// from TryAltiVecVectorToken.
4800 bool Parser::TryAltiVecVectorTokenOutOfLine() {
4801 Token Next = NextToken();
4802 switch (Next.getKind()) {
4803 default: return false;
4806 case tok::kw_signed:
4807 case tok::kw_unsigned:
4812 case tok::kw_double:
4814 case tok::kw___pixel:
4815 Tok.setKind(tok::kw___vector);
4817 case tok::identifier:
4818 if (Next.getIdentifierInfo() == Ident_pixel) {
4819 Tok.setKind(tok::kw___vector);
4826 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4827 const char *&PrevSpec, unsigned &DiagID,
4829 if (Tok.getIdentifierInfo() == Ident_vector) {
4830 Token Next = NextToken();
4831 switch (Next.getKind()) {
4834 case tok::kw_signed:
4835 case tok::kw_unsigned:
4840 case tok::kw_double:
4842 case tok::kw___pixel:
4843 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4845 case tok::identifier:
4846 if (Next.getIdentifierInfo() == Ident_pixel) {
4847 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4854 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4855 DS.isTypeAltiVecVector()) {
4856 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);