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 using namespace clang;
24 //===----------------------------------------------------------------------===//
25 // C99 6.7: Declarations.
26 //===----------------------------------------------------------------------===//
29 /// type-name: [C99 6.7.6]
30 /// specifier-qualifier-list abstract-declarator[opt]
32 /// Called type-id in C++.
33 TypeResult Parser::ParseTypeName(SourceRange *Range,
34 Declarator::TheContext Context,
35 ObjCDeclSpec *objcQuals,
38 // Parse the common declaration-specifiers piece.
39 DeclSpec DS(AttrFactory);
40 DS.setObjCQualifiers(objcQuals);
41 ParseSpecifierQualifierList(DS, AS);
43 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
45 // Parse the abstract-declarator, if present.
46 Declarator DeclaratorInfo(DS, Context);
47 ParseDeclarator(DeclaratorInfo);
49 *Range = DeclaratorInfo.getSourceRange();
51 if (DeclaratorInfo.isInvalidType())
54 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
57 /// ParseGNUAttributes - Parse a non-empty attributes list.
61 /// attributes attribute
64 /// '__attribute__' '(' '(' attribute-list ')' ')'
66 /// [GNU] attribute-list:
68 /// attribute_list ',' attrib
73 /// attrib-name '(' identifier ')'
74 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
75 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
77 /// [GNU] attrib-name:
83 /// FIXME: The GCC grammar/code for this construct implies we need two
84 /// token lookahead. Comment from gcc: "If they start with an identifier
85 /// which is followed by a comma or close parenthesis, then the arguments
86 /// start with that identifier; otherwise they are an expression list."
88 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
89 /// any attributes that don't work (based on my limited testing). Most
90 /// attributes are very simple in practice. Until we find a bug, I don't see
91 /// a pressing need to implement the 2 token lookahead.
93 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
94 SourceLocation *endLoc) {
95 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
97 while (Tok.is(tok::kw___attribute)) {
99 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
101 SkipUntil(tok::r_paren, true); // skip until ) or ;
104 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
105 SkipUntil(tok::r_paren, true); // skip until ) or ;
108 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
109 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
110 Tok.is(tok::comma)) {
112 if (Tok.is(tok::comma)) {
113 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
117 // we have an identifier or declaration specifier (const, int, etc.)
118 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
119 SourceLocation AttrNameLoc = ConsumeToken();
121 // Availability attributes have their own grammar.
122 if (AttrName->isStr("availability"))
123 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, attrs, endLoc);
124 // check if we have a "parameterized" attribute
125 else if (Tok.is(tok::l_paren)) {
126 ConsumeParen(); // ignore the left paren loc for now
128 if (Tok.is(tok::identifier)) {
129 IdentifierInfo *ParmName = Tok.getIdentifierInfo();
130 SourceLocation ParmLoc = ConsumeToken();
132 if (Tok.is(tok::r_paren)) {
133 // __attribute__(( mode(byte) ))
134 ConsumeParen(); // ignore the right paren loc for now
135 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
136 ParmName, ParmLoc, 0, 0);
137 } else if (Tok.is(tok::comma)) {
139 // __attribute__(( format(printf, 1, 2) ))
140 ExprVector ArgExprs(Actions);
141 bool ArgExprsOk = true;
143 // now parse the non-empty comma separated list of expressions
145 ExprResult ArgExpr(ParseAssignmentExpression());
146 if (ArgExpr.isInvalid()) {
148 SkipUntil(tok::r_paren);
151 ArgExprs.push_back(ArgExpr.release());
153 if (Tok.isNot(tok::comma))
155 ConsumeToken(); // Eat the comma, move to the next argument
157 if (ArgExprsOk && Tok.is(tok::r_paren)) {
158 ConsumeParen(); // ignore the right paren loc for now
159 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
160 ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
163 } else { // not an identifier
164 switch (Tok.getKind()) {
166 // parse a possibly empty comma separated list of expressions
167 // __attribute__(( nonnull() ))
168 ConsumeParen(); // ignore the right paren loc for now
169 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
170 0, SourceLocation(), 0, 0);
173 case tok::kw_wchar_t:
174 case tok::kw_char16_t:
175 case tok::kw_char32_t:
180 case tok::kw___int64:
182 case tok::kw_unsigned:
186 case tok::kw_typeof: {
188 = attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
189 0, SourceLocation(), 0, 0);
190 if (attr->getKind() == AttributeList::AT_IBOutletCollection)
191 Diag(Tok, diag::err_iboutletcollection_builtintype);
192 // If it's a builtin type name, eat it and expect a rparen
193 // __attribute__(( vec_type_hint(char) ))
195 if (Tok.is(tok::r_paren))
200 // __attribute__(( aligned(16) ))
201 ExprVector ArgExprs(Actions);
202 bool ArgExprsOk = true;
204 // now parse the list of expressions
206 ExprResult ArgExpr(ParseAssignmentExpression());
207 if (ArgExpr.isInvalid()) {
209 SkipUntil(tok::r_paren);
212 ArgExprs.push_back(ArgExpr.release());
214 if (Tok.isNot(tok::comma))
216 ConsumeToken(); // Eat the comma, move to the next argument
219 if (ArgExprsOk && Tok.is(tok::r_paren)) {
220 ConsumeParen(); // ignore the right paren loc for now
221 attrs.addNew(AttrName, AttrNameLoc, 0,
222 AttrNameLoc, 0, SourceLocation(),
223 ArgExprs.take(), ArgExprs.size());
229 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
230 0, SourceLocation(), 0, 0);
233 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
234 SkipUntil(tok::r_paren, false);
235 SourceLocation Loc = Tok.getLocation();
236 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
237 SkipUntil(tok::r_paren, false);
244 /// ParseMicrosoftDeclSpec - Parse an __declspec construct
246 /// [MS] decl-specifier:
247 /// __declspec ( extended-decl-modifier-seq )
249 /// [MS] extended-decl-modifier-seq:
250 /// extended-decl-modifier[opt]
251 /// extended-decl-modifier extended-decl-modifier-seq
253 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
254 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
257 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
259 SkipUntil(tok::r_paren, true); // skip until ) or ;
263 while (Tok.getIdentifierInfo()) {
264 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
265 SourceLocation AttrNameLoc = ConsumeToken();
267 // FIXME: Remove this when we have proper __declspec(property()) support.
268 // Just skip everything inside property().
269 if (AttrName->getName() == "property") {
271 SkipUntil(tok::r_paren);
273 if (Tok.is(tok::l_paren)) {
275 // FIXME: This doesn't parse __declspec(property(get=get_func_name))
277 ExprResult ArgExpr(ParseAssignmentExpression());
278 if (!ArgExpr.isInvalid()) {
279 Expr *ExprList = ArgExpr.take();
280 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
281 SourceLocation(), &ExprList, 1, true);
283 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
284 SkipUntil(tok::r_paren, false);
286 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
287 0, SourceLocation(), 0, 0, true);
290 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
291 SkipUntil(tok::r_paren, false);
295 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
296 // Treat these like attributes
297 // FIXME: Allow Sema to distinguish between these and real attributes!
298 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
299 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
300 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) {
301 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
302 SourceLocation AttrNameLoc = ConsumeToken();
303 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
304 // FIXME: Support these properly!
306 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
307 SourceLocation(), 0, 0, true);
311 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
312 // Treat these like attributes
313 while (Tok.is(tok::kw___pascal)) {
314 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
315 SourceLocation AttrNameLoc = ConsumeToken();
316 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
317 SourceLocation(), 0, 0, true);
321 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
322 // Treat these like attributes
323 while (Tok.is(tok::kw___kernel)) {
324 SourceLocation AttrNameLoc = ConsumeToken();
325 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
326 AttrNameLoc, 0, AttrNameLoc, 0,
327 SourceLocation(), 0, 0, false);
331 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
332 SourceLocation Loc = Tok.getLocation();
333 switch(Tok.getKind()) {
334 // OpenCL qualifiers:
335 case tok::kw___private:
336 case tok::kw_private:
337 DS.getAttributes().addNewInteger(
338 Actions.getASTContext(),
339 PP.getIdentifierInfo("address_space"), Loc, 0);
342 case tok::kw___global:
343 DS.getAttributes().addNewInteger(
344 Actions.getASTContext(),
345 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
348 case tok::kw___local:
349 DS.getAttributes().addNewInteger(
350 Actions.getASTContext(),
351 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
354 case tok::kw___constant:
355 DS.getAttributes().addNewInteger(
356 Actions.getASTContext(),
357 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
360 case tok::kw___read_only:
361 DS.getAttributes().addNewInteger(
362 Actions.getASTContext(),
363 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
366 case tok::kw___write_only:
367 DS.getAttributes().addNewInteger(
368 Actions.getASTContext(),
369 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
372 case tok::kw___read_write:
373 DS.getAttributes().addNewInteger(
374 Actions.getASTContext(),
375 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
381 /// \brief Parse a version number.
385 /// simple-integer ',' simple-integer
386 /// simple-integer ',' simple-integer ',' simple-integer
387 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
388 Range = Tok.getLocation();
390 if (!Tok.is(tok::numeric_constant)) {
391 Diag(Tok, diag::err_expected_version);
392 SkipUntil(tok::comma, tok::r_paren, true, true, true);
393 return VersionTuple();
396 // Parse the major (and possibly minor and subminor) versions, which
397 // are stored in the numeric constant. We utilize a quirk of the
398 // lexer, which is that it handles something like 1.2.3 as a single
399 // numeric constant, rather than two separate tokens.
400 llvm::SmallString<512> Buffer;
401 Buffer.resize(Tok.getLength()+1);
402 const char *ThisTokBegin = &Buffer[0];
404 // Get the spelling of the token, which eliminates trigraphs, etc.
405 bool Invalid = false;
406 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
408 return VersionTuple();
410 // Parse the major version.
411 unsigned AfterMajor = 0;
413 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
414 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
418 if (AfterMajor == 0) {
419 Diag(Tok, diag::err_expected_version);
420 SkipUntil(tok::comma, tok::r_paren, true, true, true);
421 return VersionTuple();
424 if (AfterMajor == ActualLength) {
427 // We only had a single version component.
429 Diag(Tok, diag::err_zero_version);
430 return VersionTuple();
433 return VersionTuple(Major);
436 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
437 Diag(Tok, diag::err_expected_version);
438 SkipUntil(tok::comma, tok::r_paren, true, true, true);
439 return VersionTuple();
442 // Parse the minor version.
443 unsigned AfterMinor = AfterMajor + 1;
445 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
446 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
450 if (AfterMinor == ActualLength) {
453 // We had major.minor.
454 if (Major == 0 && Minor == 0) {
455 Diag(Tok, diag::err_zero_version);
456 return VersionTuple();
459 return VersionTuple(Major, Minor);
462 // If what follows is not a '.', we have a problem.
463 if (ThisTokBegin[AfterMinor] != '.') {
464 Diag(Tok, diag::err_expected_version);
465 SkipUntil(tok::comma, tok::r_paren, true, true, true);
466 return VersionTuple();
469 // Parse the subminor version.
470 unsigned AfterSubminor = AfterMinor + 1;
471 unsigned Subminor = 0;
472 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
473 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
477 if (AfterSubminor != ActualLength) {
478 Diag(Tok, diag::err_expected_version);
479 SkipUntil(tok::comma, tok::r_paren, true, true, true);
480 return VersionTuple();
483 return VersionTuple(Major, Minor, Subminor);
486 /// \brief Parse the contents of the "availability" attribute.
488 /// availability-attribute:
489 /// 'availability' '(' platform ',' version-arg-list ')'
494 /// version-arg-list:
496 /// version-arg ',' version-arg-list
499 /// 'introduced' '=' version
500 /// 'deprecated' '=' version
501 /// 'removed' = version
503 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
504 SourceLocation AvailabilityLoc,
505 ParsedAttributes &attrs,
506 SourceLocation *endLoc) {
507 SourceLocation PlatformLoc;
508 IdentifierInfo *Platform = 0;
510 enum { Introduced, Deprecated, Obsoleted, Unknown };
511 AvailabilityChange Changes[Unknown];
514 SourceLocation LParenLoc;
515 if (!Tok.is(tok::l_paren)) {
516 Diag(Tok, diag::err_expected_lparen);
519 LParenLoc = ConsumeParen();
521 // Parse the platform name,
522 if (Tok.isNot(tok::identifier)) {
523 Diag(Tok, diag::err_availability_expected_platform);
524 SkipUntil(tok::r_paren);
527 Platform = Tok.getIdentifierInfo();
528 PlatformLoc = ConsumeToken();
530 // Parse the ',' following the platform name.
531 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
534 // If we haven't grabbed the pointers for the identifiers
535 // "introduced", "deprecated", and "obsoleted", do so now.
536 if (!Ident_introduced) {
537 Ident_introduced = PP.getIdentifierInfo("introduced");
538 Ident_deprecated = PP.getIdentifierInfo("deprecated");
539 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
540 Ident_unavailable = PP.getIdentifierInfo("unavailable");
543 // Parse the set of introductions/deprecations/removals.
544 SourceLocation UnavailableLoc;
546 if (Tok.isNot(tok::identifier)) {
547 Diag(Tok, diag::err_availability_expected_change);
548 SkipUntil(tok::r_paren);
551 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
552 SourceLocation KeywordLoc = ConsumeToken();
554 if (Keyword == Ident_unavailable) {
555 if (UnavailableLoc.isValid()) {
556 Diag(KeywordLoc, diag::err_availability_redundant)
557 << Keyword << SourceRange(UnavailableLoc);
559 UnavailableLoc = KeywordLoc;
561 if (Tok.isNot(tok::comma))
568 if (Tok.isNot(tok::equal)) {
569 Diag(Tok, diag::err_expected_equal_after)
571 SkipUntil(tok::r_paren);
576 SourceRange VersionRange;
577 VersionTuple Version = ParseVersionTuple(VersionRange);
579 if (Version.empty()) {
580 SkipUntil(tok::r_paren);
585 if (Keyword == Ident_introduced)
587 else if (Keyword == Ident_deprecated)
589 else if (Keyword == Ident_obsoleted)
594 if (Index < Unknown) {
595 if (!Changes[Index].KeywordLoc.isInvalid()) {
596 Diag(KeywordLoc, diag::err_availability_redundant)
598 << SourceRange(Changes[Index].KeywordLoc,
599 Changes[Index].VersionRange.getEnd());
602 Changes[Index].KeywordLoc = KeywordLoc;
603 Changes[Index].Version = Version;
604 Changes[Index].VersionRange = VersionRange;
606 Diag(KeywordLoc, diag::err_availability_unknown_change)
607 << Keyword << VersionRange;
610 if (Tok.isNot(tok::comma))
617 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
618 if (RParenLoc.isInvalid())
624 // The 'unavailable' availability cannot be combined with any other
625 // availability changes. Make sure that hasn't happened.
626 if (UnavailableLoc.isValid()) {
627 bool Complained = false;
628 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
629 if (Changes[Index].KeywordLoc.isValid()) {
631 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
632 << SourceRange(Changes[Index].KeywordLoc,
633 Changes[Index].VersionRange.getEnd());
637 // Clear out the availability.
638 Changes[Index] = AvailabilityChange();
643 // Record this attribute
644 attrs.addNew(&Availability, AvailabilityLoc,
646 Platform, PlatformLoc,
650 UnavailableLoc, false, false);
653 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
654 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
658 /// ParseDeclaration - Parse a full 'declaration', which consists of
659 /// declaration-specifiers, some number of declarators, and a semicolon.
660 /// 'Context' should be a Declarator::TheContext value. This returns the
661 /// location of the semicolon in DeclEnd.
663 /// declaration: [C99 6.7]
664 /// block-declaration ->
665 /// simple-declaration
667 /// [C++] template-declaration
668 /// [C++] namespace-definition
669 /// [C++] using-directive
670 /// [C++] using-declaration
671 /// [C++0x/C1X] static_assert-declaration
672 /// others... [FIXME]
674 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
676 SourceLocation &DeclEnd,
677 ParsedAttributesWithRange &attrs) {
678 ParenBraceBracketBalancer BalancerRAIIObj(*this);
680 Decl *SingleDecl = 0;
682 switch (Tok.getKind()) {
683 case tok::kw_template:
685 ProhibitAttributes(attrs);
686 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
689 // Could be the start of an inline namespace. Allowed as an ext in C++03.
690 if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) {
691 ProhibitAttributes(attrs);
692 SourceLocation InlineLoc = ConsumeToken();
693 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
696 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
698 case tok::kw_namespace:
699 ProhibitAttributes(attrs);
700 SingleDecl = ParseNamespace(Context, DeclEnd);
703 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
704 DeclEnd, attrs, &OwnedType);
706 case tok::kw_static_assert:
707 case tok::kw__Static_assert:
708 ProhibitAttributes(attrs);
709 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
712 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
715 // This routine returns a DeclGroup, if the thing we parsed only contains a
716 // single decl, convert it now. Alias declarations can also declare a type;
717 // include that too if it is present.
718 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
721 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
722 /// declaration-specifiers init-declarator-list[opt] ';'
723 ///[C90/C++]init-declarator-list ';' [TODO]
724 /// [OMP] threadprivate-directive [TODO]
726 /// for-range-declaration: [C++0x 6.5p1: stmt.ranged]
727 /// attribute-specifier-seq[opt] type-specifier-seq declarator
729 /// If RequireSemi is false, this does not check for a ';' at the end of the
730 /// declaration. If it is true, it checks for and eats it.
732 /// If FRI is non-null, we might be parsing a for-range-declaration instead
733 /// of a simple-declaration. If we find that we are, we also parse the
734 /// for-range-initializer, and place it here.
735 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
737 SourceLocation &DeclEnd,
738 ParsedAttributes &attrs,
741 // Parse the common declaration-specifiers piece.
742 ParsingDeclSpec DS(*this);
743 DS.takeAttributesFrom(attrs);
745 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
746 getDeclSpecContextFromDeclaratorContext(Context));
747 StmtResult R = Actions.ActOnVlaStmt(DS);
749 Stmts.push_back(R.release());
751 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
752 // declaration-specifiers init-declarator-list[opt] ';'
753 if (Tok.is(tok::semi)) {
754 if (RequireSemi) ConsumeToken();
755 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
757 DS.complete(TheDecl);
758 return Actions.ConvertDeclToDeclGroup(TheDecl);
761 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
764 /// ParseDeclGroup - Having concluded that this is either a function
765 /// definition or a group of object declarations, actually parse the
767 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
769 bool AllowFunctionDefinitions,
770 SourceLocation *DeclEnd,
772 // Parse the first declarator.
773 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
776 // Bail out if the first declarator didn't seem well-formed.
777 if (!D.hasName() && !D.mayOmitIdentifier()) {
778 // Skip until ; or }.
779 SkipUntil(tok::r_brace, true, true);
780 if (Tok.is(tok::semi))
782 return DeclGroupPtrTy();
785 // Check to see if we have a function *definition* which must have a body.
786 if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
787 // Look at the next token to make sure that this isn't a function
788 // declaration. We have to check this because __attribute__ might be the
789 // start of a function definition in GCC-extended K&R C.
790 !isDeclarationAfterDeclarator()) {
792 if (isStartOfFunctionDefinition(D)) {
793 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
794 Diag(Tok, diag::err_function_declared_typedef);
796 // Recover by treating the 'typedef' as spurious.
797 DS.ClearStorageClassSpecs();
800 Decl *TheDecl = ParseFunctionDefinition(D);
801 return Actions.ConvertDeclToDeclGroup(TheDecl);
804 if (isDeclarationSpecifier()) {
805 // If there is an invalid declaration specifier right after the function
806 // prototype, then we must be in a missing semicolon case where this isn't
807 // actually a body. Just fall through into the code that handles it as a
808 // prototype, and let the top-level code handle the erroneous declspec
809 // where it would otherwise expect a comma or semicolon.
811 Diag(Tok, diag::err_expected_fn_body);
812 SkipUntil(tok::semi);
813 return DeclGroupPtrTy();
817 if (ParseAttributesAfterDeclarator(D))
818 return DeclGroupPtrTy();
820 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
821 // must parse and analyze the for-range-initializer before the declaration is
823 if (FRI && Tok.is(tok::colon)) {
824 FRI->ColonLoc = ConsumeToken();
825 if (Tok.is(tok::l_brace))
826 FRI->RangeExpr = ParseBraceInitializer();
828 FRI->RangeExpr = ParseExpression();
829 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
830 Actions.ActOnCXXForRangeDecl(ThisDecl);
831 Actions.FinalizeDeclaration(ThisDecl);
832 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
835 llvm::SmallVector<Decl *, 8> DeclsInGroup;
836 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
837 D.complete(FirstDecl);
839 DeclsInGroup.push_back(FirstDecl);
841 // If we don't have a comma, it is either the end of the list (a ';') or an
843 while (Tok.is(tok::comma)) {
844 // Consume the comma.
847 // Parse the next declarator.
850 // Accept attributes in an init-declarator. In the first declarator in a
851 // declaration, these would be part of the declspec. In subsequent
852 // declarators, they become part of the declarator itself, so that they
853 // don't apply to declarators after *this* one. Examples:
854 // short __attribute__((common)) var; -> declspec
855 // short var __attribute__((common)); -> declarator
856 // short x, __attribute__((common)) var; -> declarator
857 MaybeParseGNUAttributes(D);
861 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
862 D.complete(ThisDecl);
864 DeclsInGroup.push_back(ThisDecl);
868 *DeclEnd = Tok.getLocation();
870 if (Context != Declarator::ForContext &&
871 ExpectAndConsume(tok::semi,
872 Context == Declarator::FileContext
873 ? diag::err_invalid_token_after_toplevel_declarator
874 : diag::err_expected_semi_declaration)) {
875 // Okay, there was no semicolon and one was expected. If we see a
876 // declaration specifier, just assume it was missing and continue parsing.
877 // Otherwise things are very confused and we skip to recover.
878 if (!isDeclarationSpecifier()) {
879 SkipUntil(tok::r_brace, true, true);
880 if (Tok.is(tok::semi))
885 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
887 DeclsInGroup.size());
890 /// Parse an optional simple-asm-expr and attributes, and attach them to a
891 /// declarator. Returns true on an error.
892 bool Parser::ParseAttributesAfterDeclarator(Declarator &D) {
893 // If a simple-asm-expr is present, parse it.
894 if (Tok.is(tok::kw_asm)) {
896 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
897 if (AsmLabel.isInvalid()) {
898 SkipUntil(tok::semi, true, true);
902 D.setAsmLabel(AsmLabel.release());
906 MaybeParseGNUAttributes(D);
910 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
911 /// declarator'. This method parses the remainder of the declaration
912 /// (including any attributes or initializer, among other things) and
913 /// finalizes the declaration.
915 /// init-declarator: [C99 6.7]
917 /// declarator '=' initializer
918 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
919 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
920 /// [C++] declarator initializer[opt]
922 /// [C++] initializer:
923 /// [C++] '=' initializer-clause
924 /// [C++] '(' expression-list ')'
925 /// [C++0x] '=' 'default' [TODO]
926 /// [C++0x] '=' 'delete'
927 /// [C++0x] braced-init-list
929 /// According to the standard grammar, =default and =delete are function
930 /// definitions, but that definitely doesn't fit with the parser here.
932 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
933 const ParsedTemplateInfo &TemplateInfo) {
934 if (ParseAttributesAfterDeclarator(D))
937 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
940 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
941 const ParsedTemplateInfo &TemplateInfo) {
942 // Inform the current actions module that we just parsed this declarator.
944 switch (TemplateInfo.Kind) {
945 case ParsedTemplateInfo::NonTemplate:
946 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
949 case ParsedTemplateInfo::Template:
950 case ParsedTemplateInfo::ExplicitSpecialization:
951 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
952 MultiTemplateParamsArg(Actions,
953 TemplateInfo.TemplateParams->data(),
954 TemplateInfo.TemplateParams->size()),
958 case ParsedTemplateInfo::ExplicitInstantiation: {
960 = Actions.ActOnExplicitInstantiation(getCurScope(),
961 TemplateInfo.ExternLoc,
962 TemplateInfo.TemplateLoc,
964 if (ThisRes.isInvalid()) {
965 SkipUntil(tok::semi, true, true);
969 ThisDecl = ThisRes.get();
974 bool TypeContainsAuto =
975 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
977 // Parse declarator '=' initializer.
978 if (isTokenEqualOrMistypedEqualEqual(
979 diag::err_invalid_equalequal_after_declarator)) {
981 if (Tok.is(tok::kw_delete)) {
982 if (D.isFunctionDeclarator())
983 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
986 Diag(ConsumeToken(), diag::err_deleted_non_function);
987 } else if (Tok.is(tok::kw_default)) {
988 if (D.isFunctionDeclarator())
989 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
992 Diag(ConsumeToken(), diag::err_default_special_members);
994 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
996 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
999 if (Tok.is(tok::code_completion)) {
1000 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1001 ConsumeCodeCompletionToken();
1002 SkipUntil(tok::comma, true, true);
1006 ExprResult Init(ParseInitializer());
1008 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1009 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1013 if (Init.isInvalid()) {
1014 SkipUntil(tok::comma, true, true);
1015 Actions.ActOnInitializerError(ThisDecl);
1017 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1018 /*DirectInit=*/false, TypeContainsAuto);
1020 } else if (Tok.is(tok::l_paren)) {
1021 // Parse C++ direct initializer: '(' expression-list ')'
1022 SourceLocation LParenLoc = ConsumeParen();
1023 ExprVector Exprs(Actions);
1024 CommaLocsTy CommaLocs;
1026 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1028 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1031 if (ParseExpressionList(Exprs, CommaLocs)) {
1032 SkipUntil(tok::r_paren);
1034 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1035 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1040 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1042 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1043 "Unexpected number of commas!");
1045 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1046 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1050 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
1055 } else if (getLang().CPlusPlus0x && Tok.is(tok::l_brace)) {
1056 // Parse C++0x braced-init-list.
1057 if (D.getCXXScopeSpec().isSet()) {
1059 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1062 ExprResult Init(ParseBraceInitializer());
1064 if (D.getCXXScopeSpec().isSet()) {
1065 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1069 if (Init.isInvalid()) {
1070 Actions.ActOnInitializerError(ThisDecl);
1072 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1073 /*DirectInit=*/true, TypeContainsAuto);
1076 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1079 Actions.FinalizeDeclaration(ThisDecl);
1084 /// ParseSpecifierQualifierList
1085 /// specifier-qualifier-list:
1086 /// type-specifier specifier-qualifier-list[opt]
1087 /// type-qualifier specifier-qualifier-list[opt]
1088 /// [GNU] attributes specifier-qualifier-list[opt]
1090 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS) {
1091 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1092 /// parse declaration-specifiers and complain about extra stuff.
1093 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS);
1095 // Validate declspec for type-name.
1096 unsigned Specs = DS.getParsedSpecifiers();
1097 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1098 !DS.hasAttributes())
1099 Diag(Tok, diag::err_typename_requires_specqual);
1101 // Issue diagnostic and remove storage class if present.
1102 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1103 if (DS.getStorageClassSpecLoc().isValid())
1104 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1106 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1107 DS.ClearStorageClassSpecs();
1110 // Issue diagnostic and remove function specfier if present.
1111 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1112 if (DS.isInlineSpecified())
1113 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1114 if (DS.isVirtualSpecified())
1115 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1116 if (DS.isExplicitSpecified())
1117 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1118 DS.ClearFunctionSpecs();
1122 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1123 /// specified token is valid after the identifier in a declarator which
1124 /// immediately follows the declspec. For example, these things are valid:
1126 /// int x [ 4]; // direct-declarator
1127 /// int x ( int y); // direct-declarator
1128 /// int(int x ) // direct-declarator
1129 /// int x ; // simple-declaration
1130 /// int x = 17; // init-declarator-list
1131 /// int x , y; // init-declarator-list
1132 /// int x __asm__ ("foo"); // init-declarator-list
1133 /// int x : 4; // struct-declarator
1134 /// int x { 5}; // C++'0x unified initializers
1136 /// This is not, because 'x' does not immediately follow the declspec (though
1137 /// ')' happens to be valid anyway).
1140 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1141 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1142 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1143 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1147 /// ParseImplicitInt - This method is called when we have an non-typename
1148 /// identifier in a declspec (which normally terminates the decl spec) when
1149 /// the declspec has no type specifier. In this case, the declspec is either
1150 /// malformed or is "implicit int" (in K&R and C89).
1152 /// This method handles diagnosing this prettily and returns false if the
1153 /// declspec is done being processed. If it recovers and thinks there may be
1154 /// other pieces of declspec after it, it returns true.
1156 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1157 const ParsedTemplateInfo &TemplateInfo,
1158 AccessSpecifier AS) {
1159 assert(Tok.is(tok::identifier) && "should have identifier");
1161 SourceLocation Loc = Tok.getLocation();
1162 // If we see an identifier that is not a type name, we normally would
1163 // parse it as the identifer being declared. However, when a typename
1164 // is typo'd or the definition is not included, this will incorrectly
1165 // parse the typename as the identifier name and fall over misparsing
1166 // later parts of the diagnostic.
1168 // As such, we try to do some look-ahead in cases where this would
1169 // otherwise be an "implicit-int" case to see if this is invalid. For
1170 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
1171 // an identifier with implicit int, we'd get a parse error because the
1172 // next token is obviously invalid for a type. Parse these as a case
1173 // with an invalid type specifier.
1174 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1176 // Since we know that this either implicit int (which is rare) or an
1177 // error, we'd do lookahead to try to do better recovery.
1178 if (isValidAfterIdentifierInDeclarator(NextToken())) {
1179 // If this token is valid for implicit int, e.g. "static x = 4", then
1180 // we just avoid eating the identifier, so it will be parsed as the
1181 // identifier in the declarator.
1185 // Otherwise, if we don't consume this token, we are going to emit an
1186 // error anyway. Try to recover from various common problems. Check
1187 // to see if this was a reference to a tag name without a tag specified.
1188 // This is a common problem in C (saying 'foo' instead of 'struct foo').
1190 // C++ doesn't need this, and isTagName doesn't take SS.
1192 const char *TagName = 0, *FixitTagName = 0;
1193 tok::TokenKind TagKind = tok::unknown;
1195 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1197 case DeclSpec::TST_enum:
1198 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
1199 case DeclSpec::TST_union:
1200 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1201 case DeclSpec::TST_struct:
1202 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1203 case DeclSpec::TST_class:
1204 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1208 Diag(Loc, diag::err_use_of_tag_name_without_tag)
1209 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
1210 << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
1212 // Parse this as a tag as if the missing tag were present.
1213 if (TagKind == tok::kw_enum)
1214 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1216 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
1221 // This is almost certainly an invalid type name. Let the action emit a
1222 // diagnostic and attempt to recover.
1224 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1225 getCurScope(), SS, T)) {
1226 // The action emitted a diagnostic, so we don't have to.
1228 // The action has suggested that the type T could be used. Set that as
1229 // the type in the declaration specifiers, consume the would-be type
1230 // name token, and we're done.
1231 const char *PrevSpec;
1233 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1234 DS.SetRangeEnd(Tok.getLocation());
1237 // There may be other declaration specifiers after this.
1241 // Fall through; the action had no suggestion for us.
1243 // The action did not emit a diagnostic, so emit one now.
1245 if (SS) R = SS->getRange();
1246 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1249 // Mark this as an error.
1250 const char *PrevSpec;
1252 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
1253 DS.SetRangeEnd(Tok.getLocation());
1256 // TODO: Could inject an invalid typedef decl in an enclosing scope to
1257 // avoid rippling error messages on subsequent uses of the same type,
1258 // could be useful if #include was forgotten.
1262 /// \brief Determine the declaration specifier context from the declarator
1265 /// \param Context the declarator context, which is one of the
1266 /// Declarator::TheContext enumerator values.
1267 Parser::DeclSpecContext
1268 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1269 if (Context == Declarator::MemberContext)
1271 if (Context == Declarator::FileContext)
1272 return DSC_top_level;
1276 /// ParseDeclarationSpecifiers
1277 /// declaration-specifiers: [C99 6.7]
1278 /// storage-class-specifier declaration-specifiers[opt]
1279 /// type-specifier declaration-specifiers[opt]
1280 /// [C99] function-specifier declaration-specifiers[opt]
1281 /// [GNU] attributes declaration-specifiers[opt]
1283 /// storage-class-specifier: [C99 6.7.1]
1290 /// [GNU] '__thread'
1291 /// function-specifier: [C99 6.7.4]
1294 /// [C++] 'explicit'
1295 /// [OpenCL] '__kernel'
1296 /// 'friend': [C++ dcl.friend]
1297 /// 'constexpr': [C++0x dcl.constexpr]
1300 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1301 const ParsedTemplateInfo &TemplateInfo,
1303 DeclSpecContext DSContext) {
1304 if (DS.getSourceRange().isInvalid()) {
1305 DS.SetRangeStart(Tok.getLocation());
1306 DS.SetRangeEnd(Tok.getLocation());
1310 bool isInvalid = false;
1311 const char *PrevSpec = 0;
1312 unsigned DiagID = 0;
1314 SourceLocation Loc = Tok.getLocation();
1316 switch (Tok.getKind()) {
1319 // If this is not a declaration specifier token, we're done reading decl
1320 // specifiers. First verify that DeclSpec's are consistent.
1321 DS.Finish(Diags, PP);
1324 case tok::code_completion: {
1325 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1326 if (DS.hasTypeSpecifier()) {
1327 bool AllowNonIdentifiers
1328 = (getCurScope()->getFlags() & (Scope::ControlScope |
1330 Scope::TemplateParamScope |
1331 Scope::FunctionPrototypeScope |
1332 Scope::AtCatchScope)) == 0;
1333 bool AllowNestedNameSpecifiers
1334 = DSContext == DSC_top_level ||
1335 (DSContext == DSC_class && DS.isFriendSpecified());
1337 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1338 AllowNonIdentifiers,
1339 AllowNestedNameSpecifiers);
1340 ConsumeCodeCompletionToken();
1344 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1345 CCC = Sema::PCC_LocalDeclarationSpecifiers;
1346 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1347 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1348 : Sema::PCC_Template;
1349 else if (DSContext == DSC_class)
1350 CCC = Sema::PCC_Class;
1351 else if (ObjCImpDecl)
1352 CCC = Sema::PCC_ObjCImplementation;
1354 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1355 ConsumeCodeCompletionToken();
1359 case tok::coloncolon: // ::foo::bar
1360 // C++ scope specifier. Annotate and loop, or bail out on error.
1361 if (TryAnnotateCXXScopeToken(true)) {
1362 if (!DS.hasTypeSpecifier())
1363 DS.SetTypeSpecError();
1364 goto DoneWithDeclSpec;
1366 if (Tok.is(tok::coloncolon)) // ::new or ::delete
1367 goto DoneWithDeclSpec;
1370 case tok::annot_cxxscope: {
1371 if (DS.hasTypeSpecifier())
1372 goto DoneWithDeclSpec;
1375 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1376 Tok.getAnnotationRange(),
1379 // We are looking for a qualified typename.
1380 Token Next = NextToken();
1381 if (Next.is(tok::annot_template_id) &&
1382 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1383 ->Kind == TNK_Type_template) {
1384 // We have a qualified template-id, e.g., N::A<int>
1386 // C++ [class.qual]p2:
1387 // In a lookup in which the constructor is an acceptable lookup
1388 // result and the nested-name-specifier nominates a class C:
1390 // - if the name specified after the
1391 // nested-name-specifier, when looked up in C, is the
1392 // injected-class-name of C (Clause 9), or
1394 // - if the name specified after the nested-name-specifier
1395 // is the same as the identifier or the
1396 // simple-template-id's template-name in the last
1397 // component of the nested-name-specifier,
1399 // the name is instead considered to name the constructor of
1402 // Thus, if the template-name is actually the constructor
1403 // name, then the code is ill-formed; this interpretation is
1404 // reinforced by the NAD status of core issue 635.
1405 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1406 if ((DSContext == DSC_top_level ||
1407 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1409 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1410 if (isConstructorDeclarator()) {
1411 // The user meant this to be an out-of-line constructor
1412 // definition, but template arguments are not allowed
1413 // there. Just allow this as a constructor; we'll
1414 // complain about it later.
1415 goto DoneWithDeclSpec;
1418 // The user meant this to name a type, but it actually names
1419 // a constructor with some extraneous template
1420 // arguments. Complain, then parse it as a type as the user
1422 Diag(TemplateId->TemplateNameLoc,
1423 diag::err_out_of_line_template_id_names_constructor)
1424 << TemplateId->Name;
1427 DS.getTypeSpecScope() = SS;
1428 ConsumeToken(); // The C++ scope.
1429 assert(Tok.is(tok::annot_template_id) &&
1430 "ParseOptionalCXXScopeSpecifier not working");
1431 AnnotateTemplateIdTokenAsType();
1435 if (Next.is(tok::annot_typename)) {
1436 DS.getTypeSpecScope() = SS;
1437 ConsumeToken(); // The C++ scope.
1438 if (Tok.getAnnotationValue()) {
1439 ParsedType T = getTypeAnnotation(Tok);
1440 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1441 Tok.getAnnotationEndLoc(),
1442 PrevSpec, DiagID, T);
1445 DS.SetTypeSpecError();
1446 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1447 ConsumeToken(); // The typename
1450 if (Next.isNot(tok::identifier))
1451 goto DoneWithDeclSpec;
1453 // If we're in a context where the identifier could be a class name,
1454 // check whether this is a constructor declaration.
1455 if ((DSContext == DSC_top_level ||
1456 (DSContext == DSC_class && DS.isFriendSpecified())) &&
1457 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
1459 if (isConstructorDeclarator())
1460 goto DoneWithDeclSpec;
1462 // As noted in C++ [class.qual]p2 (cited above), when the name
1463 // of the class is qualified in a context where it could name
1464 // a constructor, its a constructor name. However, we've
1465 // looked at the declarator, and the user probably meant this
1466 // to be a type. Complain that it isn't supposed to be treated
1467 // as a type, then proceed to parse it as a type.
1468 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
1469 << Next.getIdentifierInfo();
1472 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
1475 false, false, ParsedType(),
1476 /*NonTrivialSourceInfo=*/true);
1478 // If the referenced identifier is not a type, then this declspec is
1479 // erroneous: We already checked about that it has no type specifier, and
1480 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
1483 ConsumeToken(); // Eat the scope spec so the identifier is current.
1484 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
1485 goto DoneWithDeclSpec;
1488 DS.getTypeSpecScope() = SS;
1489 ConsumeToken(); // The C++ scope.
1491 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1496 DS.SetRangeEnd(Tok.getLocation());
1497 ConsumeToken(); // The typename.
1502 case tok::annot_typename: {
1503 if (Tok.getAnnotationValue()) {
1504 ParsedType T = getTypeAnnotation(Tok);
1505 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1508 DS.SetTypeSpecError();
1513 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1514 ConsumeToken(); // The typename
1516 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1517 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1518 // Objective-C interface.
1519 if (Tok.is(tok::less) && getLang().ObjC1)
1520 ParseObjCProtocolQualifiers(DS);
1525 case tok::kw___is_signed:
1526 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
1527 // typically treats it as a trait. If we see __is_signed as it appears
1528 // in libstdc++, e.g.,
1530 // static const bool __is_signed;
1532 // then treat __is_signed as an identifier rather than as a keyword.
1533 if (DS.getTypeSpecType() == TST_bool &&
1534 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
1535 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1536 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1537 Tok.setKind(tok::identifier);
1540 // We're done with the declaration-specifiers.
1541 goto DoneWithDeclSpec;
1544 case tok::identifier: {
1545 // In C++, check to see if this is a scope specifier like foo::bar::, if
1546 // so handle it as such. This is important for ctor parsing.
1547 if (getLang().CPlusPlus) {
1548 if (TryAnnotateCXXScopeToken(true)) {
1549 if (!DS.hasTypeSpecifier())
1550 DS.SetTypeSpecError();
1551 goto DoneWithDeclSpec;
1553 if (!Tok.is(tok::identifier))
1557 // This identifier can only be a typedef name if we haven't already seen
1558 // a type-specifier. Without this check we misparse:
1559 // typedef int X; struct Y { short X; }; as 'short int'.
1560 if (DS.hasTypeSpecifier())
1561 goto DoneWithDeclSpec;
1563 // Check for need to substitute AltiVec keyword tokens.
1564 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1567 // It has to be available as a typedef too!
1568 ParsedType TypeRep =
1569 Actions.getTypeName(*Tok.getIdentifierInfo(),
1570 Tok.getLocation(), getCurScope());
1572 // If this is not a typedef name, don't parse it as part of the declspec,
1573 // it must be an implicit int or an error.
1575 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1576 goto DoneWithDeclSpec;
1579 // If we're in a context where the identifier could be a class name,
1580 // check whether this is a constructor declaration.
1581 if (getLang().CPlusPlus && DSContext == DSC_class &&
1582 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
1583 isConstructorDeclarator())
1584 goto DoneWithDeclSpec;
1586 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1591 DS.SetRangeEnd(Tok.getLocation());
1592 ConsumeToken(); // The identifier
1594 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1595 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1596 // Objective-C interface.
1597 if (Tok.is(tok::less) && getLang().ObjC1)
1598 ParseObjCProtocolQualifiers(DS);
1600 // Need to support trailing type qualifiers (e.g. "id<p> const").
1601 // If a type specifier follows, it will be diagnosed elsewhere.
1606 case tok::annot_template_id: {
1607 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1608 if (TemplateId->Kind != TNK_Type_template) {
1609 // This template-id does not refer to a type name, so we're
1610 // done with the type-specifiers.
1611 goto DoneWithDeclSpec;
1614 // If we're in a context where the template-id could be a
1615 // constructor name or specialization, check whether this is a
1616 // constructor declaration.
1617 if (getLang().CPlusPlus && DSContext == DSC_class &&
1618 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
1619 isConstructorDeclarator())
1620 goto DoneWithDeclSpec;
1622 // Turn the template-id annotation token into a type annotation
1623 // token, then try again to parse it as a type-specifier.
1624 AnnotateTemplateIdTokenAsType();
1628 // GNU attributes support.
1629 case tok::kw___attribute:
1630 ParseGNUAttributes(DS.getAttributes());
1633 // Microsoft declspec support.
1634 case tok::kw___declspec:
1635 ParseMicrosoftDeclSpec(DS.getAttributes());
1638 // Microsoft single token adornments.
1639 case tok::kw___forceinline:
1640 // FIXME: Add handling here!
1643 case tok::kw___ptr64:
1645 case tok::kw___cdecl:
1646 case tok::kw___stdcall:
1647 case tok::kw___fastcall:
1648 case tok::kw___thiscall:
1649 ParseMicrosoftTypeAttributes(DS.getAttributes());
1652 // Borland single token adornments.
1653 case tok::kw___pascal:
1654 ParseBorlandTypeAttributes(DS.getAttributes());
1657 // OpenCL single token adornments.
1658 case tok::kw___kernel:
1659 ParseOpenCLAttributes(DS.getAttributes());
1662 // storage-class-specifier
1663 case tok::kw_typedef:
1664 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1667 case tok::kw_extern:
1668 if (DS.isThreadSpecified())
1669 Diag(Tok, diag::ext_thread_before) << "extern";
1670 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1673 case tok::kw___private_extern__:
1674 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1675 PrevSpec, DiagID, getLang());
1677 case tok::kw_static:
1678 if (DS.isThreadSpecified())
1679 Diag(Tok, diag::ext_thread_before) << "static";
1680 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1684 if (getLang().CPlusPlus0x) {
1685 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
1686 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1689 Diag(Tok, diag::auto_storage_class)
1690 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
1693 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1697 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1700 case tok::kw_register:
1701 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1704 case tok::kw_mutable:
1705 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1708 case tok::kw___thread:
1709 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1712 // function-specifier
1713 case tok::kw_inline:
1714 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1716 case tok::kw_virtual:
1717 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1719 case tok::kw_explicit:
1720 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1724 case tok::kw_friend:
1725 if (DSContext == DSC_class)
1726 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1728 PrevSpec = ""; // not actually used by the diagnostic
1729 DiagID = diag::err_friend_invalid_in_context;
1735 case tok::kw_constexpr:
1736 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1741 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1745 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1746 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1749 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1752 case tok::kw___int64:
1753 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1756 case tok::kw_signed:
1757 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1760 case tok::kw_unsigned:
1761 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1764 case tok::kw__Complex:
1765 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1768 case tok::kw__Imaginary:
1769 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1773 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1777 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1781 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1785 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1788 case tok::kw_double:
1789 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1792 case tok::kw_wchar_t:
1793 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1796 case tok::kw_char16_t:
1797 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1800 case tok::kw_char32_t:
1801 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1806 if (Tok.is(tok::kw_bool) &&
1807 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
1808 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1809 PrevSpec = ""; // Not used by the diagnostic.
1810 DiagID = diag::err_bool_redeclaration;
1811 // For better error recovery.
1812 Tok.setKind(tok::identifier);
1815 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1819 case tok::kw__Decimal32:
1820 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1823 case tok::kw__Decimal64:
1824 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1827 case tok::kw__Decimal128:
1828 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1831 case tok::kw___vector:
1832 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1834 case tok::kw___pixel:
1835 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1837 case tok::kw___unknown_anytype:
1838 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
1844 case tok::kw_struct:
1845 case tok::kw_union: {
1846 tok::TokenKind Kind = Tok.getKind();
1848 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1855 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1860 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1863 case tok::kw_volatile:
1864 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1867 case tok::kw_restrict:
1868 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1872 // C++ typename-specifier:
1873 case tok::kw_typename:
1874 if (TryAnnotateTypeOrScopeToken()) {
1875 DS.SetTypeSpecError();
1876 goto DoneWithDeclSpec;
1878 if (!Tok.is(tok::kw_typename))
1882 // GNU typeof support.
1883 case tok::kw_typeof:
1884 ParseTypeofSpecifier(DS);
1887 case tok::kw_decltype:
1888 ParseDecltypeSpecifier(DS);
1891 case tok::kw___underlying_type:
1892 ParseUnderlyingTypeSpecifier(DS);
1894 // OpenCL qualifiers:
1895 case tok::kw_private:
1896 if (!getLang().OpenCL)
1897 goto DoneWithDeclSpec;
1898 case tok::kw___private:
1899 case tok::kw___global:
1900 case tok::kw___local:
1901 case tok::kw___constant:
1902 case tok::kw___read_only:
1903 case tok::kw___write_only:
1904 case tok::kw___read_write:
1905 ParseOpenCLQualifiers(DS);
1909 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1910 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
1911 // but we support it.
1912 if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1913 goto DoneWithDeclSpec;
1915 if (!ParseObjCProtocolQualifiers(DS))
1916 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1917 << FixItHint::CreateInsertion(Loc, "id")
1918 << SourceRange(Loc, DS.getSourceRange().getEnd());
1920 // Need to support trailing type qualifiers (e.g. "id<p> const").
1921 // If a type specifier follows, it will be diagnosed elsewhere.
1924 // If the specifier wasn't legal, issue a diagnostic.
1926 assert(PrevSpec && "Method did not return previous specifier!");
1929 if (DiagID == diag::ext_duplicate_declspec)
1931 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
1933 Diag(Tok, DiagID) << PrevSpec;
1936 DS.SetRangeEnd(Tok.getLocation());
1937 if (DiagID != diag::err_bool_redeclaration)
1942 /// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1943 /// primarily follow the C++ grammar with additions for C99 and GNU,
1944 /// which together subsume the C grammar. Note that the C++
1945 /// type-specifier also includes the C type-qualifier (for const,
1946 /// volatile, and C99 restrict). Returns true if a type-specifier was
1947 /// found (and parsed), false otherwise.
1949 /// type-specifier: [C++ 7.1.5]
1950 /// simple-type-specifier
1953 /// elaborated-type-specifier [TODO]
1956 /// cv-qualifier: [C++ 7.1.5.1]
1959 /// [C99] 'restrict'
1961 /// simple-type-specifier: [ C++ 7.1.5.2]
1962 /// '::'[opt] nested-name-specifier[opt] type-name [TODO]
1963 /// '::'[opt] nested-name-specifier 'template' template-id [TODO]
1976 /// [C99] '_Complex'
1977 /// [C99] '_Imaginary' // Removed in TC2?
1978 /// [GNU] '_Decimal32'
1979 /// [GNU] '_Decimal64'
1980 /// [GNU] '_Decimal128'
1981 /// [GNU] typeof-specifier
1982 /// [OBJC] class-name objc-protocol-refs[opt] [TODO]
1983 /// [OBJC] typedef-name objc-protocol-refs[opt] [TODO]
1984 /// [C++0x] 'decltype' ( expression )
1985 /// [AltiVec] '__vector'
1986 bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1987 const char *&PrevSpec,
1989 const ParsedTemplateInfo &TemplateInfo,
1990 bool SuppressDeclarations) {
1991 SourceLocation Loc = Tok.getLocation();
1993 switch (Tok.getKind()) {
1994 case tok::identifier: // foo::bar
1995 // If we already have a type specifier, this identifier is not a type.
1996 if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1997 DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1998 DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
2000 // Check for need to substitute AltiVec keyword tokens.
2001 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2004 case tok::kw_typename: // typename foo::bar
2005 // Annotate typenames and C++ scope specifiers. If we get one, just
2006 // recurse to handle whatever we get.
2007 if (TryAnnotateTypeOrScopeToken())
2009 if (Tok.is(tok::identifier))
2011 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
2012 TemplateInfo, SuppressDeclarations);
2013 case tok::coloncolon: // ::foo::bar
2014 if (NextToken().is(tok::kw_new) || // ::new
2015 NextToken().is(tok::kw_delete)) // ::delete
2018 // Annotate typenames and C++ scope specifiers. If we get one, just
2019 // recurse to handle whatever we get.
2020 if (TryAnnotateTypeOrScopeToken())
2022 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
2023 TemplateInfo, SuppressDeclarations);
2025 // simple-type-specifier:
2026 case tok::annot_typename: {
2027 if (ParsedType T = getTypeAnnotation(Tok)) {
2028 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2029 Tok.getAnnotationEndLoc(), PrevSpec,
2032 DS.SetTypeSpecError();
2033 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2034 ConsumeToken(); // The typename
2036 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2037 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2038 // Objective-C interface. If we don't have Objective-C or a '<', this is
2039 // just a normal reference to a typedef name.
2040 if (Tok.is(tok::less) && getLang().ObjC1)
2041 ParseObjCProtocolQualifiers(DS);
2047 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
2050 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2051 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2054 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2057 case tok::kw___int64:
2058 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2061 case tok::kw_signed:
2062 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
2064 case tok::kw_unsigned:
2065 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2068 case tok::kw__Complex:
2069 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2072 case tok::kw__Imaginary:
2073 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2077 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
2080 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
2083 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
2086 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
2088 case tok::kw_double:
2089 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
2091 case tok::kw_wchar_t:
2092 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
2094 case tok::kw_char16_t:
2095 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
2097 case tok::kw_char32_t:
2098 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
2102 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
2104 case tok::kw__Decimal32:
2105 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2108 case tok::kw__Decimal64:
2109 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2112 case tok::kw__Decimal128:
2113 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2116 case tok::kw___vector:
2117 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2119 case tok::kw___pixel:
2120 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2125 case tok::kw_struct:
2126 case tok::kw_union: {
2127 tok::TokenKind Kind = Tok.getKind();
2129 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
2130 SuppressDeclarations);
2137 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
2142 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec,
2145 case tok::kw_volatile:
2146 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
2149 case tok::kw_restrict:
2150 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
2154 // GNU typeof support.
2155 case tok::kw_typeof:
2156 ParseTypeofSpecifier(DS);
2159 // C++0x decltype support.
2160 case tok::kw_decltype:
2161 ParseDecltypeSpecifier(DS);
2164 // C++0x type traits support.
2165 case tok::kw___underlying_type:
2166 ParseUnderlyingTypeSpecifier(DS);
2169 // OpenCL qualifiers:
2170 case tok::kw_private:
2171 if (!getLang().OpenCL)
2173 case tok::kw___private:
2174 case tok::kw___global:
2175 case tok::kw___local:
2176 case tok::kw___constant:
2177 case tok::kw___read_only:
2178 case tok::kw___write_only:
2179 case tok::kw___read_write:
2180 ParseOpenCLQualifiers(DS);
2183 // C++0x auto support.
2185 if (!getLang().CPlusPlus0x)
2188 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
2191 case tok::kw___ptr64:
2193 case tok::kw___cdecl:
2194 case tok::kw___stdcall:
2195 case tok::kw___fastcall:
2196 case tok::kw___thiscall:
2197 ParseMicrosoftTypeAttributes(DS.getAttributes());
2200 case tok::kw___pascal:
2201 ParseBorlandTypeAttributes(DS.getAttributes());
2205 // Not a type-specifier; do nothing.
2209 // If the specifier combination wasn't legal, issue a diagnostic.
2211 assert(PrevSpec && "Method did not return previous specifier!");
2212 // Pick between error or extwarn.
2213 Diag(Tok, DiagID) << PrevSpec;
2215 DS.SetRangeEnd(Tok.getLocation());
2216 ConsumeToken(); // whatever we parsed above.
2220 /// ParseStructDeclaration - Parse a struct declaration without the terminating
2223 /// struct-declaration:
2224 /// specifier-qualifier-list struct-declarator-list
2225 /// [GNU] __extension__ struct-declaration
2226 /// [GNU] specifier-qualifier-list
2227 /// struct-declarator-list:
2228 /// struct-declarator
2229 /// struct-declarator-list ',' struct-declarator
2230 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
2231 /// struct-declarator:
2233 /// [GNU] declarator attributes[opt]
2234 /// declarator[opt] ':' constant-expression
2235 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
2238 ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2239 if (Tok.is(tok::kw___extension__)) {
2240 // __extension__ silences extension warnings in the subexpression.
2241 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2243 return ParseStructDeclaration(DS, Fields);
2246 // Parse the common specifier-qualifiers-list piece.
2247 ParseSpecifierQualifierList(DS);
2249 // If there are no declarators, this is a free-standing declaration
2250 // specifier. Let the actions module cope with it.
2251 if (Tok.is(tok::semi)) {
2252 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2256 // Read struct-declarators until we find the semicolon.
2257 bool FirstDeclarator = true;
2259 ParsingDeclRAIIObject PD(*this);
2260 FieldDeclarator DeclaratorInfo(DS);
2262 // Attributes are only allowed here on successive declarators.
2263 if (!FirstDeclarator)
2264 MaybeParseGNUAttributes(DeclaratorInfo.D);
2266 /// struct-declarator: declarator
2267 /// struct-declarator: declarator[opt] ':' constant-expression
2268 if (Tok.isNot(tok::colon)) {
2269 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2270 ColonProtectionRAIIObject X(*this);
2271 ParseDeclarator(DeclaratorInfo.D);
2274 if (Tok.is(tok::colon)) {
2276 ExprResult Res(ParseConstantExpression());
2277 if (Res.isInvalid())
2278 SkipUntil(tok::semi, true, true);
2280 DeclaratorInfo.BitfieldSize = Res.release();
2283 // If attributes exist after the declarator, parse them.
2284 MaybeParseGNUAttributes(DeclaratorInfo.D);
2286 // We're done with this declarator; invoke the callback.
2287 Decl *D = Fields.invoke(DeclaratorInfo);
2290 // If we don't have a comma, it is either the end of the list (a ';')
2291 // or an error, bail out.
2292 if (Tok.isNot(tok::comma))
2295 // Consume the comma.
2298 FirstDeclarator = false;
2302 /// ParseStructUnionBody
2303 /// struct-contents:
2304 /// struct-declaration-list
2306 /// [GNU] "struct-declaration-list" without terminatoring ';'
2307 /// struct-declaration-list:
2308 /// struct-declaration
2309 /// struct-declaration-list struct-declaration
2310 /// [OBC] '@' 'defs' '(' class-name ')'
2312 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2313 unsigned TagType, Decl *TagDecl) {
2314 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2315 "parsing struct/union body");
2317 SourceLocation LBraceLoc = ConsumeBrace();
2319 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2320 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2322 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2324 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2325 Diag(Tok, diag::ext_empty_struct_union)
2326 << (TagType == TST_union);
2328 llvm::SmallVector<Decl *, 32> FieldDecls;
2330 // While we still have something to read, read the declarations in the struct.
2331 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2332 // Each iteration of this loop reads one struct-declaration.
2334 // Check for extraneous top-level semicolon.
2335 if (Tok.is(tok::semi)) {
2336 Diag(Tok, diag::ext_extra_struct_semi)
2337 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2338 << FixItHint::CreateRemoval(Tok.getLocation());
2343 // Parse all the comma separated declarators.
2344 DeclSpec DS(AttrFactory);
2346 if (!Tok.is(tok::at)) {
2347 struct CFieldCallback : FieldCallback {
2350 llvm::SmallVectorImpl<Decl *> &FieldDecls;
2352 CFieldCallback(Parser &P, Decl *TagDecl,
2353 llvm::SmallVectorImpl<Decl *> &FieldDecls) :
2354 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2356 virtual Decl *invoke(FieldDeclarator &FD) {
2357 // Install the declarator into the current TagDecl.
2358 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2359 FD.D.getDeclSpec().getSourceRange().getBegin(),
2360 FD.D, FD.BitfieldSize);
2361 FieldDecls.push_back(Field);
2364 } Callback(*this, TagDecl, FieldDecls);
2366 ParseStructDeclaration(DS, Callback);
2367 } else { // Handle @defs
2369 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2370 Diag(Tok, diag::err_unexpected_at);
2371 SkipUntil(tok::semi, true);
2375 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2376 if (!Tok.is(tok::identifier)) {
2377 Diag(Tok, diag::err_expected_ident);
2378 SkipUntil(tok::semi, true);
2381 llvm::SmallVector<Decl *, 16> Fields;
2382 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2383 Tok.getIdentifierInfo(), Fields);
2384 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2386 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2389 if (Tok.is(tok::semi)) {
2391 } else if (Tok.is(tok::r_brace)) {
2392 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2395 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2396 // Skip to end of block or statement to avoid ext-warning on extra ';'.
2397 SkipUntil(tok::r_brace, true, true);
2398 // If we stopped at a ';', eat it.
2399 if (Tok.is(tok::semi)) ConsumeToken();
2403 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2405 ParsedAttributes attrs(AttrFactory);
2406 // If attributes exist after struct contents, parse them.
2407 MaybeParseGNUAttributes(attrs);
2409 Actions.ActOnFields(getCurScope(),
2410 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
2411 LBraceLoc, RBraceLoc,
2414 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
2417 /// ParseEnumSpecifier
2418 /// enum-specifier: [C99 6.7.2.2]
2419 /// 'enum' identifier[opt] '{' enumerator-list '}'
2420 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2421 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2422 /// '}' attributes[opt]
2423 /// 'enum' identifier
2424 /// [GNU] 'enum' attributes[opt] identifier
2426 /// [C++0x] enum-head '{' enumerator-list[opt] '}'
2427 /// [C++0x] enum-head '{' enumerator-list ',' '}'
2429 /// enum-head: [C++0x]
2430 /// enum-key attributes[opt] identifier[opt] enum-base[opt]
2431 /// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
2433 /// enum-key: [C++0x]
2438 /// enum-base: [C++0x]
2439 /// ':' type-specifier-seq
2441 /// [C++] elaborated-type-specifier:
2442 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
2444 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2445 const ParsedTemplateInfo &TemplateInfo,
2446 AccessSpecifier AS) {
2447 // Parse the tag portion of this.
2448 if (Tok.is(tok::code_completion)) {
2449 // Code completion for an enum name.
2450 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2451 ConsumeCodeCompletionToken();
2454 bool IsScopedEnum = false;
2455 bool IsScopedUsingClassTag = false;
2457 if (getLang().CPlusPlus0x &&
2458 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2459 IsScopedEnum = true;
2460 IsScopedUsingClassTag = Tok.is(tok::kw_class);
2464 // If attributes exist after tag, parse them.
2465 ParsedAttributes attrs(AttrFactory);
2466 MaybeParseGNUAttributes(attrs);
2468 bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft;
2470 CXXScopeSpec &SS = DS.getTypeSpecScope();
2471 if (getLang().CPlusPlus) {
2472 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
2473 // if a fixed underlying type is allowed.
2474 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
2476 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
2479 if (SS.isSet() && Tok.isNot(tok::identifier)) {
2480 Diag(Tok, diag::err_expected_ident);
2481 if (Tok.isNot(tok::l_brace)) {
2482 // Has no name and is not a definition.
2483 // Skip the rest of this declarator, up until the comma or semicolon.
2484 SkipUntil(tok::comma, true);
2490 // Must have either 'enum name' or 'enum {...}'.
2491 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2492 (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
2493 Diag(Tok, diag::err_expected_ident_lbrace);
2495 // Skip the rest of this declarator, up until the comma or semicolon.
2496 SkipUntil(tok::comma, true);
2500 // If an identifier is present, consume and remember it.
2501 IdentifierInfo *Name = 0;
2502 SourceLocation NameLoc;
2503 if (Tok.is(tok::identifier)) {
2504 Name = Tok.getIdentifierInfo();
2505 NameLoc = ConsumeToken();
2508 if (!Name && IsScopedEnum) {
2509 // C++0x 7.2p2: The optional identifier shall not be omitted in the
2510 // declaration of a scoped enumeration.
2511 Diag(Tok, diag::err_scoped_enum_missing_identifier);
2512 IsScopedEnum = false;
2513 IsScopedUsingClassTag = false;
2516 TypeResult BaseType;
2518 // Parse the fixed underlying type.
2519 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2520 bool PossibleBitfield = false;
2521 if (getCurScope()->getFlags() & Scope::ClassScope) {
2522 // If we're in class scope, this can either be an enum declaration with
2523 // an underlying type, or a declaration of a bitfield member. We try to
2524 // use a simple disambiguation scheme first to catch the common cases
2525 // (integer literal, sizeof); if it's still ambiguous, we then consider
2526 // anything that's a simple-type-specifier followed by '(' as an
2527 // expression. This suffices because function types are not valid
2528 // underlying types anyway.
2529 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2530 // If the next token starts an expression, we know we're parsing a
2531 // bit-field. This is the common case.
2532 if (TPR == TPResult::True())
2533 PossibleBitfield = true;
2534 // If the next token starts a type-specifier-seq, it may be either a
2535 // a fixed underlying type or the start of a function-style cast in C++;
2536 // lookahead one more token to see if it's obvious that we have a
2537 // fixed underlying type.
2538 else if (TPR == TPResult::False() &&
2539 GetLookAheadToken(2).getKind() == tok::semi) {
2543 // We have the start of a type-specifier-seq, so we have to perform
2544 // tentative parsing to determine whether we have an expression or a
2546 TentativeParsingAction TPA(*this);
2551 if ((getLang().CPlusPlus &&
2552 isCXXDeclarationSpecifier() != TPResult::True()) ||
2553 (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
2554 // We'll parse this as a bitfield later.
2555 PossibleBitfield = true;
2558 // We have a type-specifier-seq.
2567 if (!PossibleBitfield) {
2569 BaseType = ParseTypeName(&Range);
2571 if (!getLang().CPlusPlus0x)
2572 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2577 // There are three options here. If we have 'enum foo;', then this is a
2578 // forward declaration. If we have 'enum foo {...' then this is a
2579 // definition. Otherwise we have something like 'enum foo xyz', a reference.
2581 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2582 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
2583 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
2585 Sema::TagUseKind TUK;
2586 if (Tok.is(tok::l_brace))
2587 TUK = Sema::TUK_Definition;
2588 else if (Tok.is(tok::semi))
2589 TUK = Sema::TUK_Declaration;
2591 TUK = Sema::TUK_Reference;
2593 // enums cannot be templates, although they can be referenced from a
2595 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2596 TUK != Sema::TUK_Reference) {
2597 Diag(Tok, diag::err_enum_template);
2599 // Skip the rest of this declarator, up until the comma or semicolon.
2600 SkipUntil(tok::comma, true);
2604 if (!Name && TUK != Sema::TUK_Definition) {
2605 Diag(Tok, diag::err_enumerator_unnamed_no_def);
2607 // Skip the rest of this declarator, up until the comma or semicolon.
2608 SkipUntil(tok::comma, true);
2613 bool IsDependent = false;
2614 const char *PrevSpec = 0;
2616 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2617 StartLoc, SS, Name, NameLoc, attrs.getList(),
2619 MultiTemplateParamsArg(Actions),
2620 Owned, IsDependent, IsScopedEnum,
2621 IsScopedUsingClassTag, BaseType);
2624 // This enum has a dependent nested-name-specifier. Handle it as a
2627 DS.SetTypeSpecError();
2628 Diag(Tok, diag::err_expected_type_name_after_typename);
2632 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2633 TUK, SS, Name, StartLoc,
2635 if (Type.isInvalid()) {
2636 DS.SetTypeSpecError();
2640 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2641 NameLoc.isValid() ? NameLoc : StartLoc,
2642 PrevSpec, DiagID, Type.get()))
2643 Diag(StartLoc, DiagID) << PrevSpec;
2649 // The action failed to produce an enumeration tag. If this is a
2650 // definition, consume the entire definition.
2651 if (Tok.is(tok::l_brace)) {
2653 SkipUntil(tok::r_brace);
2656 DS.SetTypeSpecError();
2660 if (Tok.is(tok::l_brace))
2661 ParseEnumBody(StartLoc, TagDecl);
2663 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
2664 NameLoc.isValid() ? NameLoc : StartLoc,
2665 PrevSpec, DiagID, TagDecl, Owned))
2666 Diag(StartLoc, DiagID) << PrevSpec;
2669 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
2670 /// enumerator-list:
2672 /// enumerator-list ',' enumerator
2674 /// enumeration-constant
2675 /// enumeration-constant '=' constant-expression
2676 /// enumeration-constant:
2679 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
2680 // Enter the scope of the enum body and start the definition.
2681 ParseScope EnumScope(this, Scope::DeclScope);
2682 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
2684 SourceLocation LBraceLoc = ConsumeBrace();
2686 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2687 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2688 Diag(Tok, diag::error_empty_enum);
2690 llvm::SmallVector<Decl *, 32> EnumConstantDecls;
2692 Decl *LastEnumConstDecl = 0;
2694 // Parse the enumerator-list.
2695 while (Tok.is(tok::identifier)) {
2696 IdentifierInfo *Ident = Tok.getIdentifierInfo();
2697 SourceLocation IdentLoc = ConsumeToken();
2699 // If attributes exist after the enumerator, parse them.
2700 ParsedAttributes attrs(AttrFactory);
2701 MaybeParseGNUAttributes(attrs);
2703 SourceLocation EqualLoc;
2704 ExprResult AssignedVal;
2705 if (Tok.is(tok::equal)) {
2706 EqualLoc = ConsumeToken();
2707 AssignedVal = ParseConstantExpression();
2708 if (AssignedVal.isInvalid())
2709 SkipUntil(tok::comma, tok::r_brace, true, true);
2712 // Install the enumerator constant into EnumDecl.
2713 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
2716 attrs.getList(), EqualLoc,
2717 AssignedVal.release());
2718 EnumConstantDecls.push_back(EnumConstDecl);
2719 LastEnumConstDecl = EnumConstDecl;
2721 if (Tok.is(tok::identifier)) {
2722 // We're missing a comma between enumerators.
2723 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2724 Diag(Loc, diag::err_enumerator_list_missing_comma)
2725 << FixItHint::CreateInsertion(Loc, ", ");
2729 if (Tok.isNot(tok::comma))
2731 SourceLocation CommaLoc = ConsumeToken();
2733 if (Tok.isNot(tok::identifier) &&
2734 !(getLang().C99 || getLang().CPlusPlus0x))
2735 Diag(CommaLoc, diag::ext_enumerator_list_comma)
2736 << getLang().CPlusPlus
2737 << FixItHint::CreateRemoval(CommaLoc);
2741 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2743 // If attributes exist after the identifier list, parse them.
2744 ParsedAttributes attrs(AttrFactory);
2745 MaybeParseGNUAttributes(attrs);
2747 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2748 EnumConstantDecls.data(), EnumConstantDecls.size(),
2749 getCurScope(), attrs.getList());
2752 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc);
2755 /// isTypeSpecifierQualifier - Return true if the current token could be the
2756 /// start of a type-qualifier-list.
2757 bool Parser::isTypeQualifier() const {
2758 switch (Tok.getKind()) {
2759 default: return false;
2761 // type-qualifier only in OpenCL
2762 case tok::kw_private:
2763 return getLang().OpenCL;
2767 case tok::kw_volatile:
2768 case tok::kw_restrict:
2769 case tok::kw___private:
2770 case tok::kw___local:
2771 case tok::kw___global:
2772 case tok::kw___constant:
2773 case tok::kw___read_only:
2774 case tok::kw___read_write:
2775 case tok::kw___write_only:
2780 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2781 /// is definitely a type-specifier. Return false if it isn't part of a type
2782 /// specifier or if we're not sure.
2783 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2784 switch (Tok.getKind()) {
2785 default: return false;
2789 case tok::kw___int64:
2790 case tok::kw_signed:
2791 case tok::kw_unsigned:
2792 case tok::kw__Complex:
2793 case tok::kw__Imaginary:
2796 case tok::kw_wchar_t:
2797 case tok::kw_char16_t:
2798 case tok::kw_char32_t:
2801 case tok::kw_double:
2804 case tok::kw__Decimal32:
2805 case tok::kw__Decimal64:
2806 case tok::kw__Decimal128:
2807 case tok::kw___vector:
2809 // struct-or-union-specifier (C99) or class-specifier (C++)
2811 case tok::kw_struct:
2817 case tok::annot_typename:
2822 /// isTypeSpecifierQualifier - Return true if the current token could be the
2823 /// start of a specifier-qualifier-list.
2824 bool Parser::isTypeSpecifierQualifier() {
2825 switch (Tok.getKind()) {
2826 default: return false;
2828 case tok::identifier: // foo::bar
2829 if (TryAltiVecVectorToken())
2832 case tok::kw_typename: // typename T::type
2833 // Annotate typenames and C++ scope specifiers. If we get one, just
2834 // recurse to handle whatever we get.
2835 if (TryAnnotateTypeOrScopeToken())
2837 if (Tok.is(tok::identifier))
2839 return isTypeSpecifierQualifier();
2841 case tok::coloncolon: // ::foo::bar
2842 if (NextToken().is(tok::kw_new) || // ::new
2843 NextToken().is(tok::kw_delete)) // ::delete
2846 if (TryAnnotateTypeOrScopeToken())
2848 return isTypeSpecifierQualifier();
2850 // GNU attributes support.
2851 case tok::kw___attribute:
2852 // GNU typeof support.
2853 case tok::kw_typeof:
2858 case tok::kw___int64:
2859 case tok::kw_signed:
2860 case tok::kw_unsigned:
2861 case tok::kw__Complex:
2862 case tok::kw__Imaginary:
2865 case tok::kw_wchar_t:
2866 case tok::kw_char16_t:
2867 case tok::kw_char32_t:
2870 case tok::kw_double:
2873 case tok::kw__Decimal32:
2874 case tok::kw__Decimal64:
2875 case tok::kw__Decimal128:
2876 case tok::kw___vector:
2878 // struct-or-union-specifier (C99) or class-specifier (C++)
2880 case tok::kw_struct:
2887 case tok::kw_volatile:
2888 case tok::kw_restrict:
2891 case tok::annot_typename:
2894 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2896 return getLang().ObjC1;
2898 case tok::kw___cdecl:
2899 case tok::kw___stdcall:
2900 case tok::kw___fastcall:
2901 case tok::kw___thiscall:
2903 case tok::kw___ptr64:
2904 case tok::kw___pascal:
2906 case tok::kw___private:
2907 case tok::kw___local:
2908 case tok::kw___global:
2909 case tok::kw___constant:
2910 case tok::kw___read_only:
2911 case tok::kw___read_write:
2912 case tok::kw___write_only:
2916 case tok::kw_private:
2917 return getLang().OpenCL;
2921 /// isDeclarationSpecifier() - Return true if the current token is part of a
2922 /// declaration specifier.
2924 /// \param DisambiguatingWithExpression True to indicate that the purpose of
2925 /// this check is to disambiguate between an expression and a declaration.
2926 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
2927 switch (Tok.getKind()) {
2928 default: return false;
2930 case tok::kw_private:
2931 return getLang().OpenCL;
2933 case tok::identifier: // foo::bar
2934 // Unfortunate hack to support "Class.factoryMethod" notation.
2935 if (getLang().ObjC1 && NextToken().is(tok::period))
2937 if (TryAltiVecVectorToken())
2940 case tok::kw_typename: // typename T::type
2941 // Annotate typenames and C++ scope specifiers. If we get one, just
2942 // recurse to handle whatever we get.
2943 if (TryAnnotateTypeOrScopeToken())
2945 if (Tok.is(tok::identifier))
2948 // If we're in Objective-C and we have an Objective-C class type followed
2949 // by an identifier and then either ':' or ']', in a place where an
2950 // expression is permitted, then this is probably a class message send
2951 // missing the initial '['. In this case, we won't consider this to be
2952 // the start of a declaration.
2953 if (DisambiguatingWithExpression &&
2954 isStartOfObjCClassMessageMissingOpenBracket())
2957 return isDeclarationSpecifier();
2959 case tok::coloncolon: // ::foo::bar
2960 if (NextToken().is(tok::kw_new) || // ::new
2961 NextToken().is(tok::kw_delete)) // ::delete
2964 // Annotate typenames and C++ scope specifiers. If we get one, just
2965 // recurse to handle whatever we get.
2966 if (TryAnnotateTypeOrScopeToken())
2968 return isDeclarationSpecifier();
2970 // storage-class-specifier
2971 case tok::kw_typedef:
2972 case tok::kw_extern:
2973 case tok::kw___private_extern__:
2974 case tok::kw_static:
2976 case tok::kw_register:
2977 case tok::kw___thread:
2982 case tok::kw___int64:
2983 case tok::kw_signed:
2984 case tok::kw_unsigned:
2985 case tok::kw__Complex:
2986 case tok::kw__Imaginary:
2989 case tok::kw_wchar_t:
2990 case tok::kw_char16_t:
2991 case tok::kw_char32_t:
2995 case tok::kw_double:
2998 case tok::kw__Decimal32:
2999 case tok::kw__Decimal64:
3000 case tok::kw__Decimal128:
3001 case tok::kw___vector:
3003 // struct-or-union-specifier (C99) or class-specifier (C++)
3005 case tok::kw_struct:
3012 case tok::kw_volatile:
3013 case tok::kw_restrict:
3015 // function-specifier
3016 case tok::kw_inline:
3017 case tok::kw_virtual:
3018 case tok::kw_explicit:
3020 // static_assert-declaration
3021 case tok::kw__Static_assert:
3023 // GNU typeof support.
3024 case tok::kw_typeof:
3027 case tok::kw___attribute:
3031 case tok::kw_decltype:
3034 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3036 return getLang().ObjC1;
3039 case tok::annot_typename:
3040 return !DisambiguatingWithExpression ||
3041 !isStartOfObjCClassMessageMissingOpenBracket();
3043 case tok::kw___declspec:
3044 case tok::kw___cdecl:
3045 case tok::kw___stdcall:
3046 case tok::kw___fastcall:
3047 case tok::kw___thiscall:
3049 case tok::kw___ptr64:
3050 case tok::kw___forceinline:
3051 case tok::kw___pascal:
3053 case tok::kw___private:
3054 case tok::kw___local:
3055 case tok::kw___global:
3056 case tok::kw___constant:
3057 case tok::kw___read_only:
3058 case tok::kw___read_write:
3059 case tok::kw___write_only:
3065 bool Parser::isConstructorDeclarator() {
3066 TentativeParsingAction TPA(*this);
3068 // Parse the C++ scope specifier.
3070 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
3075 // Parse the constructor name.
3076 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3077 // We already know that we have a constructor name; just consume
3085 // Current class name must be followed by a left parentheses.
3086 if (Tok.isNot(tok::l_paren)) {
3092 // A right parentheses or ellipsis signals that we have a constructor.
3093 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
3098 // If we need to, enter the specified scope.
3099 DeclaratorScopeObj DeclScopeObj(*this, SS);
3100 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3101 DeclScopeObj.EnterDeclaratorScope();
3103 // Optionally skip Microsoft attributes.
3104 ParsedAttributes Attrs(AttrFactory);
3105 MaybeParseMicrosoftAttributes(Attrs);
3107 // Check whether the next token(s) are part of a declaration
3108 // specifier, in which case we have the start of a parameter and,
3109 // therefore, we know that this is a constructor.
3110 bool IsConstructor = isDeclarationSpecifier();
3112 return IsConstructor;
3115 /// ParseTypeQualifierListOpt
3116 /// type-qualifier-list: [C99 6.7.5]
3118 /// [vendor] attributes
3119 /// [ only if VendorAttributesAllowed=true ]
3120 /// type-qualifier-list type-qualifier
3121 /// [vendor] type-qualifier-list attributes
3122 /// [ only if VendorAttributesAllowed=true ]
3123 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
3124 /// [ only if CXX0XAttributesAllowed=true ]
3125 /// Note: vendor can be GNU, MS, etc.
3127 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3128 bool VendorAttributesAllowed,
3129 bool CXX0XAttributesAllowed) {
3130 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3131 SourceLocation Loc = Tok.getLocation();
3132 ParsedAttributesWithRange attrs(AttrFactory);
3133 ParseCXX0XAttributes(attrs);
3134 if (CXX0XAttributesAllowed)
3135 DS.takeAttributesFrom(attrs);
3137 Diag(Loc, diag::err_attributes_not_allowed);
3140 SourceLocation EndLoc;
3143 bool isInvalid = false;
3144 const char *PrevSpec = 0;
3145 unsigned DiagID = 0;
3146 SourceLocation Loc = Tok.getLocation();
3148 switch (Tok.getKind()) {
3149 case tok::code_completion:
3150 Actions.CodeCompleteTypeQualifiers(DS);
3151 ConsumeCodeCompletionToken();
3155 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
3158 case tok::kw_volatile:
3159 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3162 case tok::kw_restrict:
3163 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3167 // OpenCL qualifiers:
3168 case tok::kw_private:
3169 if (!getLang().OpenCL)
3170 goto DoneWithTypeQuals;
3171 case tok::kw___private:
3172 case tok::kw___global:
3173 case tok::kw___local:
3174 case tok::kw___constant:
3175 case tok::kw___read_only:
3176 case tok::kw___write_only:
3177 case tok::kw___read_write:
3178 ParseOpenCLQualifiers(DS);
3182 case tok::kw___ptr64:
3183 case tok::kw___cdecl:
3184 case tok::kw___stdcall:
3185 case tok::kw___fastcall:
3186 case tok::kw___thiscall:
3187 if (VendorAttributesAllowed) {
3188 ParseMicrosoftTypeAttributes(DS.getAttributes());
3191 goto DoneWithTypeQuals;
3192 case tok::kw___pascal:
3193 if (VendorAttributesAllowed) {
3194 ParseBorlandTypeAttributes(DS.getAttributes());
3197 goto DoneWithTypeQuals;
3198 case tok::kw___attribute:
3199 if (VendorAttributesAllowed) {
3200 ParseGNUAttributes(DS.getAttributes());
3201 continue; // do *not* consume the next token!
3203 // otherwise, FALL THROUGH!
3206 // If this is not a type-qualifier token, we're done reading type
3207 // qualifiers. First verify that DeclSpec's are consistent.
3208 DS.Finish(Diags, PP);
3209 if (EndLoc.isValid())
3210 DS.SetRangeEnd(EndLoc);
3214 // If the specifier combination wasn't legal, issue a diagnostic.
3216 assert(PrevSpec && "Method did not return previous specifier!");
3217 Diag(Tok, DiagID) << PrevSpec;
3219 EndLoc = ConsumeToken();
3224 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
3226 void Parser::ParseDeclarator(Declarator &D) {
3227 /// This implements the 'declarator' production in the C grammar, then checks
3228 /// for well-formedness and issues diagnostics.
3229 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3232 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3233 /// is parsed by the function passed to it. Pass null, and the direct-declarator
3234 /// isn't parsed at all, making this function effectively parse the C++
3235 /// ptr-operator production.
3237 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3238 /// [C] pointer[opt] direct-declarator
3239 /// [C++] direct-declarator
3240 /// [C++] ptr-operator declarator
3242 /// pointer: [C99 6.7.5]
3243 /// '*' type-qualifier-list[opt]
3244 /// '*' type-qualifier-list[opt] pointer
3247 /// '*' cv-qualifier-seq[opt]
3250 /// [GNU] '&' restrict[opt] attributes[opt]
3251 /// [GNU?] '&&' restrict[opt] attributes[opt]
3252 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3253 void Parser::ParseDeclaratorInternal(Declarator &D,
3254 DirectDeclParseFunction DirectDeclParser) {
3255 if (Diags.hasAllExtensionsSilenced())
3258 // C++ member pointers start with a '::' or a nested-name.
3259 // Member pointers get special handling, since there's no place for the
3260 // scope spec in the generic path below.
3261 if (getLang().CPlusPlus &&
3262 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3263 Tok.is(tok::annot_cxxscope))) {
3265 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
3267 if (SS.isNotEmpty()) {
3268 if (Tok.isNot(tok::star)) {
3269 // The scope spec really belongs to the direct-declarator.
3270 D.getCXXScopeSpec() = SS;
3271 if (DirectDeclParser)
3272 (this->*DirectDeclParser)(D);
3276 SourceLocation Loc = ConsumeToken();
3278 DeclSpec DS(AttrFactory);
3279 ParseTypeQualifierListOpt(DS);
3280 D.ExtendWithDeclSpec(DS);
3282 // Recurse to parse whatever is left.
3283 ParseDeclaratorInternal(D, DirectDeclParser);
3285 // Sema will have to catch (syntactically invalid) pointers into global
3286 // scope. It has to catch pointers into namespace scope anyway.
3287 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3290 /* Don't replace range end. */SourceLocation());
3295 tok::TokenKind Kind = Tok.getKind();
3296 // Not a pointer, C++ reference, or block.
3297 if (Kind != tok::star && Kind != tok::caret &&
3298 (Kind != tok::amp || !getLang().CPlusPlus) &&
3299 // We parse rvalue refs in C++03, because otherwise the errors are scary.
3300 (Kind != tok::ampamp || !getLang().CPlusPlus)) {
3301 if (DirectDeclParser)
3302 (this->*DirectDeclParser)(D);
3306 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3307 // '&&' -> rvalue reference
3308 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
3311 if (Kind == tok::star || Kind == tok::caret) {
3313 DeclSpec DS(AttrFactory);
3315 ParseTypeQualifierListOpt(DS);
3316 D.ExtendWithDeclSpec(DS);
3318 // Recursively parse the declarator.
3319 ParseDeclaratorInternal(D, DirectDeclParser);
3320 if (Kind == tok::star)
3321 // Remember that we parsed a pointer type, and remember the type-quals.
3322 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3323 DS.getConstSpecLoc(),
3324 DS.getVolatileSpecLoc(),
3325 DS.getRestrictSpecLoc()),
3329 // Remember that we parsed a Block type, and remember the type-quals.
3330 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3336 DeclSpec DS(AttrFactory);
3338 // Complain about rvalue references in C++03, but then go on and build
3340 if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
3341 Diag(Loc, diag::ext_rvalue_reference);
3343 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3344 // cv-qualifiers are introduced through the use of a typedef or of a
3345 // template type argument, in which case the cv-qualifiers are ignored.
3347 // [GNU] Retricted references are allowed.
3348 // [GNU] Attributes on references are allowed.
3349 // [C++0x] Attributes on references are not allowed.
3350 ParseTypeQualifierListOpt(DS, true, false);
3351 D.ExtendWithDeclSpec(DS);
3353 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3354 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3355 Diag(DS.getConstSpecLoc(),
3356 diag::err_invalid_reference_qualifier_application) << "const";
3357 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3358 Diag(DS.getVolatileSpecLoc(),
3359 diag::err_invalid_reference_qualifier_application) << "volatile";
3362 // Recursively parse the declarator.
3363 ParseDeclaratorInternal(D, DirectDeclParser);
3365 if (D.getNumTypeObjects() > 0) {
3366 // C++ [dcl.ref]p4: There shall be no references to references.
3367 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3368 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3369 if (const IdentifierInfo *II = D.getIdentifier())
3370 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3373 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3376 // Once we've complained about the reference-to-reference, we
3377 // can go ahead and build the (technically ill-formed)
3378 // declarator: reference collapsing will take care of it.
3382 // Remember that we parsed a reference type. It doesn't have type-quals.
3383 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3390 /// ParseDirectDeclarator
3391 /// direct-declarator: [C99 6.7.5]
3392 /// [C99] identifier
3393 /// '(' declarator ')'
3394 /// [GNU] '(' attributes declarator ')'
3395 /// [C90] direct-declarator '[' constant-expression[opt] ']'
3396 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3397 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3398 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3399 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
3400 /// direct-declarator '(' parameter-type-list ')'
3401 /// direct-declarator '(' identifier-list[opt] ')'
3402 /// [GNU] direct-declarator '(' parameter-forward-declarations
3403 /// parameter-type-list[opt] ')'
3404 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
3405 /// cv-qualifier-seq[opt] exception-specification[opt]
3406 /// [C++] declarator-id
3408 /// declarator-id: [C++ 8]
3409 /// '...'[opt] id-expression
3410 /// '::'[opt] nested-name-specifier[opt] type-name
3412 /// id-expression: [C++ 5.1]
3416 /// unqualified-id: [C++ 5.1]
3418 /// operator-function-id
3419 /// conversion-function-id
3423 void Parser::ParseDirectDeclarator(Declarator &D) {
3424 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3426 if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
3427 // ParseDeclaratorInternal might already have parsed the scope.
3428 if (D.getCXXScopeSpec().isEmpty()) {
3429 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
3432 if (D.getCXXScopeSpec().isValid()) {
3433 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3434 // Change the declaration context for name lookup, until this function
3435 // is exited (and the declarator has been parsed).
3436 DeclScopeObj.EnterDeclaratorScope();
3439 // C++0x [dcl.fct]p14:
3440 // There is a syntactic ambiguity when an ellipsis occurs at the end
3441 // of a parameter-declaration-clause without a preceding comma. In
3442 // this case, the ellipsis is parsed as part of the
3443 // abstract-declarator if the type of the parameter names a template
3444 // parameter pack that has not been expanded; otherwise, it is parsed
3445 // as part of the parameter-declaration-clause.
3446 if (Tok.is(tok::ellipsis) &&
3447 !((D.getContext() == Declarator::PrototypeContext ||
3448 D.getContext() == Declarator::BlockLiteralContext) &&
3449 NextToken().is(tok::r_paren) &&
3450 !Actions.containsUnexpandedParameterPacks(D)))
3451 D.setEllipsisLoc(ConsumeToken());
3453 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3454 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3455 // We found something that indicates the start of an unqualified-id.
3456 // Parse that unqualified-id.
3457 bool AllowConstructorName;
3458 if (D.getDeclSpec().hasTypeSpecifier())
3459 AllowConstructorName = false;
3460 else if (D.getCXXScopeSpec().isSet())
3461 AllowConstructorName =
3462 (D.getContext() == Declarator::FileContext ||
3463 (D.getContext() == Declarator::MemberContext &&
3464 D.getDeclSpec().isFriendSpecified()));
3466 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3468 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3469 /*EnteringContext=*/true,
3470 /*AllowDestructorName=*/true,
3471 AllowConstructorName,
3474 // Once we're past the identifier, if the scope was bad, mark the
3475 // whole declarator bad.
3476 D.getCXXScopeSpec().isInvalid()) {
3477 D.SetIdentifier(0, Tok.getLocation());
3478 D.setInvalidType(true);
3480 // Parsed the unqualified-id; update range information and move along.
3481 if (D.getSourceRange().getBegin().isInvalid())
3482 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3483 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3485 goto PastIdentifier;
3487 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3488 assert(!getLang().CPlusPlus &&
3489 "There's a C++-specific check for tok::identifier above");
3490 assert(Tok.getIdentifierInfo() && "Not an identifier?");
3491 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3493 goto PastIdentifier;
3496 if (Tok.is(tok::l_paren)) {
3497 // direct-declarator: '(' declarator ')'
3498 // direct-declarator: '(' attributes declarator ')'
3499 // Example: 'char (*X)' or 'int (*XX)(void)'
3500 ParseParenDeclarator(D);
3502 // If the declarator was parenthesized, we entered the declarator
3503 // scope when parsing the parenthesized declarator, then exited
3504 // the scope already. Re-enter the scope, if we need to.
3505 if (D.getCXXScopeSpec().isSet()) {
3506 // If there was an error parsing parenthesized declarator, declarator
3507 // scope may have been enterred before. Don't do it again.
3508 if (!D.isInvalidType() &&
3509 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3510 // Change the declaration context for name lookup, until this function
3511 // is exited (and the declarator has been parsed).
3512 DeclScopeObj.EnterDeclaratorScope();
3514 } else if (D.mayOmitIdentifier()) {
3515 // This could be something simple like "int" (in which case the declarator
3516 // portion is empty), if an abstract-declarator is allowed.
3517 D.SetIdentifier(0, Tok.getLocation());
3519 if (D.getContext() == Declarator::MemberContext)
3520 Diag(Tok, diag::err_expected_member_name_or_semi)
3521 << D.getDeclSpec().getSourceRange();
3522 else if (getLang().CPlusPlus)
3523 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
3525 Diag(Tok, diag::err_expected_ident_lparen);
3526 D.SetIdentifier(0, Tok.getLocation());
3527 D.setInvalidType(true);
3531 assert(D.isPastIdentifier() &&
3532 "Haven't past the location of the identifier yet?");
3534 // Don't parse attributes unless we have an identifier.
3535 if (D.getIdentifier())
3536 MaybeParseCXX0XAttributes(D);
3539 if (Tok.is(tok::l_paren)) {
3540 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
3541 // In such a case, check if we actually have a function declarator; if it
3542 // is not, the declarator has been fully parsed.
3543 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
3544 // When not in file scope, warn for ambiguous function declarators, just
3545 // in case the author intended it as a variable definition.
3546 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
3547 if (!isCXXFunctionDeclarator(warnIfAmbiguous))
3550 ParsedAttributes attrs(AttrFactory);
3551 ParseFunctionDeclarator(ConsumeParen(), D, attrs);
3552 } else if (Tok.is(tok::l_square)) {
3553 ParseBracketDeclarator(D);
3560 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
3561 /// only called before the identifier, so these are most likely just grouping
3562 /// parens for precedence. If we find that these are actually function
3563 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
3565 /// direct-declarator:
3566 /// '(' declarator ')'
3567 /// [GNU] '(' attributes declarator ')'
3568 /// direct-declarator '(' parameter-type-list ')'
3569 /// direct-declarator '(' identifier-list[opt] ')'
3570 /// [GNU] direct-declarator '(' parameter-forward-declarations
3571 /// parameter-type-list[opt] ')'
3573 void Parser::ParseParenDeclarator(Declarator &D) {
3574 SourceLocation StartLoc = ConsumeParen();
3575 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
3577 // Eat any attributes before we look at whether this is a grouping or function
3578 // declarator paren. If this is a grouping paren, the attribute applies to
3579 // the type being built up, for example:
3580 // int (__attribute__(()) *x)(long y)
3581 // If this ends up not being a grouping paren, the attribute applies to the
3582 // first argument, for example:
3583 // int (__attribute__(()) int x)
3584 // In either case, we need to eat any attributes to be able to determine what
3585 // sort of paren this is.
3587 ParsedAttributes attrs(AttrFactory);
3588 bool RequiresArg = false;
3589 if (Tok.is(tok::kw___attribute)) {
3590 ParseGNUAttributes(attrs);
3592 // We require that the argument list (if this is a non-grouping paren) be
3593 // present even if the attribute list was empty.
3596 // Eat any Microsoft extensions.
3597 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
3598 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
3599 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) {
3600 ParseMicrosoftTypeAttributes(attrs);
3602 // Eat any Borland extensions.
3603 if (Tok.is(tok::kw___pascal))
3604 ParseBorlandTypeAttributes(attrs);
3606 // If we haven't past the identifier yet (or where the identifier would be
3607 // stored, if this is an abstract declarator), then this is probably just
3608 // grouping parens. However, if this could be an abstract-declarator, then
3609 // this could also be the start of function arguments (consider 'void()').
3612 if (!D.mayOmitIdentifier()) {
3613 // If this can't be an abstract-declarator, this *must* be a grouping
3614 // paren, because we haven't seen the identifier yet.
3616 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
3617 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
3618 isDeclarationSpecifier()) { // 'int(int)' is a function.
3619 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3620 // considered to be a type, not a K&R identifier-list.
3623 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3627 // If this is a grouping paren, handle:
3628 // direct-declarator: '(' declarator ')'
3629 // direct-declarator: '(' attributes declarator ')'
3631 bool hadGroupingParens = D.hasGroupingParens();
3632 D.setGroupingParens(true);
3634 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3636 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc);
3637 D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc),
3640 D.setGroupingParens(hadGroupingParens);
3644 // Okay, if this wasn't a grouping paren, it must be the start of a function
3645 // argument list. Recognize that this declarator will never have an
3646 // identifier (and remember where it would have been), then call into
3647 // ParseFunctionDeclarator to handle of argument list.
3648 D.SetIdentifier(0, Tok.getLocation());
3650 ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg);
3653 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
3654 /// declarator D up to a paren, which indicates that we are parsing function
3657 /// If attrs is non-null, then the caller parsed those arguments immediately
3658 /// after the open paren - they should be considered to be the first argument of
3659 /// a parameter. If RequiresArg is true, then the first argument of the
3660 /// function is required to be present and required to not be an identifier
3663 /// For C++, after the parameter-list, it also parses cv-qualifier-seq[opt],
3664 /// (C++0x) ref-qualifier[opt], exception-specification[opt], and
3665 /// (C++0x) trailing-return-type[opt].
3667 /// [C++0x] exception-specification:
3668 /// dynamic-exception-specification
3669 /// noexcept-specification
3671 void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
3672 ParsedAttributes &attrs,
3674 // lparen is already consumed!
3675 assert(D.isPastIdentifier() && "Should not call before identifier!");
3677 // This should be true when the function has typed arguments.
3678 // Otherwise, it is treated as a K&R-style function.
3679 bool HasProto = false;
3680 // Build up an array of information about the parsed arguments.
3681 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3682 // Remember where we see an ellipsis, if any.
3683 SourceLocation EllipsisLoc;
3685 DeclSpec DS(AttrFactory);
3686 bool RefQualifierIsLValueRef = true;
3687 SourceLocation RefQualifierLoc;
3688 ExceptionSpecificationType ESpecType = EST_None;
3689 SourceRange ESpecRange;
3690 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3691 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3692 ExprResult NoexceptExpr;
3693 ParsedType TrailingReturnType;
3695 SourceLocation EndLoc;
3697 if (isFunctionDeclaratorIdentifierList()) {
3699 Diag(Tok, diag::err_argument_required_after_attribute);
3701 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
3703 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3705 // Enter function-declaration scope, limiting any declarators to the
3706 // function prototype scope, including parameter declarators.
3707 ParseScope PrototypeScope(this,
3708 Scope::FunctionPrototypeScope|Scope::DeclScope);
3710 if (Tok.isNot(tok::r_paren))
3711 ParseParameterDeclarationClause(D, attrs, ParamInfo, EllipsisLoc);
3712 else if (RequiresArg)
3713 Diag(Tok, diag::err_argument_required_after_attribute);
3715 HasProto = ParamInfo.size() || getLang().CPlusPlus;
3717 // If we have the closing ')', eat it.
3718 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3720 if (getLang().CPlusPlus) {
3721 MaybeParseCXX0XAttributes(attrs);
3723 // Parse cv-qualifier-seq[opt].
3724 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3725 if (!DS.getSourceRange().getEnd().isInvalid())
3726 EndLoc = DS.getSourceRange().getEnd();
3728 // Parse ref-qualifier[opt].
3729 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3730 if (!getLang().CPlusPlus0x)
3731 Diag(Tok, diag::ext_ref_qualifier);
3733 RefQualifierIsLValueRef = Tok.is(tok::amp);
3734 RefQualifierLoc = ConsumeToken();
3735 EndLoc = RefQualifierLoc;
3738 // Parse exception-specification[opt].
3739 ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3741 DynamicExceptionRanges,
3743 if (ESpecType != EST_None)
3744 EndLoc = ESpecRange.getEnd();
3746 // Parse trailing-return-type[opt].
3747 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3748 TrailingReturnType = ParseTrailingReturnType().get();
3752 // Leave prototype scope.
3753 PrototypeScope.Exit();
3756 // Remember that we parsed a function type, and remember the attributes.
3757 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
3758 /*isVariadic=*/EllipsisLoc.isValid(),
3760 ParamInfo.data(), ParamInfo.size(),
3761 DS.getTypeQualifiers(),
3762 RefQualifierIsLValueRef,
3764 /*MutableLoc=*/SourceLocation(),
3765 ESpecType, ESpecRange.getBegin(),
3766 DynamicExceptions.data(),
3767 DynamicExceptionRanges.data(),
3768 DynamicExceptions.size(),
3769 NoexceptExpr.isUsable() ?
3770 NoexceptExpr.get() : 0,
3771 LParenLoc, EndLoc, D,
3772 TrailingReturnType),
3776 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
3777 /// identifier list form for a K&R-style function: void foo(a,b,c)
3779 /// Note that identifier-lists are only allowed for normal declarators, not for
3780 /// abstract-declarators.
3781 bool Parser::isFunctionDeclaratorIdentifierList() {
3782 return !getLang().CPlusPlus
3783 && Tok.is(tok::identifier)
3784 && !TryAltiVecVectorToken()
3785 // K&R identifier lists can't have typedefs as identifiers, per C99
3787 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
3788 // Identifier lists follow a really simple grammar: the identifiers can
3789 // be followed *only* by a ", identifier" or ")". However, K&R
3790 // identifier lists are really rare in the brave new modern world, and
3791 // it is very common for someone to typo a type in a non-K&R style
3792 // list. If we are presented with something like: "void foo(intptr x,
3793 // float y)", we don't want to start parsing the function declarator as
3794 // though it is a K&R style declarator just because intptr is an
3797 // To handle this, we check to see if the token after the first
3798 // identifier is a "," or ")". Only then do we parse it as an
3800 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
3803 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3804 /// we found a K&R-style identifier list instead of a typed parameter list.
3806 /// After returning, ParamInfo will hold the parsed parameters.
3808 /// identifier-list: [C99 6.7.5]
3810 /// identifier-list ',' identifier
3812 void Parser::ParseFunctionDeclaratorIdentifierList(
3814 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
3815 // If there was no identifier specified for the declarator, either we are in
3816 // an abstract-declarator, or we are in a parameter declarator which was found
3817 // to be abstract. In abstract-declarators, identifier lists are not valid:
3819 if (!D.getIdentifier())
3820 Diag(Tok, diag::ext_ident_list_in_param);
3822 // Maintain an efficient lookup of params we have seen so far.
3823 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3826 // If this isn't an identifier, report the error and skip until ')'.
3827 if (Tok.isNot(tok::identifier)) {
3828 Diag(Tok, diag::err_expected_ident);
3829 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
3830 // Forget we parsed anything.
3835 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3837 // Reject 'typedef int y; int test(x, y)', but continue parsing.
3838 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
3839 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3841 // Verify that the argument identifier has not already been mentioned.
3842 if (!ParamsSoFar.insert(ParmII)) {
3843 Diag(Tok, diag::err_param_redefinition) << ParmII;
3845 // Remember this identifier in ParamInfo.
3846 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3851 // Eat the identifier.
3854 // The list continues if we see a comma.
3855 if (Tok.isNot(tok::comma))
3861 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
3862 /// after the opening parenthesis. This function will not parse a K&R-style
3863 /// identifier list.
3865 /// D is the declarator being parsed. If attrs is non-null, then the caller
3866 /// parsed those arguments immediately after the open paren - they should be
3867 /// considered to be the first argument of a parameter.
3869 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
3870 /// be the location of the ellipsis, if any was parsed.
3872 /// parameter-type-list: [C99 6.7.5]
3874 /// parameter-list ',' '...'
3875 /// [C++] parameter-list '...'
3877 /// parameter-list: [C99 6.7.5]
3878 /// parameter-declaration
3879 /// parameter-list ',' parameter-declaration
3881 /// parameter-declaration: [C99 6.7.5]
3882 /// declaration-specifiers declarator
3883 /// [C++] declaration-specifiers declarator '=' assignment-expression
3884 /// [GNU] declaration-specifiers declarator attributes
3885 /// declaration-specifiers abstract-declarator[opt]
3886 /// [C++] declaration-specifiers abstract-declarator[opt]
3887 /// '=' assignment-expression
3888 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
3890 void Parser::ParseParameterDeclarationClause(
3892 ParsedAttributes &attrs,
3893 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
3894 SourceLocation &EllipsisLoc) {
3897 if (Tok.is(tok::ellipsis)) {
3898 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
3902 // Parse the declaration-specifiers.
3903 // Just use the ParsingDeclaration "scope" of the declarator.
3904 DeclSpec DS(AttrFactory);
3906 // Skip any Microsoft attributes before a param.
3907 if (getLang().Microsoft && Tok.is(tok::l_square))
3908 ParseMicrosoftAttributes(DS.getAttributes());
3910 SourceLocation DSStart = Tok.getLocation();
3912 // If the caller parsed attributes for the first argument, add them now.
3913 // Take them so that we only apply the attributes to the first parameter.
3914 // FIXME: If we saw an ellipsis first, this code is not reached. Are the
3915 // attributes lost? Should they even be allowed?
3916 // FIXME: If we can leave the attributes in the token stream somehow, we can
3917 // get rid of a parameter (attrs) and this statement. It might be too much
3919 DS.takeAttributesFrom(attrs);
3921 ParseDeclarationSpecifiers(DS);
3923 // Parse the declarator. This is "PrototypeContext", because we must
3924 // accept either 'declarator' or 'abstract-declarator' here.
3925 Declarator ParmDecl(DS, Declarator::PrototypeContext);
3926 ParseDeclarator(ParmDecl);
3928 // Parse GNU attributes, if present.
3929 MaybeParseGNUAttributes(ParmDecl);
3931 // Remember this parsed parameter in ParamInfo.
3932 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
3934 // DefArgToks is used when the parsing of default arguments needs
3936 CachedTokens *DefArgToks = 0;
3938 // If no parameter was specified, verify that *something* was specified,
3939 // otherwise we have a missing type and identifier.
3940 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
3941 ParmDecl.getNumTypeObjects() == 0) {
3942 // Completely missing, emit error.
3943 Diag(DSStart, diag::err_missing_param);
3945 // Otherwise, we have something. Add it and let semantic analysis try
3946 // to grok it and add the result to the ParamInfo we are building.
3948 // Inform the actions module about the parameter declarator, so it gets
3949 // added to the current scope.
3950 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
3952 // Parse the default argument, if any. We parse the default
3953 // arguments in all dialects; the semantic analysis in
3954 // ActOnParamDefaultArgument will reject the default argument in
3956 if (Tok.is(tok::equal)) {
3957 SourceLocation EqualLoc = Tok.getLocation();
3959 // Parse the default argument
3960 if (D.getContext() == Declarator::MemberContext) {
3961 // If we're inside a class definition, cache the tokens
3962 // corresponding to the default argument. We'll actually parse
3963 // them when we see the end of the class definition.
3964 // FIXME: Templates will require something similar.
3965 // FIXME: Can we use a smart pointer for Toks?
3966 DefArgToks = new CachedTokens;
3968 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
3969 /*StopAtSemi=*/true,
3970 /*ConsumeFinalToken=*/false)) {
3973 Actions.ActOnParamDefaultArgumentError(Param);
3975 // Mark the end of the default argument so that we know when to
3976 // stop when we parse it later on.
3978 DefArgEnd.startToken();
3979 DefArgEnd.setKind(tok::cxx_defaultarg_end);
3980 DefArgEnd.setLocation(Tok.getLocation());
3981 DefArgToks->push_back(DefArgEnd);
3982 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
3983 (*DefArgToks)[1].getLocation());
3989 // The argument isn't actually potentially evaluated unless it is
3991 EnterExpressionEvaluationContext Eval(Actions,
3992 Sema::PotentiallyEvaluatedIfUsed);
3994 ExprResult DefArgResult(ParseAssignmentExpression());
3995 if (DefArgResult.isInvalid()) {
3996 Actions.ActOnParamDefaultArgumentError(Param);
3997 SkipUntil(tok::comma, tok::r_paren, true, true);
3999 // Inform the actions module about the default argument
4000 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
4001 DefArgResult.take());
4006 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4007 ParmDecl.getIdentifierLoc(), Param,
4011 // If the next token is a comma, consume it and keep reading arguments.
4012 if (Tok.isNot(tok::comma)) {
4013 if (Tok.is(tok::ellipsis)) {
4014 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4016 if (!getLang().CPlusPlus) {
4017 // We have ellipsis without a preceding ',', which is ill-formed
4018 // in C. Complain and provide the fix.
4019 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
4020 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
4027 // Consume the comma.
4033 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4034 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4035 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4036 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4037 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4038 void Parser::ParseBracketDeclarator(Declarator &D) {
4039 SourceLocation StartLoc = ConsumeBracket();
4041 // C array syntax has many features, but by-far the most common is [] and [4].
4042 // This code does a fast path to handle some of the most obvious cases.
4043 if (Tok.getKind() == tok::r_square) {
4044 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4045 ParsedAttributes attrs(AttrFactory);
4046 MaybeParseCXX0XAttributes(attrs);
4048 // Remember that we parsed the empty array type.
4049 ExprResult NumElements;
4050 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4054 } else if (Tok.getKind() == tok::numeric_constant &&
4055 GetLookAheadToken(1).is(tok::r_square)) {
4056 // [4] is very common. Parse the numeric constant expression.
4057 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
4060 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4061 ParsedAttributes attrs(AttrFactory);
4062 MaybeParseCXX0XAttributes(attrs);
4064 // Remember that we parsed a array type, and remember its features.
4065 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4072 // If valid, this location is the position where we read the 'static' keyword.
4073 SourceLocation StaticLoc;
4074 if (Tok.is(tok::kw_static))
4075 StaticLoc = ConsumeToken();
4077 // If there is a type-qualifier-list, read it now.
4078 // Type qualifiers in an array subscript are a C99 feature.
4079 DeclSpec DS(AttrFactory);
4080 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4082 // If we haven't already read 'static', check to see if there is one after the
4083 // type-qualifier-list.
4084 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4085 StaticLoc = ConsumeToken();
4087 // Handle "direct-declarator [ type-qual-list[opt] * ]".
4088 bool isStar = false;
4089 ExprResult NumElements;
4091 // Handle the case where we have '[*]' as the array size. However, a leading
4092 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
4093 // the the token after the star is a ']'. Since stars in arrays are
4094 // infrequent, use of lookahead is not costly here.
4095 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4096 ConsumeToken(); // Eat the '*'.
4098 if (StaticLoc.isValid()) {
4099 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4100 StaticLoc = SourceLocation(); // Drop the static.
4103 } else if (Tok.isNot(tok::r_square)) {
4104 // Note, in C89, this production uses the constant-expr production instead
4105 // of assignment-expr. The only difference is that assignment-expr allows
4106 // things like '=' and '*='. Sema rejects these in C89 mode because they
4107 // are not i-c-e's, so we don't need to distinguish between the two here.
4109 // Parse the constant-expression or assignment-expression now (depending
4111 if (getLang().CPlusPlus)
4112 NumElements = ParseConstantExpression();
4114 NumElements = ParseAssignmentExpression();
4117 // If there was an error parsing the assignment-expression, recover.
4118 if (NumElements.isInvalid()) {
4119 D.setInvalidType(true);
4120 // If the expression was invalid, skip it.
4121 SkipUntil(tok::r_square);
4125 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4127 ParsedAttributes attrs(AttrFactory);
4128 MaybeParseCXX0XAttributes(attrs);
4130 // Remember that we parsed a array type, and remember its features.
4131 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4132 StaticLoc.isValid(), isStar,
4133 NumElements.release(),
4138 /// [GNU] typeof-specifier:
4139 /// typeof ( expressions )
4140 /// typeof ( type-name )
4141 /// [GNU/C++] typeof unary-expression
4143 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4144 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4146 SourceLocation StartLoc = ConsumeToken();
4148 const bool hasParens = Tok.is(tok::l_paren);
4152 SourceRange CastRange;
4153 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4156 DS.setTypeofParensRange(CastRange);
4158 if (CastRange.getEnd().isInvalid())
4159 // FIXME: Not accurate, the range gets one token more than it should.
4160 DS.SetRangeEnd(Tok.getLocation());
4162 DS.SetRangeEnd(CastRange.getEnd());
4166 DS.SetTypeSpecError();
4170 const char *PrevSpec = 0;
4172 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4173 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4175 Diag(StartLoc, DiagID) << PrevSpec;
4179 // If we get here, the operand to the typeof was an expresion.
4180 if (Operand.isInvalid()) {
4181 DS.SetTypeSpecError();
4185 const char *PrevSpec = 0;
4187 // Check for duplicate type specifiers (e.g. "int typeof(int)").
4188 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4189 DiagID, Operand.get()))
4190 Diag(StartLoc, DiagID) << PrevSpec;
4194 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4195 /// from TryAltiVecVectorToken.
4196 bool Parser::TryAltiVecVectorTokenOutOfLine() {
4197 Token Next = NextToken();
4198 switch (Next.getKind()) {
4199 default: return false;
4202 case tok::kw_signed:
4203 case tok::kw_unsigned:
4208 case tok::kw_double:
4210 case tok::kw___pixel:
4211 Tok.setKind(tok::kw___vector);
4213 case tok::identifier:
4214 if (Next.getIdentifierInfo() == Ident_pixel) {
4215 Tok.setKind(tok::kw___vector);
4222 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4223 const char *&PrevSpec, unsigned &DiagID,
4225 if (Tok.getIdentifierInfo() == Ident_vector) {
4226 Token Next = NextToken();
4227 switch (Next.getKind()) {
4230 case tok::kw_signed:
4231 case tok::kw_unsigned:
4236 case tok::kw_double:
4238 case tok::kw___pixel:
4239 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4241 case tok::identifier:
4242 if (Next.getIdentifierInfo() == Ident_pixel) {
4243 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4250 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4251 DS.isTypeAltiVecVector()) {
4252 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);