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/Lookup.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/PrettyDeclStackTrace.h"
21 #include "RAIIObjectsForParser.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringSwitch.h"
25 using namespace clang;
27 //===----------------------------------------------------------------------===//
28 // C99 6.7: Declarations.
29 //===----------------------------------------------------------------------===//
32 /// type-name: [C99 6.7.6]
33 /// specifier-qualifier-list abstract-declarator[opt]
35 /// Called type-id in C++.
36 TypeResult Parser::ParseTypeName(SourceRange *Range,
37 Declarator::TheContext Context,
40 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
41 if (DSC == DSC_normal)
42 DSC = DSC_type_specifier;
44 // Parse the common declaration-specifiers piece.
45 DeclSpec DS(AttrFactory);
46 ParseSpecifierQualifierList(DS, AS, DSC);
48 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
50 // Parse the abstract-declarator, if present.
51 Declarator DeclaratorInfo(DS, Context);
52 ParseDeclarator(DeclaratorInfo);
54 *Range = DeclaratorInfo.getSourceRange();
56 if (DeclaratorInfo.isInvalidType())
59 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
63 /// isAttributeLateParsed - Return true if the attribute has arguments that
64 /// require late parsing.
65 static bool isAttributeLateParsed(const IdentifierInfo &II) {
66 return llvm::StringSwitch<bool>(II.getName())
67 #include "clang/Parse/AttrLateParsed.inc"
71 /// ParseGNUAttributes - Parse a non-empty attributes list.
75 /// attributes attribute
78 /// '__attribute__' '(' '(' attribute-list ')' ')'
80 /// [GNU] attribute-list:
82 /// attribute_list ',' attrib
87 /// attrib-name '(' identifier ')'
88 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
89 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
91 /// [GNU] attrib-name:
97 /// FIXME: The GCC grammar/code for this construct implies we need two
98 /// token lookahead. Comment from gcc: "If they start with an identifier
99 /// which is followed by a comma or close parenthesis, then the arguments
100 /// start with that identifier; otherwise they are an expression list."
102 /// GCC does not require the ',' between attribs in an attribute-list.
104 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
105 /// any attributes that don't work (based on my limited testing). Most
106 /// attributes are very simple in practice. Until we find a bug, I don't see
107 /// a pressing need to implement the 2 token lookahead.
109 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
110 SourceLocation *endLoc,
111 LateParsedAttrList *LateAttrs) {
112 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
114 while (Tok.is(tok::kw___attribute)) {
116 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
118 SkipUntil(tok::r_paren, true); // skip until ) or ;
121 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
122 SkipUntil(tok::r_paren, true); // skip until ) or ;
125 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
126 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
127 Tok.is(tok::comma)) {
128 if (Tok.is(tok::comma)) {
129 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
133 // we have an identifier or declaration specifier (const, int, etc.)
134 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
135 SourceLocation AttrNameLoc = ConsumeToken();
137 if (Tok.is(tok::l_paren)) {
138 // handle "parameterized" attributes
139 if (LateAttrs && isAttributeLateParsed(*AttrName)) {
140 LateParsedAttribute *LA =
141 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
142 LateAttrs->push_back(LA);
144 // Attributes in a class are parsed at the end of the class, along
145 // with other late-parsed declarations.
146 if (!ClassStack.empty() && !LateAttrs->parseSoon())
147 getCurrentClass().LateParsedDeclarations.push_back(LA);
149 // consume everything up to and including the matching right parens
150 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
154 Eof.setLocation(Tok.getLocation());
155 LA->Toks.push_back(Eof);
157 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
158 0, SourceLocation(), AttributeList::AS_GNU);
161 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
162 0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
165 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
166 SkipUntil(tok::r_paren, false);
167 SourceLocation Loc = Tok.getLocation();
168 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
169 SkipUntil(tok::r_paren, false);
177 /// Parse the arguments to a parameterized GNU attribute or
178 /// a C++11 attribute in "gnu" namespace.
179 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
180 SourceLocation AttrNameLoc,
181 ParsedAttributes &Attrs,
182 SourceLocation *EndLoc,
183 IdentifierInfo *ScopeName,
184 SourceLocation ScopeLoc,
185 AttributeList::Syntax Syntax) {
187 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
189 // Availability attributes have their own grammar.
190 if (AttrName->isStr("availability")) {
191 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
194 // Thread safety attributes fit into the FIXME case above, so we
195 // just parse the arguments as a list of expressions
196 if (IsThreadSafetyAttribute(AttrName->getName())) {
197 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
200 // Type safety attributes have their own grammar.
201 if (AttrName->isStr("type_tag_for_datatype")) {
202 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
206 ConsumeParen(); // ignore the left paren loc for now
208 IdentifierInfo *ParmName = 0;
209 SourceLocation ParmLoc;
210 bool BuiltinType = false;
212 switch (Tok.getKind()) {
214 case tok::kw_wchar_t:
215 case tok::kw_char16_t:
216 case tok::kw_char32_t:
221 case tok::kw___int64:
222 case tok::kw___int128:
224 case tok::kw_unsigned:
229 // __attribute__(( vec_type_hint(char) ))
230 // FIXME: Don't just discard the builtin type token.
235 case tok::identifier:
236 ParmName = Tok.getIdentifierInfo();
237 ParmLoc = ConsumeToken();
247 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
249 if (ParmLoc.isValid())
252 // Parse the non-empty comma-separated list of expressions.
254 ExprResult ArgExpr(ParseAssignmentExpression());
255 if (ArgExpr.isInvalid()) {
256 SkipUntil(tok::r_paren);
259 ArgExprs.push_back(ArgExpr.release());
260 if (Tok.isNot(tok::comma))
262 ConsumeToken(); // Eat the comma, move to the next argument
265 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
266 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
268 while (Tok.is(tok::identifier)) {
270 if (Tok.is(tok::greater))
272 if (Tok.is(tok::comma)) {
277 if (Tok.isNot(tok::greater))
278 Diag(Tok, diag::err_iboutletcollection_with_protocol);
279 SkipUntil(tok::r_paren, false, true); // skip until ')'
283 SourceLocation RParen = Tok.getLocation();
284 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
285 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
286 AttributeList *attr =
287 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen),
288 ScopeName, ScopeLoc, ParmName, ParmLoc,
289 ArgExprs.data(), ArgExprs.size(), Syntax);
290 if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection)
291 Diag(Tok, diag::err_iboutletcollection_builtintype);
295 /// \brief Parses a single argument for a declspec, including the
296 /// surrounding parens.
297 void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
298 SourceLocation AttrNameLoc,
299 ParsedAttributes &Attrs)
301 BalancedDelimiterTracker T(*this, tok::l_paren);
302 if (T.expectAndConsume(diag::err_expected_lparen_after,
303 AttrName->getNameStart(), tok::r_paren))
306 ExprResult ArgExpr(ParseConstantExpression());
307 if (ArgExpr.isInvalid()) {
311 Expr *ExprList = ArgExpr.take();
312 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
313 &ExprList, 1, AttributeList::AS_Declspec);
318 /// \brief Determines whether a declspec is a "simple" one requiring no
320 bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
321 return llvm::StringSwitch<bool>(Ident->getName())
322 .Case("dllimport", true)
323 .Case("dllexport", true)
324 .Case("noreturn", true)
325 .Case("nothrow", true)
326 .Case("noinline", true)
328 .Case("appdomain", true)
329 .Case("process", true)
330 .Case("jitintrinsic", true)
331 .Case("noalias", true)
332 .Case("restrict", true)
333 .Case("novtable", true)
334 .Case("selectany", true)
335 .Case("thread", true)
339 /// \brief Attempts to parse a declspec which is not simple (one that takes
340 /// parameters). Will return false if we properly handled the declspec, or
341 /// true if it is an unknown declspec.
342 void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
344 ParsedAttributes &Attrs) {
345 // Try to handle the easy case first -- these declspecs all take a single
346 // parameter as their argument.
347 if (llvm::StringSwitch<bool>(Ident->getName())
350 .Case("allocate", true)
352 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
353 } else if (Ident->getName() == "deprecated") {
354 // The deprecated declspec has an optional single argument, so we will
355 // check for a l-paren to decide whether we should parse an argument or
357 if (Tok.getKind() == tok::l_paren)
358 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
360 Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
361 AttributeList::AS_Declspec);
362 } else if (Ident->getName() == "property") {
363 // The property declspec is more complex in that it can take one or two
364 // assignment expressions as a parameter, but the lhs of the assignment
365 // must be named get or put.
367 // For right now, we will just skip to the closing right paren of the
368 // property expression.
370 // FIXME: we should deal with __declspec(property) at some point because it
371 // is used in the platform SDK headers for the Parallel Patterns Library
373 BalancedDelimiterTracker T(*this, tok::l_paren);
374 if (T.expectAndConsume(diag::err_expected_lparen_after,
375 Ident->getNameStart(), tok::r_paren))
379 // We don't recognize this as a valid declspec, but instead of creating the
380 // attribute and allowing sema to warn about it, we will warn here instead.
381 // This is because some attributes have multiple spellings, but we need to
382 // disallow that for declspecs (such as align vs aligned). If we made the
383 // attribute, we'd have to split the valid declspec spelling logic into
385 Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
387 // If there's an open paren, we should eat the open and close parens under
388 // the assumption that this unknown declspec has parameters.
389 BalancedDelimiterTracker T(*this, tok::l_paren);
390 if (!T.consumeOpen())
395 /// [MS] decl-specifier:
396 /// __declspec ( extended-decl-modifier-seq )
398 /// [MS] extended-decl-modifier-seq:
399 /// extended-decl-modifier[opt]
400 /// extended-decl-modifier extended-decl-modifier-seq
401 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
402 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
405 BalancedDelimiterTracker T(*this, tok::l_paren);
406 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
410 // An empty declspec is perfectly legal and should not warn. Additionally,
411 // you can specify multiple attributes per declspec.
412 while (Tok.getKind() != tok::r_paren) {
413 // We expect either a well-known identifier or a generic string. Anything
414 // else is a malformed declspec.
415 bool IsString = Tok.getKind() == tok::string_literal ? true : false;
416 if (!IsString && Tok.getKind() != tok::identifier &&
417 Tok.getKind() != tok::kw_restrict) {
418 Diag(Tok, diag::err_ms_declspec_type);
423 IdentifierInfo *AttrName;
424 SourceLocation AttrNameLoc;
426 SmallString<8> StrBuffer;
427 bool Invalid = false;
428 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
433 AttrName = PP.getIdentifierInfo(Str);
434 AttrNameLoc = ConsumeStringToken();
436 AttrName = Tok.getIdentifierInfo();
437 AttrNameLoc = ConsumeToken();
440 if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
441 // If we have a generic string, we will allow it because there is no
442 // documented list of allowable string declspecs, but we know they exist
443 // (for instance, SAL declspecs in older versions of MSVC).
445 // Alternatively, if the identifier is a simple one, then it requires no
446 // arguments and can be turned into an attribute directly.
447 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
448 0, 0, AttributeList::AS_Declspec);
450 ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
455 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
456 // Treat these like attributes
457 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
458 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
459 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
460 Tok.is(tok::kw___ptr32) ||
461 Tok.is(tok::kw___unaligned)) {
462 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
463 SourceLocation AttrNameLoc = ConsumeToken();
464 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
465 SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
469 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
470 // Treat these like attributes
471 while (Tok.is(tok::kw___pascal)) {
472 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
473 SourceLocation AttrNameLoc = ConsumeToken();
474 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
475 SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
479 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
480 // Treat these like attributes
481 while (Tok.is(tok::kw___kernel)) {
482 SourceLocation AttrNameLoc = ConsumeToken();
483 attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
484 AttrNameLoc, 0, AttrNameLoc, 0,
485 SourceLocation(), 0, 0, AttributeList::AS_GNU);
489 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
490 SourceLocation Loc = Tok.getLocation();
491 switch(Tok.getKind()) {
492 // OpenCL qualifiers:
493 case tok::kw___private:
494 case tok::kw_private:
495 DS.getAttributes().addNewInteger(
496 Actions.getASTContext(),
497 PP.getIdentifierInfo("address_space"), Loc, 0);
500 case tok::kw___global:
501 DS.getAttributes().addNewInteger(
502 Actions.getASTContext(),
503 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
506 case tok::kw___local:
507 DS.getAttributes().addNewInteger(
508 Actions.getASTContext(),
509 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
512 case tok::kw___constant:
513 DS.getAttributes().addNewInteger(
514 Actions.getASTContext(),
515 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
518 case tok::kw___read_only:
519 DS.getAttributes().addNewInteger(
520 Actions.getASTContext(),
521 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
524 case tok::kw___write_only:
525 DS.getAttributes().addNewInteger(
526 Actions.getASTContext(),
527 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
530 case tok::kw___read_write:
531 DS.getAttributes().addNewInteger(
532 Actions.getASTContext(),
533 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
539 /// \brief Parse a version number.
543 /// simple-integer ',' simple-integer
544 /// simple-integer ',' simple-integer ',' simple-integer
545 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
546 Range = Tok.getLocation();
548 if (!Tok.is(tok::numeric_constant)) {
549 Diag(Tok, diag::err_expected_version);
550 SkipUntil(tok::comma, tok::r_paren, true, true, true);
551 return VersionTuple();
554 // Parse the major (and possibly minor and subminor) versions, which
555 // are stored in the numeric constant. We utilize a quirk of the
556 // lexer, which is that it handles something like 1.2.3 as a single
557 // numeric constant, rather than two separate tokens.
558 SmallString<512> Buffer;
559 Buffer.resize(Tok.getLength()+1);
560 const char *ThisTokBegin = &Buffer[0];
562 // Get the spelling of the token, which eliminates trigraphs, etc.
563 bool Invalid = false;
564 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
566 return VersionTuple();
568 // Parse the major version.
569 unsigned AfterMajor = 0;
571 while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
572 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
576 if (AfterMajor == 0) {
577 Diag(Tok, diag::err_expected_version);
578 SkipUntil(tok::comma, tok::r_paren, true, true, true);
579 return VersionTuple();
582 if (AfterMajor == ActualLength) {
585 // We only had a single version component.
587 Diag(Tok, diag::err_zero_version);
588 return VersionTuple();
591 return VersionTuple(Major);
594 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
595 Diag(Tok, diag::err_expected_version);
596 SkipUntil(tok::comma, tok::r_paren, true, true, true);
597 return VersionTuple();
600 // Parse the minor version.
601 unsigned AfterMinor = AfterMajor + 1;
603 while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
604 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
608 if (AfterMinor == ActualLength) {
611 // We had major.minor.
612 if (Major == 0 && Minor == 0) {
613 Diag(Tok, diag::err_zero_version);
614 return VersionTuple();
617 return VersionTuple(Major, Minor);
620 // If what follows is not a '.', we have a problem.
621 if (ThisTokBegin[AfterMinor] != '.') {
622 Diag(Tok, diag::err_expected_version);
623 SkipUntil(tok::comma, tok::r_paren, true, true, true);
624 return VersionTuple();
627 // Parse the subminor version.
628 unsigned AfterSubminor = AfterMinor + 1;
629 unsigned Subminor = 0;
630 while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
631 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
635 if (AfterSubminor != ActualLength) {
636 Diag(Tok, diag::err_expected_version);
637 SkipUntil(tok::comma, tok::r_paren, true, true, true);
638 return VersionTuple();
641 return VersionTuple(Major, Minor, Subminor);
644 /// \brief Parse the contents of the "availability" attribute.
646 /// availability-attribute:
647 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
652 /// version-arg-list:
654 /// version-arg ',' version-arg-list
657 /// 'introduced' '=' version
658 /// 'deprecated' '=' version
659 /// 'obsoleted' = version
662 /// 'message' '=' <string>
663 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
664 SourceLocation AvailabilityLoc,
665 ParsedAttributes &attrs,
666 SourceLocation *endLoc) {
667 SourceLocation PlatformLoc;
668 IdentifierInfo *Platform = 0;
670 enum { Introduced, Deprecated, Obsoleted, Unknown };
671 AvailabilityChange Changes[Unknown];
672 ExprResult MessageExpr;
675 BalancedDelimiterTracker T(*this, tok::l_paren);
676 if (T.consumeOpen()) {
677 Diag(Tok, diag::err_expected_lparen);
681 // Parse the platform name,
682 if (Tok.isNot(tok::identifier)) {
683 Diag(Tok, diag::err_availability_expected_platform);
684 SkipUntil(tok::r_paren);
687 Platform = Tok.getIdentifierInfo();
688 PlatformLoc = ConsumeToken();
690 // Parse the ',' following the platform name.
691 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
694 // If we haven't grabbed the pointers for the identifiers
695 // "introduced", "deprecated", and "obsoleted", do so now.
696 if (!Ident_introduced) {
697 Ident_introduced = PP.getIdentifierInfo("introduced");
698 Ident_deprecated = PP.getIdentifierInfo("deprecated");
699 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
700 Ident_unavailable = PP.getIdentifierInfo("unavailable");
701 Ident_message = PP.getIdentifierInfo("message");
704 // Parse the set of introductions/deprecations/removals.
705 SourceLocation UnavailableLoc;
707 if (Tok.isNot(tok::identifier)) {
708 Diag(Tok, diag::err_availability_expected_change);
709 SkipUntil(tok::r_paren);
712 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
713 SourceLocation KeywordLoc = ConsumeToken();
715 if (Keyword == Ident_unavailable) {
716 if (UnavailableLoc.isValid()) {
717 Diag(KeywordLoc, diag::err_availability_redundant)
718 << Keyword << SourceRange(UnavailableLoc);
720 UnavailableLoc = KeywordLoc;
722 if (Tok.isNot(tok::comma))
729 if (Tok.isNot(tok::equal)) {
730 Diag(Tok, diag::err_expected_equal_after)
732 SkipUntil(tok::r_paren);
736 if (Keyword == Ident_message) {
737 if (!isTokenStringLiteral()) {
738 Diag(Tok, diag::err_expected_string_literal);
739 SkipUntil(tok::r_paren);
742 MessageExpr = ParseStringLiteralExpression();
746 SourceRange VersionRange;
747 VersionTuple Version = ParseVersionTuple(VersionRange);
749 if (Version.empty()) {
750 SkipUntil(tok::r_paren);
755 if (Keyword == Ident_introduced)
757 else if (Keyword == Ident_deprecated)
759 else if (Keyword == Ident_obsoleted)
764 if (Index < Unknown) {
765 if (!Changes[Index].KeywordLoc.isInvalid()) {
766 Diag(KeywordLoc, diag::err_availability_redundant)
768 << SourceRange(Changes[Index].KeywordLoc,
769 Changes[Index].VersionRange.getEnd());
772 Changes[Index].KeywordLoc = KeywordLoc;
773 Changes[Index].Version = Version;
774 Changes[Index].VersionRange = VersionRange;
776 Diag(KeywordLoc, diag::err_availability_unknown_change)
777 << Keyword << VersionRange;
780 if (Tok.isNot(tok::comma))
787 if (T.consumeClose())
791 *endLoc = T.getCloseLocation();
793 // The 'unavailable' availability cannot be combined with any other
794 // availability changes. Make sure that hasn't happened.
795 if (UnavailableLoc.isValid()) {
796 bool Complained = false;
797 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
798 if (Changes[Index].KeywordLoc.isValid()) {
800 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
801 << SourceRange(Changes[Index].KeywordLoc,
802 Changes[Index].VersionRange.getEnd());
806 // Clear out the availability.
807 Changes[Index] = AvailabilityChange();
812 // Record this attribute
813 attrs.addNew(&Availability,
814 SourceRange(AvailabilityLoc, T.getCloseLocation()),
816 Platform, PlatformLoc,
820 UnavailableLoc, MessageExpr.take(),
821 AttributeList::AS_GNU);
825 // Late Parsed Attributes:
826 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
828 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
830 void Parser::LateParsedClass::ParseLexedAttributes() {
831 Self->ParseLexedAttributes(*Class);
834 void Parser::LateParsedAttribute::ParseLexedAttributes() {
835 Self->ParseLexedAttribute(*this, true, false);
838 /// Wrapper class which calls ParseLexedAttribute, after setting up the
839 /// scope appropriately.
840 void Parser::ParseLexedAttributes(ParsingClass &Class) {
841 // Deal with templates
842 // FIXME: Test cases to make sure this does the right thing for templates.
843 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
844 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
846 if (HasTemplateScope)
847 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
849 // Set or update the scope flags.
850 bool AlreadyHasClassScope = Class.TopLevelClass;
851 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
852 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
853 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
855 // Enter the scope of nested classes
856 if (!AlreadyHasClassScope)
857 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
858 Class.TagOrTemplate);
859 if (!Class.LateParsedDeclarations.empty()) {
860 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
861 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
865 if (!AlreadyHasClassScope)
866 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
867 Class.TagOrTemplate);
871 /// \brief Parse all attributes in LAs, and attach them to Decl D.
872 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
873 bool EnterScope, bool OnDefinition) {
874 assert(LAs.parseSoon() &&
875 "Attribute list should be marked for immediate parsing.");
876 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
879 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
886 /// \brief Finish parsing an attribute for which parsing was delayed.
887 /// This will be called at the end of parsing a class declaration
888 /// for each LateParsedAttribute. We consume the saved tokens and
889 /// create an attribute with the arguments filled in. We add this
890 /// to the Attribute list for the decl.
891 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
892 bool EnterScope, bool OnDefinition) {
893 // Save the current token position.
894 SourceLocation OrigLoc = Tok.getLocation();
896 // Append the current token at the end of the new token stream so that it
898 LA.Toks.push_back(Tok);
899 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
900 // Consume the previously pushed token.
903 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
904 Diag(Tok, diag::warn_attribute_on_function_definition)
905 << LA.AttrName.getName();
908 ParsedAttributes Attrs(AttrFactory);
909 SourceLocation endLoc;
911 if (LA.Decls.size() > 0) {
912 Decl *D = LA.Decls[0];
913 NamedDecl *ND = dyn_cast<NamedDecl>(D);
914 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
916 // Allow 'this' within late-parsed attributes.
917 Sema::CXXThisScopeRAII ThisScope(Actions, RD,
919 ND && RD && ND->isCXXInstanceMember());
921 if (LA.Decls.size() == 1) {
922 // If the Decl is templatized, add template parameters to scope.
923 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
924 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
925 if (HasTemplateScope)
926 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
928 // If the Decl is on a function, add function parameters to the scope.
929 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
930 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
932 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
934 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
935 0, SourceLocation(), AttributeList::AS_GNU);
938 Actions.ActOnExitFunctionContext();
939 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
941 if (HasTemplateScope) {
945 // If there are multiple decls, then the decl cannot be within the
947 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
948 0, SourceLocation(), AttributeList::AS_GNU);
951 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
954 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
955 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
958 if (Tok.getLocation() != OrigLoc) {
959 // Due to a parsing error, we either went over the cached tokens or
960 // there are still cached tokens left, so we skip the leftover tokens.
961 // Since this is an uncommon situation that should be avoided, use the
962 // expensive isBeforeInTranslationUnit call.
963 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
965 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
970 /// \brief Wrapper around a case statement checking if AttrName is
971 /// one of the thread safety attributes
972 bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
973 return llvm::StringSwitch<bool>(AttrName)
974 .Case("guarded_by", true)
975 .Case("guarded_var", true)
976 .Case("pt_guarded_by", true)
977 .Case("pt_guarded_var", true)
978 .Case("lockable", true)
979 .Case("scoped_lockable", true)
980 .Case("no_thread_safety_analysis", true)
981 .Case("acquired_after", true)
982 .Case("acquired_before", true)
983 .Case("exclusive_lock_function", true)
984 .Case("shared_lock_function", true)
985 .Case("exclusive_trylock_function", true)
986 .Case("shared_trylock_function", true)
987 .Case("unlock_function", true)
988 .Case("lock_returned", true)
989 .Case("locks_excluded", true)
990 .Case("exclusive_locks_required", true)
991 .Case("shared_locks_required", true)
995 /// \brief Parse the contents of thread safety attributes. These
996 /// should always be parsed as an expression list.
998 /// We need to special case the parsing due to the fact that if the first token
999 /// of the first argument is an identifier, the main parse loop will store
1000 /// that token as a "parameter" and the rest of
1001 /// the arguments will be added to a list of "arguments". However,
1002 /// subsequent tokens in the first argument are lost. We instead parse each
1003 /// argument as an expression and add all arguments to the list of "arguments".
1004 /// In future, we will take advantage of this special case to also
1005 /// deal with some argument scoping issues here (for example, referring to a
1006 /// function parameter in the attribute on that function).
1007 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1008 SourceLocation AttrNameLoc,
1009 ParsedAttributes &Attrs,
1010 SourceLocation *EndLoc) {
1011 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1013 BalancedDelimiterTracker T(*this, tok::l_paren);
1016 ExprVector ArgExprs;
1017 bool ArgExprsOk = true;
1019 // now parse the list of expressions
1020 while (Tok.isNot(tok::r_paren)) {
1021 ExprResult ArgExpr(ParseAssignmentExpression());
1022 if (ArgExpr.isInvalid()) {
1027 ArgExprs.push_back(ArgExpr.release());
1029 if (Tok.isNot(tok::comma))
1031 ConsumeToken(); // Eat the comma, move to the next argument
1034 if (ArgExprsOk && !T.consumeClose()) {
1035 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
1036 ArgExprs.data(), ArgExprs.size(), AttributeList::AS_GNU);
1039 *EndLoc = T.getCloseLocation();
1042 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1043 SourceLocation AttrNameLoc,
1044 ParsedAttributes &Attrs,
1045 SourceLocation *EndLoc) {
1046 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1048 BalancedDelimiterTracker T(*this, tok::l_paren);
1051 if (Tok.isNot(tok::identifier)) {
1052 Diag(Tok, diag::err_expected_ident);
1056 IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
1057 SourceLocation ArgumentKindLoc = ConsumeToken();
1059 if (Tok.isNot(tok::comma)) {
1060 Diag(Tok, diag::err_expected_comma);
1066 SourceRange MatchingCTypeRange;
1067 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1068 if (MatchingCType.isInvalid()) {
1073 bool LayoutCompatible = false;
1074 bool MustBeNull = false;
1075 while (Tok.is(tok::comma)) {
1077 if (Tok.isNot(tok::identifier)) {
1078 Diag(Tok, diag::err_expected_ident);
1082 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1083 if (Flag->isStr("layout_compatible"))
1084 LayoutCompatible = true;
1085 else if (Flag->isStr("must_be_null"))
1088 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1092 ConsumeToken(); // consume flag
1095 if (!T.consumeClose()) {
1096 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
1097 ArgumentKind, ArgumentKindLoc,
1098 MatchingCType.release(), LayoutCompatible,
1099 MustBeNull, AttributeList::AS_GNU);
1103 *EndLoc = T.getCloseLocation();
1106 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1107 /// of a C++11 attribute-specifier in a location where an attribute is not
1108 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1111 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1112 /// this doesn't appear to actually be an attribute-specifier, and the caller
1113 /// should try to parse it.
1114 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1115 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1117 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1118 case CAK_NotAttributeSpecifier:
1119 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1122 case CAK_InvalidAttributeSpecifier:
1123 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1126 case CAK_AttributeSpecifier:
1127 // Parse and discard the attributes.
1128 SourceLocation BeginLoc = ConsumeBracket();
1130 SkipUntil(tok::r_square, /*StopAtSemi*/ false);
1131 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1132 SourceLocation EndLoc = ConsumeBracket();
1133 Diag(BeginLoc, diag::err_attributes_not_allowed)
1134 << SourceRange(BeginLoc, EndLoc);
1137 llvm_unreachable("All cases handled above.");
1140 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1141 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1145 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1146 AttributeList *AttrList = attrs.getList();
1148 if (AttrList->isCXX0XAttribute()) {
1149 Diag(AttrList->getLoc(), diag::warn_attribute_no_decl)
1150 << AttrList->getName();
1151 AttrList->setInvalid();
1153 AttrList = AttrList->getNext();
1157 /// ParseDeclaration - Parse a full 'declaration', which consists of
1158 /// declaration-specifiers, some number of declarators, and a semicolon.
1159 /// 'Context' should be a Declarator::TheContext value. This returns the
1160 /// location of the semicolon in DeclEnd.
1162 /// declaration: [C99 6.7]
1163 /// block-declaration ->
1164 /// simple-declaration
1166 /// [C++] template-declaration
1167 /// [C++] namespace-definition
1168 /// [C++] using-directive
1169 /// [C++] using-declaration
1170 /// [C++11/C11] static_assert-declaration
1171 /// others... [FIXME]
1173 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1175 SourceLocation &DeclEnd,
1176 ParsedAttributesWithRange &attrs) {
1177 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1178 // Must temporarily exit the objective-c container scope for
1179 // parsing c none objective-c decls.
1180 ObjCDeclContextSwitch ObjCDC(*this);
1182 Decl *SingleDecl = 0;
1183 Decl *OwnedType = 0;
1184 switch (Tok.getKind()) {
1185 case tok::kw_template:
1186 case tok::kw_export:
1187 ProhibitAttributes(attrs);
1188 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1190 case tok::kw_inline:
1191 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1192 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1193 ProhibitAttributes(attrs);
1194 SourceLocation InlineLoc = ConsumeToken();
1195 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1198 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1200 case tok::kw_namespace:
1201 ProhibitAttributes(attrs);
1202 SingleDecl = ParseNamespace(Context, DeclEnd);
1205 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1206 DeclEnd, attrs, &OwnedType);
1208 case tok::kw_static_assert:
1209 case tok::kw__Static_assert:
1210 ProhibitAttributes(attrs);
1211 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1214 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1217 // This routine returns a DeclGroup, if the thing we parsed only contains a
1218 // single decl, convert it now. Alias declarations can also declare a type;
1219 // include that too if it is present.
1220 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1223 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1224 /// declaration-specifiers init-declarator-list[opt] ';'
1225 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1226 /// init-declarator-list ';'
1227 ///[C90/C++]init-declarator-list ';' [TODO]
1228 /// [OMP] threadprivate-directive [TODO]
1230 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1231 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1233 /// If RequireSemi is false, this does not check for a ';' at the end of the
1234 /// declaration. If it is true, it checks for and eats it.
1236 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1237 /// of a simple-declaration. If we find that we are, we also parse the
1238 /// for-range-initializer, and place it here.
1239 Parser::DeclGroupPtrTy
1240 Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1241 SourceLocation &DeclEnd,
1242 ParsedAttributesWithRange &attrs,
1243 bool RequireSemi, ForRangeInit *FRI) {
1244 // Parse the common declaration-specifiers piece.
1245 ParsingDeclSpec DS(*this);
1246 DS.takeAttributesFrom(attrs);
1248 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1249 getDeclSpecContextFromDeclaratorContext(Context));
1251 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1252 // declaration-specifiers init-declarator-list[opt] ';'
1253 if (Tok.is(tok::semi)) {
1254 DeclEnd = Tok.getLocation();
1255 if (RequireSemi) ConsumeToken();
1256 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1258 DS.complete(TheDecl);
1259 return Actions.ConvertDeclToDeclGroup(TheDecl);
1262 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1265 /// Returns true if this might be the start of a declarator, or a common typo
1266 /// for a declarator.
1267 bool Parser::MightBeDeclarator(unsigned Context) {
1268 switch (Tok.getKind()) {
1269 case tok::annot_cxxscope:
1270 case tok::annot_template_id:
1272 case tok::code_completion:
1273 case tok::coloncolon:
1275 case tok::kw___attribute:
1276 case tok::kw_operator:
1283 return getLangOpts().CPlusPlus;
1285 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1286 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x &&
1287 NextToken().is(tok::l_square);
1289 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1290 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1292 case tok::identifier:
1293 switch (NextToken().getKind()) {
1294 case tok::code_completion:
1295 case tok::coloncolon:
1298 case tok::equalequal: // Might be a typo for '='.
1299 case tok::kw_alignas:
1301 case tok::kw___attribute:
1313 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1314 // and in block scope it's probably a label. Inside a class definition,
1315 // this is a bit-field.
1316 return Context == Declarator::MemberContext ||
1317 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1319 case tok::identifier: // Possible virt-specifier.
1320 return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken());
1331 /// Skip until we reach something which seems like a sensible place to pick
1332 /// up parsing after a malformed declaration. This will sometimes stop sooner
1333 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1334 void Parser::SkipMalformedDecl() {
1336 switch (Tok.getKind()) {
1338 // Skip until matching }, then stop. We've probably skipped over
1339 // a malformed class or function definition or similar.
1341 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1342 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1343 // This declaration isn't over yet. Keep skipping.
1346 if (Tok.is(tok::semi))
1352 SkipUntil(tok::r_square, /*StopAtSemi*/false);
1357 SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1367 case tok::kw_inline:
1368 // 'inline namespace' at the start of a line is almost certainly
1369 // a good place to pick back up parsing, except in an Objective-C
1370 // @interface context.
1371 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1372 (!ParsingInObjCContainer || CurParsedObjCImpl))
1376 case tok::kw_namespace:
1377 // 'namespace' at the start of a line is almost certainly a good
1378 // place to pick back up parsing, except in an Objective-C
1379 // @interface context.
1380 if (Tok.isAtStartOfLine() &&
1381 (!ParsingInObjCContainer || CurParsedObjCImpl))
1386 // @end is very much like } in Objective-C contexts.
1387 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1388 ParsingInObjCContainer)
1394 // - and + probably start new method declarations in Objective-C contexts.
1395 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1410 /// ParseDeclGroup - Having concluded that this is either a function
1411 /// definition or a group of object declarations, actually parse the
1413 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1415 bool AllowFunctionDefinitions,
1416 SourceLocation *DeclEnd,
1417 ForRangeInit *FRI) {
1418 // Parse the first declarator.
1419 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1422 // Bail out if the first declarator didn't seem well-formed.
1423 if (!D.hasName() && !D.mayOmitIdentifier()) {
1424 SkipMalformedDecl();
1425 return DeclGroupPtrTy();
1428 // Save late-parsed attributes for now; they need to be parsed in the
1429 // appropriate function scope after the function Decl has been constructed.
1430 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1431 LateParsedAttrList LateParsedAttrs(true);
1432 if (D.isFunctionDeclarator())
1433 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1435 // Check to see if we have a function *definition* which must have a body.
1436 if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
1437 // Look at the next token to make sure that this isn't a function
1438 // declaration. We have to check this because __attribute__ might be the
1439 // start of a function definition in GCC-extended K&R C.
1440 !isDeclarationAfterDeclarator()) {
1442 if (isStartOfFunctionDefinition(D)) {
1443 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1444 Diag(Tok, diag::err_function_declared_typedef);
1446 // Recover by treating the 'typedef' as spurious.
1447 DS.ClearStorageClassSpecs();
1451 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1452 return Actions.ConvertDeclToDeclGroup(TheDecl);
1455 if (isDeclarationSpecifier()) {
1456 // If there is an invalid declaration specifier right after the function
1457 // prototype, then we must be in a missing semicolon case where this isn't
1458 // actually a body. Just fall through into the code that handles it as a
1459 // prototype, and let the top-level code handle the erroneous declspec
1460 // where it would otherwise expect a comma or semicolon.
1462 Diag(Tok, diag::err_expected_fn_body);
1463 SkipUntil(tok::semi);
1464 return DeclGroupPtrTy();
1468 if (ParseAsmAttributesAfterDeclarator(D))
1469 return DeclGroupPtrTy();
1471 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1472 // must parse and analyze the for-range-initializer before the declaration is
1474 if (FRI && Tok.is(tok::colon)) {
1475 FRI->ColonLoc = ConsumeToken();
1476 if (Tok.is(tok::l_brace))
1477 FRI->RangeExpr = ParseBraceInitializer();
1479 FRI->RangeExpr = ParseExpression();
1480 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1481 Actions.ActOnCXXForRangeDecl(ThisDecl);
1482 Actions.FinalizeDeclaration(ThisDecl);
1483 D.complete(ThisDecl);
1484 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
1487 SmallVector<Decl *, 8> DeclsInGroup;
1488 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1489 if (LateParsedAttrs.size() > 0)
1490 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1491 D.complete(FirstDecl);
1493 DeclsInGroup.push_back(FirstDecl);
1495 bool ExpectSemi = Context != Declarator::ForContext;
1497 // If we don't have a comma, it is either the end of the list (a ';') or an
1499 while (Tok.is(tok::comma)) {
1500 SourceLocation CommaLoc = ConsumeToken();
1502 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1503 // This comma was followed by a line-break and something which can't be
1504 // the start of a declarator. The comma was probably a typo for a
1506 Diag(CommaLoc, diag::err_expected_semi_declaration)
1507 << FixItHint::CreateReplacement(CommaLoc, ";");
1512 // Parse the next declarator.
1514 D.setCommaLoc(CommaLoc);
1516 // Accept attributes in an init-declarator. In the first declarator in a
1517 // declaration, these would be part of the declspec. In subsequent
1518 // declarators, they become part of the declarator itself, so that they
1519 // don't apply to declarators after *this* one. Examples:
1520 // short __attribute__((common)) var; -> declspec
1521 // short var __attribute__((common)); -> declarator
1522 // short x, __attribute__((common)) var; -> declarator
1523 MaybeParseGNUAttributes(D);
1526 if (!D.isInvalidType()) {
1527 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1528 D.complete(ThisDecl);
1530 DeclsInGroup.push_back(ThisDecl);
1535 *DeclEnd = Tok.getLocation();
1538 ExpectAndConsumeSemi(Context == Declarator::FileContext
1539 ? diag::err_invalid_token_after_toplevel_declarator
1540 : diag::err_expected_semi_declaration)) {
1541 // Okay, there was no semicolon and one was expected. If we see a
1542 // declaration specifier, just assume it was missing and continue parsing.
1543 // Otherwise things are very confused and we skip to recover.
1544 if (!isDeclarationSpecifier()) {
1545 SkipUntil(tok::r_brace, true, true);
1546 if (Tok.is(tok::semi))
1551 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
1552 DeclsInGroup.data(),
1553 DeclsInGroup.size());
1556 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1557 /// declarator. Returns true on an error.
1558 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1559 // If a simple-asm-expr is present, parse it.
1560 if (Tok.is(tok::kw_asm)) {
1562 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1563 if (AsmLabel.isInvalid()) {
1564 SkipUntil(tok::semi, true, true);
1568 D.setAsmLabel(AsmLabel.release());
1572 MaybeParseGNUAttributes(D);
1576 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1577 /// declarator'. This method parses the remainder of the declaration
1578 /// (including any attributes or initializer, among other things) and
1579 /// finalizes the declaration.
1581 /// init-declarator: [C99 6.7]
1583 /// declarator '=' initializer
1584 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1585 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1586 /// [C++] declarator initializer[opt]
1588 /// [C++] initializer:
1589 /// [C++] '=' initializer-clause
1590 /// [C++] '(' expression-list ')'
1591 /// [C++0x] '=' 'default' [TODO]
1592 /// [C++0x] '=' 'delete'
1593 /// [C++0x] braced-init-list
1595 /// According to the standard grammar, =default and =delete are function
1596 /// definitions, but that definitely doesn't fit with the parser here.
1598 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1599 const ParsedTemplateInfo &TemplateInfo) {
1600 if (ParseAsmAttributesAfterDeclarator(D))
1603 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1606 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1607 const ParsedTemplateInfo &TemplateInfo) {
1608 // Inform the current actions module that we just parsed this declarator.
1610 switch (TemplateInfo.Kind) {
1611 case ParsedTemplateInfo::NonTemplate:
1612 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1615 case ParsedTemplateInfo::Template:
1616 case ParsedTemplateInfo::ExplicitSpecialization:
1617 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1618 *TemplateInfo.TemplateParams,
1622 case ParsedTemplateInfo::ExplicitInstantiation: {
1624 = Actions.ActOnExplicitInstantiation(getCurScope(),
1625 TemplateInfo.ExternLoc,
1626 TemplateInfo.TemplateLoc,
1628 if (ThisRes.isInvalid()) {
1629 SkipUntil(tok::semi, true, true);
1633 ThisDecl = ThisRes.get();
1638 bool TypeContainsAuto =
1639 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
1641 // Parse declarator '=' initializer.
1642 // If a '==' or '+=' is found, suggest a fixit to '='.
1643 if (isTokenEqualOrEqualTypo()) {
1645 if (Tok.is(tok::kw_delete)) {
1646 if (D.isFunctionDeclarator())
1647 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1650 Diag(ConsumeToken(), diag::err_deleted_non_function);
1651 } else if (Tok.is(tok::kw_default)) {
1652 if (D.isFunctionDeclarator())
1653 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1656 Diag(ConsumeToken(), diag::err_default_special_members);
1658 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1660 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1663 if (Tok.is(tok::code_completion)) {
1664 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1665 Actions.FinalizeDeclaration(ThisDecl);
1670 ExprResult Init(ParseInitializer());
1672 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1673 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1677 if (Init.isInvalid()) {
1678 SkipUntil(tok::comma, true, true);
1679 Actions.ActOnInitializerError(ThisDecl);
1681 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1682 /*DirectInit=*/false, TypeContainsAuto);
1684 } else if (Tok.is(tok::l_paren)) {
1685 // Parse C++ direct initializer: '(' expression-list ')'
1686 BalancedDelimiterTracker T(*this, tok::l_paren);
1690 CommaLocsTy CommaLocs;
1692 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1694 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1697 if (ParseExpressionList(Exprs, CommaLocs)) {
1698 Actions.ActOnInitializerError(ThisDecl);
1699 SkipUntil(tok::r_paren);
1701 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1702 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1709 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1710 "Unexpected number of commas!");
1712 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1713 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1717 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1718 T.getCloseLocation(),
1720 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1721 /*DirectInit=*/true, TypeContainsAuto);
1723 } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace) &&
1724 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1725 // Parse C++0x braced-init-list.
1726 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1728 if (D.getCXXScopeSpec().isSet()) {
1730 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1733 ExprResult Init(ParseBraceInitializer());
1735 if (D.getCXXScopeSpec().isSet()) {
1736 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1740 if (Init.isInvalid()) {
1741 Actions.ActOnInitializerError(ThisDecl);
1743 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1744 /*DirectInit=*/true, TypeContainsAuto);
1747 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1750 Actions.FinalizeDeclaration(ThisDecl);
1755 /// ParseSpecifierQualifierList
1756 /// specifier-qualifier-list:
1757 /// type-specifier specifier-qualifier-list[opt]
1758 /// type-qualifier specifier-qualifier-list[opt]
1759 /// [GNU] attributes specifier-qualifier-list[opt]
1761 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1762 DeclSpecContext DSC) {
1763 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1764 /// parse declaration-specifiers and complain about extra stuff.
1765 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1766 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1768 // Validate declspec for type-name.
1769 unsigned Specs = DS.getParsedSpecifiers();
1770 if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
1771 !DS.hasTypeSpecifier()) {
1772 Diag(Tok, diag::err_expected_type);
1773 DS.SetTypeSpecError();
1774 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1775 !DS.hasAttributes()) {
1776 Diag(Tok, diag::err_typename_requires_specqual);
1777 if (!DS.hasTypeSpecifier())
1778 DS.SetTypeSpecError();
1781 // Issue diagnostic and remove storage class if present.
1782 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1783 if (DS.getStorageClassSpecLoc().isValid())
1784 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1786 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1787 DS.ClearStorageClassSpecs();
1790 // Issue diagnostic and remove function specfier if present.
1791 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1792 if (DS.isInlineSpecified())
1793 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1794 if (DS.isVirtualSpecified())
1795 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1796 if (DS.isExplicitSpecified())
1797 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1798 DS.ClearFunctionSpecs();
1801 // Issue diagnostic and remove constexpr specfier if present.
1802 if (DS.isConstexprSpecified()) {
1803 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1804 DS.ClearConstexprSpec();
1808 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1809 /// specified token is valid after the identifier in a declarator which
1810 /// immediately follows the declspec. For example, these things are valid:
1812 /// int x [ 4]; // direct-declarator
1813 /// int x ( int y); // direct-declarator
1814 /// int(int x ) // direct-declarator
1815 /// int x ; // simple-declaration
1816 /// int x = 17; // init-declarator-list
1817 /// int x , y; // init-declarator-list
1818 /// int x __asm__ ("foo"); // init-declarator-list
1819 /// int x : 4; // struct-declarator
1820 /// int x { 5}; // C++'0x unified initializers
1822 /// This is not, because 'x' does not immediately follow the declspec (though
1823 /// ')' happens to be valid anyway).
1826 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1827 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1828 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1829 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1833 /// ParseImplicitInt - This method is called when we have an non-typename
1834 /// identifier in a declspec (which normally terminates the decl spec) when
1835 /// the declspec has no type specifier. In this case, the declspec is either
1836 /// malformed or is "implicit int" (in K&R and C89).
1838 /// This method handles diagnosing this prettily and returns false if the
1839 /// declspec is done being processed. If it recovers and thinks there may be
1840 /// other pieces of declspec after it, it returns true.
1842 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1843 const ParsedTemplateInfo &TemplateInfo,
1844 AccessSpecifier AS, DeclSpecContext DSC) {
1845 assert(Tok.is(tok::identifier) && "should have identifier");
1847 SourceLocation Loc = Tok.getLocation();
1848 // If we see an identifier that is not a type name, we normally would
1849 // parse it as the identifer being declared. However, when a typename
1850 // is typo'd or the definition is not included, this will incorrectly
1851 // parse the typename as the identifier name and fall over misparsing
1852 // later parts of the diagnostic.
1854 // As such, we try to do some look-ahead in cases where this would
1855 // otherwise be an "implicit-int" case to see if this is invalid. For
1856 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
1857 // an identifier with implicit int, we'd get a parse error because the
1858 // next token is obviously invalid for a type. Parse these as a case
1859 // with an invalid type specifier.
1860 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1862 // Since we know that this either implicit int (which is rare) or an
1863 // error, do lookahead to try to do better recovery. This never applies
1864 // within a type specifier. Outside of C++, we allow this even if the
1865 // language doesn't "officially" support implicit int -- we support
1866 // implicit int as an extension in C99 and C11. Allegedly, MS also
1867 // supports implicit int in C++ mode.
1868 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
1869 (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) &&
1870 isValidAfterIdentifierInDeclarator(NextToken())) {
1871 // If this token is valid for implicit int, e.g. "static x = 4", then
1872 // we just avoid eating the identifier, so it will be parsed as the
1873 // identifier in the declarator.
1877 if (getLangOpts().CPlusPlus &&
1878 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
1879 // Don't require a type specifier if we have the 'auto' storage class
1880 // specifier in C++98 -- we'll promote it to a type specifier.
1884 // Otherwise, if we don't consume this token, we are going to emit an
1885 // error anyway. Try to recover from various common problems. Check
1886 // to see if this was a reference to a tag name without a tag specified.
1887 // This is a common problem in C (saying 'foo' instead of 'struct foo').
1889 // C++ doesn't need this, and isTagName doesn't take SS.
1891 const char *TagName = 0, *FixitTagName = 0;
1892 tok::TokenKind TagKind = tok::unknown;
1894 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1896 case DeclSpec::TST_enum:
1897 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
1898 case DeclSpec::TST_union:
1899 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1900 case DeclSpec::TST_struct:
1901 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1902 case DeclSpec::TST_interface:
1903 TagName="__interface"; FixitTagName = "__interface ";
1904 TagKind=tok::kw___interface;break;
1905 case DeclSpec::TST_class:
1906 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1910 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
1911 LookupResult R(Actions, TokenName, SourceLocation(),
1912 Sema::LookupOrdinaryName);
1914 Diag(Loc, diag::err_use_of_tag_name_without_tag)
1915 << TokenName << TagName << getLangOpts().CPlusPlus
1916 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
1918 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
1919 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
1921 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
1922 << TokenName << TagName;
1925 // Parse this as a tag as if the missing tag were present.
1926 if (TagKind == tok::kw_enum)
1927 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
1929 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
1930 /*EnteringContext*/ false, DSC_normal);
1935 // Determine whether this identifier could plausibly be the name of something
1936 // being declared (with a missing type).
1937 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
1938 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
1939 // Look ahead to the next token to try to figure out what this declaration
1940 // was supposed to be.
1941 switch (NextToken().getKind()) {
1948 // This looks like a variable declaration. The type is probably missing.
1949 // We're done parsing decl-specifiers.
1952 case tok::l_paren: {
1953 // static x(4); // 'x' is not a type
1954 // x(int n); // 'x' is not a type
1955 // x (*p)[]; // 'x' is a type
1957 // Since we're in an error case (or the rare 'implicit int in C++' MS
1958 // extension), we can afford to perform a tentative parse to determine
1959 // which case we're in.
1960 TentativeParsingAction PA(*this);
1962 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
1964 if (TPR == TPResult::False())
1966 // The identifier is followed by a parenthesized declarator.
1967 // It's supposed to be a type.
1972 // This is probably supposed to be a type. This includes cases like:
1974 // struct S { unsinged : 4; };
1979 // This is almost certainly an invalid type name. Let the action emit a
1980 // diagnostic and attempt to recover.
1982 IdentifierInfo *II = Tok.getIdentifierInfo();
1983 if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
1984 // The action emitted a diagnostic, so we don't have to.
1986 // The action has suggested that the type T could be used. Set that as
1987 // the type in the declaration specifiers, consume the would-be type
1988 // name token, and we're done.
1989 const char *PrevSpec;
1991 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1992 DS.SetRangeEnd(Tok.getLocation());
1994 // There may be other declaration specifiers after this.
1996 } else if (II != Tok.getIdentifierInfo()) {
1997 // If no type was suggested, the correction is to a keyword
1998 Tok.setKind(II->getTokenID());
1999 // There may be other declaration specifiers after this.
2003 // Fall through; the action had no suggestion for us.
2005 // The action did not emit a diagnostic, so emit one now.
2007 if (SS) R = SS->getRange();
2008 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
2011 // Mark this as an error.
2012 DS.SetTypeSpecError();
2013 DS.SetRangeEnd(Tok.getLocation());
2016 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2017 // avoid rippling error messages on subsequent uses of the same type,
2018 // could be useful if #include was forgotten.
2022 /// \brief Determine the declaration specifier context from the declarator
2025 /// \param Context the declarator context, which is one of the
2026 /// Declarator::TheContext enumerator values.
2027 Parser::DeclSpecContext
2028 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2029 if (Context == Declarator::MemberContext)
2031 if (Context == Declarator::FileContext)
2032 return DSC_top_level;
2033 if (Context == Declarator::TrailingReturnContext)
2034 return DSC_trailing;
2038 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2040 /// FIXME: Simply returns an alignof() expression if the argument is a
2041 /// type. Ideally, the type should be propagated directly into Sema.
2044 /// [C11] constant-expression
2045 /// [C++0x] type-id ...[opt]
2046 /// [C++0x] assignment-expression ...[opt]
2047 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2048 SourceLocation &EllipsisLoc) {
2050 if (isTypeIdInParens()) {
2051 SourceLocation TypeLoc = Tok.getLocation();
2052 ParsedType Ty = ParseTypeName().get();
2053 SourceRange TypeRange(Start, Tok.getLocation());
2054 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2055 Ty.getAsOpaquePtr(), TypeRange);
2057 ER = ParseConstantExpression();
2059 if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
2060 EllipsisLoc = ConsumeToken();
2065 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2066 /// attribute to Attrs.
2068 /// alignment-specifier:
2069 /// [C11] '_Alignas' '(' type-id ')'
2070 /// [C11] '_Alignas' '(' constant-expression ')'
2071 /// [C++0x] 'alignas' '(' type-id ...[opt] ')'
2072 /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
2073 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2074 SourceLocation *endLoc) {
2075 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2076 "Not an alignment-specifier!");
2078 SourceLocation KWLoc = Tok.getLocation();
2081 BalancedDelimiterTracker T(*this, tok::l_paren);
2082 if (T.expectAndConsume(diag::err_expected_lparen))
2085 SourceLocation EllipsisLoc;
2086 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2087 if (ArgExpr.isInvalid()) {
2088 SkipUntil(tok::r_paren);
2094 *endLoc = T.getCloseLocation();
2096 // FIXME: Handle pack-expansions here.
2097 if (EllipsisLoc.isValid()) {
2098 Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
2102 ExprVector ArgExprs;
2103 ArgExprs.push_back(ArgExpr.release());
2104 // FIXME: This should not be GNU, but we since the attribute used is
2105 // based on the spelling, and there is no true spelling for
2106 // C++11 attributes, this isn't accepted.
2107 Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
2108 0, T.getOpenLocation(), ArgExprs.data(), 1,
2109 AttributeList::AS_GNU);
2112 /// ParseDeclarationSpecifiers
2113 /// declaration-specifiers: [C99 6.7]
2114 /// storage-class-specifier declaration-specifiers[opt]
2115 /// type-specifier declaration-specifiers[opt]
2116 /// [C99] function-specifier declaration-specifiers[opt]
2117 /// [C11] alignment-specifier declaration-specifiers[opt]
2118 /// [GNU] attributes declaration-specifiers[opt]
2119 /// [Clang] '__module_private__' declaration-specifiers[opt]
2121 /// storage-class-specifier: [C99 6.7.1]
2128 /// [GNU] '__thread'
2129 /// function-specifier: [C99 6.7.4]
2132 /// [C++] 'explicit'
2133 /// [OpenCL] '__kernel'
2134 /// 'friend': [C++ dcl.friend]
2135 /// 'constexpr': [C++0x dcl.constexpr]
2138 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2139 const ParsedTemplateInfo &TemplateInfo,
2141 DeclSpecContext DSContext,
2142 LateParsedAttrList *LateAttrs) {
2143 if (DS.getSourceRange().isInvalid()) {
2144 DS.SetRangeStart(Tok.getLocation());
2145 DS.SetRangeEnd(Tok.getLocation());
2148 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2149 bool AttrsLastTime = false;
2150 ParsedAttributesWithRange attrs(AttrFactory);
2152 bool isInvalid = false;
2153 const char *PrevSpec = 0;
2154 unsigned DiagID = 0;
2156 SourceLocation Loc = Tok.getLocation();
2158 switch (Tok.getKind()) {
2162 ProhibitAttributes(attrs);
2164 // Reject C++11 attributes that appertain to decl specifiers as
2165 // we don't support any C++11 attributes that appertain to decl
2166 // specifiers. This also conforms to what g++ 4.8 is doing.
2167 ProhibitCXX11Attributes(attrs);
2169 DS.takeAttributesFrom(attrs);
2172 // If this is not a declaration specifier token, we're done reading decl
2173 // specifiers. First verify that DeclSpec's are consistent.
2174 DS.Finish(Diags, PP);
2178 case tok::kw_alignas:
2179 if (!isCXX11AttributeSpecifier())
2180 goto DoneWithDeclSpec;
2182 ProhibitAttributes(attrs);
2183 // FIXME: It would be good to recover by accepting the attributes,
2184 // but attempting to do that now would cause serious
2185 // madness in terms of diagnostics.
2187 attrs.Range = SourceRange();
2189 ParseCXX11Attributes(attrs);
2190 AttrsLastTime = true;
2193 case tok::code_completion: {
2194 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2195 if (DS.hasTypeSpecifier()) {
2196 bool AllowNonIdentifiers
2197 = (getCurScope()->getFlags() & (Scope::ControlScope |
2199 Scope::TemplateParamScope |
2200 Scope::FunctionPrototypeScope |
2201 Scope::AtCatchScope)) == 0;
2202 bool AllowNestedNameSpecifiers
2203 = DSContext == DSC_top_level ||
2204 (DSContext == DSC_class && DS.isFriendSpecified());
2206 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2207 AllowNonIdentifiers,
2208 AllowNestedNameSpecifiers);
2209 return cutOffParsing();
2212 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2213 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2214 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2215 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2216 : Sema::PCC_Template;
2217 else if (DSContext == DSC_class)
2218 CCC = Sema::PCC_Class;
2219 else if (CurParsedObjCImpl)
2220 CCC = Sema::PCC_ObjCImplementation;
2222 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2223 return cutOffParsing();
2226 case tok::coloncolon: // ::foo::bar
2227 // C++ scope specifier. Annotate and loop, or bail out on error.
2228 if (TryAnnotateCXXScopeToken(true)) {
2229 if (!DS.hasTypeSpecifier())
2230 DS.SetTypeSpecError();
2231 goto DoneWithDeclSpec;
2233 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2234 goto DoneWithDeclSpec;
2237 case tok::annot_cxxscope: {
2238 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2239 goto DoneWithDeclSpec;
2242 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2243 Tok.getAnnotationRange(),
2246 // We are looking for a qualified typename.
2247 Token Next = NextToken();
2248 if (Next.is(tok::annot_template_id) &&
2249 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2250 ->Kind == TNK_Type_template) {
2251 // We have a qualified template-id, e.g., N::A<int>
2253 // C++ [class.qual]p2:
2254 // In a lookup in which the constructor is an acceptable lookup
2255 // result and the nested-name-specifier nominates a class C:
2257 // - if the name specified after the
2258 // nested-name-specifier, when looked up in C, is the
2259 // injected-class-name of C (Clause 9), or
2261 // - if the name specified after the nested-name-specifier
2262 // is the same as the identifier or the
2263 // simple-template-id's template-name in the last
2264 // component of the nested-name-specifier,
2266 // the name is instead considered to name the constructor of
2269 // Thus, if the template-name is actually the constructor
2270 // name, then the code is ill-formed; this interpretation is
2271 // reinforced by the NAD status of core issue 635.
2272 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2273 if ((DSContext == DSC_top_level ||
2274 (DSContext == DSC_class && DS.isFriendSpecified())) &&
2276 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2277 if (isConstructorDeclarator()) {
2278 // The user meant this to be an out-of-line constructor
2279 // definition, but template arguments are not allowed
2280 // there. Just allow this as a constructor; we'll
2281 // complain about it later.
2282 goto DoneWithDeclSpec;
2285 // The user meant this to name a type, but it actually names
2286 // a constructor with some extraneous template
2287 // arguments. Complain, then parse it as a type as the user
2289 Diag(TemplateId->TemplateNameLoc,
2290 diag::err_out_of_line_template_id_names_constructor)
2291 << TemplateId->Name;
2294 DS.getTypeSpecScope() = SS;
2295 ConsumeToken(); // The C++ scope.
2296 assert(Tok.is(tok::annot_template_id) &&
2297 "ParseOptionalCXXScopeSpecifier not working");
2298 AnnotateTemplateIdTokenAsType();
2302 if (Next.is(tok::annot_typename)) {
2303 DS.getTypeSpecScope() = SS;
2304 ConsumeToken(); // The C++ scope.
2305 if (Tok.getAnnotationValue()) {
2306 ParsedType T = getTypeAnnotation(Tok);
2307 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2308 Tok.getAnnotationEndLoc(),
2309 PrevSpec, DiagID, T);
2314 DS.SetTypeSpecError();
2315 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2316 ConsumeToken(); // The typename
2319 if (Next.isNot(tok::identifier))
2320 goto DoneWithDeclSpec;
2322 // If we're in a context where the identifier could be a class name,
2323 // check whether this is a constructor declaration.
2324 if ((DSContext == DSC_top_level ||
2325 (DSContext == DSC_class && DS.isFriendSpecified())) &&
2326 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2328 if (isConstructorDeclarator())
2329 goto DoneWithDeclSpec;
2331 // As noted in C++ [class.qual]p2 (cited above), when the name
2332 // of the class is qualified in a context where it could name
2333 // a constructor, its a constructor name. However, we've
2334 // looked at the declarator, and the user probably meant this
2335 // to be a type. Complain that it isn't supposed to be treated
2336 // as a type, then proceed to parse it as a type.
2337 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2338 << Next.getIdentifierInfo();
2341 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2344 false, false, ParsedType(),
2345 /*IsCtorOrDtorName=*/false,
2346 /*NonTrivialSourceInfo=*/true);
2348 // If the referenced identifier is not a type, then this declspec is
2349 // erroneous: We already checked about that it has no type specifier, and
2350 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2353 ConsumeToken(); // Eat the scope spec so the identifier is current.
2354 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue;
2355 goto DoneWithDeclSpec;
2358 DS.getTypeSpecScope() = SS;
2359 ConsumeToken(); // The C++ scope.
2361 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2366 DS.SetRangeEnd(Tok.getLocation());
2367 ConsumeToken(); // The typename.
2372 case tok::annot_typename: {
2373 if (Tok.getAnnotationValue()) {
2374 ParsedType T = getTypeAnnotation(Tok);
2375 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2378 DS.SetTypeSpecError();
2383 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2384 ConsumeToken(); // The typename
2386 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2387 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2388 // Objective-C interface.
2389 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2390 ParseObjCProtocolQualifiers(DS);
2395 case tok::kw___is_signed:
2396 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2397 // typically treats it as a trait. If we see __is_signed as it appears
2398 // in libstdc++, e.g.,
2400 // static const bool __is_signed;
2402 // then treat __is_signed as an identifier rather than as a keyword.
2403 if (DS.getTypeSpecType() == TST_bool &&
2404 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2405 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2406 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2407 Tok.setKind(tok::identifier);
2410 // We're done with the declaration-specifiers.
2411 goto DoneWithDeclSpec;
2414 case tok::kw_decltype:
2415 case tok::identifier: {
2416 // In C++, check to see if this is a scope specifier like foo::bar::, if
2417 // so handle it as such. This is important for ctor parsing.
2418 if (getLangOpts().CPlusPlus) {
2419 if (TryAnnotateCXXScopeToken(true)) {
2420 if (!DS.hasTypeSpecifier())
2421 DS.SetTypeSpecError();
2422 goto DoneWithDeclSpec;
2424 if (!Tok.is(tok::identifier))
2428 // This identifier can only be a typedef name if we haven't already seen
2429 // a type-specifier. Without this check we misparse:
2430 // typedef int X; struct Y { short X; }; as 'short int'.
2431 if (DS.hasTypeSpecifier())
2432 goto DoneWithDeclSpec;
2434 // Check for need to substitute AltiVec keyword tokens.
2435 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2438 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2439 // allow the use of a typedef name as a type specifier.
2440 if (DS.isTypeAltiVecVector())
2441 goto DoneWithDeclSpec;
2443 ParsedType TypeRep =
2444 Actions.getTypeName(*Tok.getIdentifierInfo(),
2445 Tok.getLocation(), getCurScope());
2447 // If this is not a typedef name, don't parse it as part of the declspec,
2448 // it must be an implicit int or an error.
2450 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
2451 goto DoneWithDeclSpec;
2454 // If we're in a context where the identifier could be a class name,
2455 // check whether this is a constructor declaration.
2456 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2457 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2458 isConstructorDeclarator())
2459 goto DoneWithDeclSpec;
2461 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2466 DS.SetRangeEnd(Tok.getLocation());
2467 ConsumeToken(); // The identifier
2469 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2470 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2471 // Objective-C interface.
2472 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2473 ParseObjCProtocolQualifiers(DS);
2475 // Need to support trailing type qualifiers (e.g. "id<p> const").
2476 // If a type specifier follows, it will be diagnosed elsewhere.
2481 case tok::annot_template_id: {
2482 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2483 if (TemplateId->Kind != TNK_Type_template) {
2484 // This template-id does not refer to a type name, so we're
2485 // done with the type-specifiers.
2486 goto DoneWithDeclSpec;
2489 // If we're in a context where the template-id could be a
2490 // constructor name or specialization, check whether this is a
2491 // constructor declaration.
2492 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2493 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2494 isConstructorDeclarator())
2495 goto DoneWithDeclSpec;
2497 // Turn the template-id annotation token into a type annotation
2498 // token, then try again to parse it as a type-specifier.
2499 AnnotateTemplateIdTokenAsType();
2503 // GNU attributes support.
2504 case tok::kw___attribute:
2505 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2508 // Microsoft declspec support.
2509 case tok::kw___declspec:
2510 ParseMicrosoftDeclSpec(DS.getAttributes());
2513 // Microsoft single token adornments.
2514 case tok::kw___forceinline: {
2515 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2516 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2517 SourceLocation AttrNameLoc = Tok.getLocation();
2518 // FIXME: This does not work correctly if it is set to be a declspec
2519 // attribute, and a GNU attribute is simply incorrect.
2520 DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
2521 SourceLocation(), 0, 0, AttributeList::AS_GNU);
2525 case tok::kw___ptr64:
2526 case tok::kw___ptr32:
2528 case tok::kw___cdecl:
2529 case tok::kw___stdcall:
2530 case tok::kw___fastcall:
2531 case tok::kw___thiscall:
2532 case tok::kw___unaligned:
2533 ParseMicrosoftTypeAttributes(DS.getAttributes());
2536 // Borland single token adornments.
2537 case tok::kw___pascal:
2538 ParseBorlandTypeAttributes(DS.getAttributes());
2541 // OpenCL single token adornments.
2542 case tok::kw___kernel:
2543 ParseOpenCLAttributes(DS.getAttributes());
2546 // storage-class-specifier
2547 case tok::kw_typedef:
2548 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2551 case tok::kw_extern:
2552 if (DS.isThreadSpecified())
2553 Diag(Tok, diag::ext_thread_before) << "extern";
2554 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2557 case tok::kw___private_extern__:
2558 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2559 Loc, PrevSpec, DiagID);
2561 case tok::kw_static:
2562 if (DS.isThreadSpecified())
2563 Diag(Tok, diag::ext_thread_before) << "static";
2564 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2568 if (getLangOpts().CPlusPlus0x) {
2569 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2570 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2573 Diag(Tok, diag::ext_auto_storage_class)
2574 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2579 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2582 case tok::kw_register:
2583 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2586 case tok::kw_mutable:
2587 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2590 case tok::kw___thread:
2591 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
2594 // function-specifier
2595 case tok::kw_inline:
2596 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
2598 case tok::kw_virtual:
2599 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
2601 case tok::kw_explicit:
2602 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
2605 // alignment-specifier
2606 case tok::kw__Alignas:
2607 if (!getLangOpts().C11)
2608 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2609 ParseAlignmentSpecifier(DS.getAttributes());
2613 case tok::kw_friend:
2614 if (DSContext == DSC_class)
2615 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2617 PrevSpec = ""; // not actually used by the diagnostic
2618 DiagID = diag::err_friend_invalid_in_context;
2624 case tok::kw___module_private__:
2625 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2629 case tok::kw_constexpr:
2630 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2635 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2639 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2640 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2643 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2646 case tok::kw___int64:
2647 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2650 case tok::kw_signed:
2651 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2654 case tok::kw_unsigned:
2655 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2658 case tok::kw__Complex:
2659 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2662 case tok::kw__Imaginary:
2663 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2667 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2671 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2675 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2678 case tok::kw___int128:
2679 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2683 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2687 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2690 case tok::kw_double:
2691 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2694 case tok::kw_wchar_t:
2695 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2698 case tok::kw_char16_t:
2699 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2702 case tok::kw_char32_t:
2703 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2708 if (Tok.is(tok::kw_bool) &&
2709 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2710 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2711 PrevSpec = ""; // Not used by the diagnostic.
2712 DiagID = diag::err_bool_redeclaration;
2713 // For better error recovery.
2714 Tok.setKind(tok::identifier);
2717 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2721 case tok::kw__Decimal32:
2722 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2725 case tok::kw__Decimal64:
2726 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2729 case tok::kw__Decimal128:
2730 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2733 case tok::kw___vector:
2734 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2736 case tok::kw___pixel:
2737 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2739 case tok::kw___unknown_anytype:
2740 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
2746 case tok::kw_struct:
2747 case tok::kw___interface:
2748 case tok::kw_union: {
2749 tok::TokenKind Kind = Tok.getKind();
2751 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
2752 EnteringContext, DSContext);
2759 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
2764 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
2767 case tok::kw_volatile:
2768 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2771 case tok::kw_restrict:
2772 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2776 // C++ typename-specifier:
2777 case tok::kw_typename:
2778 if (TryAnnotateTypeOrScopeToken()) {
2779 DS.SetTypeSpecError();
2780 goto DoneWithDeclSpec;
2782 if (!Tok.is(tok::kw_typename))
2786 // GNU typeof support.
2787 case tok::kw_typeof:
2788 ParseTypeofSpecifier(DS);
2791 case tok::annot_decltype:
2792 ParseDecltypeSpecifier(DS);
2795 case tok::kw___underlying_type:
2796 ParseUnderlyingTypeSpecifier(DS);
2799 case tok::kw__Atomic:
2800 ParseAtomicSpecifier(DS);
2803 // OpenCL qualifiers:
2804 case tok::kw_private:
2805 if (!getLangOpts().OpenCL)
2806 goto DoneWithDeclSpec;
2807 case tok::kw___private:
2808 case tok::kw___global:
2809 case tok::kw___local:
2810 case tok::kw___constant:
2811 case tok::kw___read_only:
2812 case tok::kw___write_only:
2813 case tok::kw___read_write:
2814 ParseOpenCLQualifiers(DS);
2818 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
2819 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
2820 // but we support it.
2821 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
2822 goto DoneWithDeclSpec;
2824 if (!ParseObjCProtocolQualifiers(DS))
2825 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
2826 << FixItHint::CreateInsertion(Loc, "id")
2827 << SourceRange(Loc, DS.getSourceRange().getEnd());
2829 // Need to support trailing type qualifiers (e.g. "id<p> const").
2830 // If a type specifier follows, it will be diagnosed elsewhere.
2833 // If the specifier wasn't legal, issue a diagnostic.
2835 assert(PrevSpec && "Method did not return previous specifier!");
2838 if (DiagID == diag::ext_duplicate_declspec)
2840 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
2842 Diag(Tok, DiagID) << PrevSpec;
2845 DS.SetRangeEnd(Tok.getLocation());
2846 if (DiagID != diag::err_bool_redeclaration)
2849 AttrsLastTime = false;
2853 /// ParseStructDeclaration - Parse a struct declaration without the terminating
2856 /// struct-declaration:
2857 /// specifier-qualifier-list struct-declarator-list
2858 /// [GNU] __extension__ struct-declaration
2859 /// [GNU] specifier-qualifier-list
2860 /// struct-declarator-list:
2861 /// struct-declarator
2862 /// struct-declarator-list ',' struct-declarator
2863 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
2864 /// struct-declarator:
2866 /// [GNU] declarator attributes[opt]
2867 /// declarator[opt] ':' constant-expression
2868 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
2871 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
2873 if (Tok.is(tok::kw___extension__)) {
2874 // __extension__ silences extension warnings in the subexpression.
2875 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2877 return ParseStructDeclaration(DS, Fields);
2880 // Parse the common specifier-qualifiers-list piece.
2881 ParseSpecifierQualifierList(DS);
2883 // If there are no declarators, this is a free-standing declaration
2884 // specifier. Let the actions module cope with it.
2885 if (Tok.is(tok::semi)) {
2886 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
2888 DS.complete(TheDecl);
2892 // Read struct-declarators until we find the semicolon.
2893 bool FirstDeclarator = true;
2894 SourceLocation CommaLoc;
2896 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
2897 DeclaratorInfo.D.setCommaLoc(CommaLoc);
2899 // Attributes are only allowed here on successive declarators.
2900 if (!FirstDeclarator)
2901 MaybeParseGNUAttributes(DeclaratorInfo.D);
2903 /// struct-declarator: declarator
2904 /// struct-declarator: declarator[opt] ':' constant-expression
2905 if (Tok.isNot(tok::colon)) {
2906 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2907 ColonProtectionRAIIObject X(*this);
2908 ParseDeclarator(DeclaratorInfo.D);
2911 if (Tok.is(tok::colon)) {
2913 ExprResult Res(ParseConstantExpression());
2914 if (Res.isInvalid())
2915 SkipUntil(tok::semi, true, true);
2917 DeclaratorInfo.BitfieldSize = Res.release();
2920 // If attributes exist after the declarator, parse them.
2921 MaybeParseGNUAttributes(DeclaratorInfo.D);
2923 // We're done with this declarator; invoke the callback.
2924 Fields.invoke(DeclaratorInfo);
2926 // If we don't have a comma, it is either the end of the list (a ';')
2927 // or an error, bail out.
2928 if (Tok.isNot(tok::comma))
2931 // Consume the comma.
2932 CommaLoc = ConsumeToken();
2934 FirstDeclarator = false;
2938 /// ParseStructUnionBody
2939 /// struct-contents:
2940 /// struct-declaration-list
2942 /// [GNU] "struct-declaration-list" without terminatoring ';'
2943 /// struct-declaration-list:
2944 /// struct-declaration
2945 /// struct-declaration-list struct-declaration
2946 /// [OBC] '@' 'defs' '(' class-name ')'
2948 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2949 unsigned TagType, Decl *TagDecl) {
2950 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2951 "parsing struct/union body");
2953 BalancedDelimiterTracker T(*this, tok::l_brace);
2954 if (T.consumeOpen())
2957 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2958 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2960 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2962 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
2963 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
2964 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
2967 SmallVector<Decl *, 32> FieldDecls;
2969 // While we still have something to read, read the declarations in the struct.
2970 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2971 // Each iteration of this loop reads one struct-declaration.
2973 // Check for extraneous top-level semicolon.
2974 if (Tok.is(tok::semi)) {
2975 ConsumeExtraSemi(InsideStruct, TagType);
2979 if (!Tok.is(tok::at)) {
2980 struct CFieldCallback : FieldCallback {
2983 SmallVectorImpl<Decl *> &FieldDecls;
2985 CFieldCallback(Parser &P, Decl *TagDecl,
2986 SmallVectorImpl<Decl *> &FieldDecls) :
2987 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2989 void invoke(ParsingFieldDeclarator &FD) {
2990 // Install the declarator into the current TagDecl.
2991 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2992 FD.D.getDeclSpec().getSourceRange().getBegin(),
2993 FD.D, FD.BitfieldSize);
2994 FieldDecls.push_back(Field);
2997 } Callback(*this, TagDecl, FieldDecls);
2999 // Parse all the comma separated declarators.
3000 ParsingDeclSpec DS(*this);
3001 ParseStructDeclaration(DS, Callback);
3002 } else { // Handle @defs
3004 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3005 Diag(Tok, diag::err_unexpected_at);
3006 SkipUntil(tok::semi, true);
3010 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
3011 if (!Tok.is(tok::identifier)) {
3012 Diag(Tok, diag::err_expected_ident);
3013 SkipUntil(tok::semi, true);
3016 SmallVector<Decl *, 16> Fields;
3017 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3018 Tok.getIdentifierInfo(), Fields);
3019 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3021 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
3024 if (Tok.is(tok::semi)) {
3026 } else if (Tok.is(tok::r_brace)) {
3027 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3030 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3031 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3032 SkipUntil(tok::r_brace, true, true);
3033 // If we stopped at a ';', eat it.
3034 if (Tok.is(tok::semi)) ConsumeToken();
3040 ParsedAttributes attrs(AttrFactory);
3041 // If attributes exist after struct contents, parse them.
3042 MaybeParseGNUAttributes(attrs);
3044 Actions.ActOnFields(getCurScope(),
3045 RecordLoc, TagDecl, FieldDecls,
3046 T.getOpenLocation(), T.getCloseLocation(),
3049 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3050 T.getCloseLocation());
3053 /// ParseEnumSpecifier
3054 /// enum-specifier: [C99 6.7.2.2]
3055 /// 'enum' identifier[opt] '{' enumerator-list '}'
3056 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3057 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3058 /// '}' attributes[opt]
3059 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3061 /// 'enum' identifier
3062 /// [GNU] 'enum' attributes[opt] identifier
3064 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3065 /// [C++11] enum-head '{' enumerator-list ',' '}'
3067 /// enum-head: [C++11]
3068 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3069 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3070 /// identifier enum-base[opt]
3072 /// enum-key: [C++11]
3077 /// enum-base: [C++11]
3078 /// ':' type-specifier-seq
3080 /// [C++] elaborated-type-specifier:
3081 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3083 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3084 const ParsedTemplateInfo &TemplateInfo,
3085 AccessSpecifier AS, DeclSpecContext DSC) {
3086 // Parse the tag portion of this.
3087 if (Tok.is(tok::code_completion)) {
3088 // Code completion for an enum name.
3089 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3090 return cutOffParsing();
3093 // If attributes exist after tag, parse them.
3094 ParsedAttributesWithRange attrs(AttrFactory);
3095 MaybeParseGNUAttributes(attrs);
3096 MaybeParseCXX0XAttributes(attrs);
3098 // If declspecs exist after tag, parse them.
3099 while (Tok.is(tok::kw___declspec))
3100 ParseMicrosoftDeclSpec(attrs);
3102 SourceLocation ScopedEnumKWLoc;
3103 bool IsScopedUsingClassTag = false;
3105 // In C++11, recognize 'enum class' and 'enum struct'.
3106 if (getLangOpts().CPlusPlus0x &&
3107 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
3108 Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
3109 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3110 ScopedEnumKWLoc = ConsumeToken();
3112 // Attributes are not allowed between these keywords. Diagnose,
3113 // but then just treat them like they appeared in the right place.
3114 ProhibitAttributes(attrs);
3116 // They are allowed afterwards, though.
3117 MaybeParseGNUAttributes(attrs);
3118 MaybeParseCXX0XAttributes(attrs);
3119 while (Tok.is(tok::kw___declspec))
3120 ParseMicrosoftDeclSpec(attrs);
3123 // C++11 [temp.explicit]p12:
3124 // The usual access controls do not apply to names used to specify
3125 // explicit instantiations.
3126 // We extend this to also cover explicit specializations. Note that
3127 // we don't suppress if this turns out to be an elaborated type
3129 bool shouldDelayDiagsInTag =
3130 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3131 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3132 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3134 // Enum definitions should not be parsed in a trailing-return-type.
3135 bool AllowDeclaration = DSC != DSC_trailing;
3137 bool AllowFixedUnderlyingType = AllowDeclaration &&
3138 (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
3139 getLangOpts().ObjC2);
3141 CXXScopeSpec &SS = DS.getTypeSpecScope();
3142 if (getLangOpts().CPlusPlus) {
3143 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3144 // if a fixed underlying type is allowed.
3145 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3147 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3148 /*EnteringContext=*/false))
3151 if (SS.isSet() && Tok.isNot(tok::identifier)) {
3152 Diag(Tok, diag::err_expected_ident);
3153 if (Tok.isNot(tok::l_brace)) {
3154 // Has no name and is not a definition.
3155 // Skip the rest of this declarator, up until the comma or semicolon.
3156 SkipUntil(tok::comma, true);
3162 // Must have either 'enum name' or 'enum {...}'.
3163 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3164 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3165 Diag(Tok, diag::err_expected_ident_lbrace);
3167 // Skip the rest of this declarator, up until the comma or semicolon.
3168 SkipUntil(tok::comma, true);
3172 // If an identifier is present, consume and remember it.
3173 IdentifierInfo *Name = 0;
3174 SourceLocation NameLoc;
3175 if (Tok.is(tok::identifier)) {
3176 Name = Tok.getIdentifierInfo();
3177 NameLoc = ConsumeToken();
3180 if (!Name && ScopedEnumKWLoc.isValid()) {
3181 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3182 // declaration of a scoped enumeration.
3183 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3184 ScopedEnumKWLoc = SourceLocation();
3185 IsScopedUsingClassTag = false;
3188 // Okay, end the suppression area. We'll decide whether to emit the
3189 // diagnostics in a second.
3190 if (shouldDelayDiagsInTag)
3191 diagsFromTag.done();
3193 TypeResult BaseType;
3195 // Parse the fixed underlying type.
3196 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3197 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3198 bool PossibleBitfield = false;
3199 if (CanBeBitfield) {
3200 // If we're in class scope, this can either be an enum declaration with
3201 // an underlying type, or a declaration of a bitfield member. We try to
3202 // use a simple disambiguation scheme first to catch the common cases
3203 // (integer literal, sizeof); if it's still ambiguous, we then consider
3204 // anything that's a simple-type-specifier followed by '(' as an
3205 // expression. This suffices because function types are not valid
3206 // underlying types anyway.
3207 EnterExpressionEvaluationContext Unevaluated(Actions,
3208 Sema::ConstantEvaluated);
3209 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3210 // If the next token starts an expression, we know we're parsing a
3211 // bit-field. This is the common case.
3212 if (TPR == TPResult::True())
3213 PossibleBitfield = true;
3214 // If the next token starts a type-specifier-seq, it may be either a
3215 // a fixed underlying type or the start of a function-style cast in C++;
3216 // lookahead one more token to see if it's obvious that we have a
3217 // fixed underlying type.
3218 else if (TPR == TPResult::False() &&
3219 GetLookAheadToken(2).getKind() == tok::semi) {
3223 // We have the start of a type-specifier-seq, so we have to perform
3224 // tentative parsing to determine whether we have an expression or a
3226 TentativeParsingAction TPA(*this);
3231 // If we see a type specifier followed by an open-brace, we have an
3232 // ambiguity between an underlying type and a C++11 braced
3233 // function-style cast. Resolve this by always treating it as an
3235 // FIXME: The standard is not entirely clear on how to disambiguate in
3237 if ((getLangOpts().CPlusPlus &&
3238 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
3239 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3240 // We'll parse this as a bitfield later.
3241 PossibleBitfield = true;
3244 // We have a type-specifier-seq.
3253 if (!PossibleBitfield) {
3255 BaseType = ParseTypeName(&Range);
3257 if (getLangOpts().CPlusPlus0x) {
3258 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3259 } else if (!getLangOpts().ObjC2) {
3260 if (getLangOpts().CPlusPlus)
3261 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3263 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3268 // There are four options here. If we have 'friend enum foo;' then this is a
3269 // friend declaration, and cannot have an accompanying definition. If we have
3270 // 'enum foo;', then this is a forward declaration. If we have
3271 // 'enum foo {...' then this is a definition. Otherwise we have something
3272 // like 'enum foo xyz', a reference.
3274 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3275 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3276 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3278 Sema::TagUseKind TUK;
3279 if (!AllowDeclaration) {
3280 TUK = Sema::TUK_Reference;
3281 } else if (Tok.is(tok::l_brace)) {
3282 if (DS.isFriendSpecified()) {
3283 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3284 << SourceRange(DS.getFriendSpecLoc());
3286 SkipUntil(tok::r_brace);
3287 TUK = Sema::TUK_Friend;
3289 TUK = Sema::TUK_Definition;
3291 } else if (DSC != DSC_type_specifier &&
3292 (Tok.is(tok::semi) ||
3293 (Tok.isAtStartOfLine() &&
3294 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3295 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3296 if (Tok.isNot(tok::semi)) {
3297 // A semicolon was missing after this declaration. Diagnose and recover.
3298 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
3301 Tok.setKind(tok::semi);
3304 TUK = Sema::TUK_Reference;
3307 // If this is an elaborated type specifier, and we delayed
3308 // diagnostics before, just merge them into the current pool.
3309 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3310 diagsFromTag.redelay();
3313 MultiTemplateParamsArg TParams;
3314 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3315 TUK != Sema::TUK_Reference) {
3316 if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
3317 // Skip the rest of this declarator, up until the comma or semicolon.
3318 Diag(Tok, diag::err_enum_template);
3319 SkipUntil(tok::comma, true);
3323 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3324 // Enumerations can't be explicitly instantiated.
3325 DS.SetTypeSpecError();
3326 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3330 assert(TemplateInfo.TemplateParams && "no template parameters");
3331 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3332 TemplateInfo.TemplateParams->size());
3335 if (TUK == Sema::TUK_Reference)
3336 ProhibitAttributes(attrs);
3338 if (!Name && TUK != Sema::TUK_Definition) {
3339 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3341 // Skip the rest of this declarator, up until the comma or semicolon.
3342 SkipUntil(tok::comma, true);
3347 bool IsDependent = false;
3348 const char *PrevSpec = 0;
3350 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3351 StartLoc, SS, Name, NameLoc, attrs.getList(),
3352 AS, DS.getModulePrivateSpecLoc(), TParams,
3353 Owned, IsDependent, ScopedEnumKWLoc,
3354 IsScopedUsingClassTag, BaseType);
3357 // This enum has a dependent nested-name-specifier. Handle it as a
3360 DS.SetTypeSpecError();
3361 Diag(Tok, diag::err_expected_type_name_after_typename);
3365 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
3366 TUK, SS, Name, StartLoc,
3368 if (Type.isInvalid()) {
3369 DS.SetTypeSpecError();
3373 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3374 NameLoc.isValid() ? NameLoc : StartLoc,
3375 PrevSpec, DiagID, Type.get()))
3376 Diag(StartLoc, DiagID) << PrevSpec;
3382 // The action failed to produce an enumeration tag. If this is a
3383 // definition, consume the entire definition.
3384 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3386 SkipUntil(tok::r_brace);
3389 DS.SetTypeSpecError();
3393 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3394 ParseEnumBody(StartLoc, TagDecl);
3396 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3397 NameLoc.isValid() ? NameLoc : StartLoc,
3398 PrevSpec, DiagID, TagDecl, Owned))
3399 Diag(StartLoc, DiagID) << PrevSpec;
3402 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3403 /// enumerator-list:
3405 /// enumerator-list ',' enumerator
3407 /// enumeration-constant
3408 /// enumeration-constant '=' constant-expression
3409 /// enumeration-constant:
3412 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3413 // Enter the scope of the enum body and start the definition.
3414 ParseScope EnumScope(this, Scope::DeclScope);
3415 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3417 BalancedDelimiterTracker T(*this, tok::l_brace);
3420 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3421 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3422 Diag(Tok, diag::error_empty_enum);
3424 SmallVector<Decl *, 32> EnumConstantDecls;
3426 Decl *LastEnumConstDecl = 0;
3428 // Parse the enumerator-list.
3429 while (Tok.is(tok::identifier)) {
3430 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3431 SourceLocation IdentLoc = ConsumeToken();
3433 // If attributes exist after the enumerator, parse them.
3434 ParsedAttributesWithRange attrs(AttrFactory);
3435 MaybeParseGNUAttributes(attrs);
3436 MaybeParseCXX0XAttributes(attrs);
3437 ProhibitAttributes(attrs);
3439 SourceLocation EqualLoc;
3440 ExprResult AssignedVal;
3441 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3443 if (Tok.is(tok::equal)) {
3444 EqualLoc = ConsumeToken();
3445 AssignedVal = ParseConstantExpression();
3446 if (AssignedVal.isInvalid())
3447 SkipUntil(tok::comma, tok::r_brace, true, true);
3450 // Install the enumerator constant into EnumDecl.
3451 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3454 attrs.getList(), EqualLoc,
3455 AssignedVal.release());
3456 PD.complete(EnumConstDecl);
3458 EnumConstantDecls.push_back(EnumConstDecl);
3459 LastEnumConstDecl = EnumConstDecl;
3461 if (Tok.is(tok::identifier)) {
3462 // We're missing a comma between enumerators.
3463 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3464 Diag(Loc, diag::err_enumerator_list_missing_comma)
3465 << FixItHint::CreateInsertion(Loc, ", ");
3469 if (Tok.isNot(tok::comma))
3471 SourceLocation CommaLoc = ConsumeToken();
3473 if (Tok.isNot(tok::identifier)) {
3474 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
3475 Diag(CommaLoc, getLangOpts().CPlusPlus ?
3476 diag::ext_enumerator_list_comma_cxx :
3477 diag::ext_enumerator_list_comma_c)
3478 << FixItHint::CreateRemoval(CommaLoc);
3479 else if (getLangOpts().CPlusPlus0x)
3480 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3481 << FixItHint::CreateRemoval(CommaLoc);
3488 // If attributes exist after the identifier list, parse them.
3489 ParsedAttributes attrs(AttrFactory);
3490 MaybeParseGNUAttributes(attrs);
3492 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3493 EnumDecl, EnumConstantDecls.data(),
3494 EnumConstantDecls.size(), getCurScope(),
3498 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3499 T.getCloseLocation());
3501 // The next token must be valid after an enum definition. If not, a ';'
3502 // was probably forgotten.
3503 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3504 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3505 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
3506 // Push this token back into the preprocessor and change our current token
3507 // to ';' so that the rest of the code recovers as though there were an
3508 // ';' after the definition.
3510 Tok.setKind(tok::semi);
3514 /// isTypeSpecifierQualifier - Return true if the current token could be the
3515 /// start of a type-qualifier-list.
3516 bool Parser::isTypeQualifier() const {
3517 switch (Tok.getKind()) {
3518 default: return false;
3520 // type-qualifier only in OpenCL
3521 case tok::kw_private:
3522 return getLangOpts().OpenCL;
3526 case tok::kw_volatile:
3527 case tok::kw_restrict:
3528 case tok::kw___private:
3529 case tok::kw___local:
3530 case tok::kw___global:
3531 case tok::kw___constant:
3532 case tok::kw___read_only:
3533 case tok::kw___read_write:
3534 case tok::kw___write_only:
3539 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3540 /// is definitely a type-specifier. Return false if it isn't part of a type
3541 /// specifier or if we're not sure.
3542 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3543 switch (Tok.getKind()) {
3544 default: return false;
3548 case tok::kw___int64:
3549 case tok::kw___int128:
3550 case tok::kw_signed:
3551 case tok::kw_unsigned:
3552 case tok::kw__Complex:
3553 case tok::kw__Imaginary:
3556 case tok::kw_wchar_t:
3557 case tok::kw_char16_t:
3558 case tok::kw_char32_t:
3562 case tok::kw_double:
3565 case tok::kw__Decimal32:
3566 case tok::kw__Decimal64:
3567 case tok::kw__Decimal128:
3568 case tok::kw___vector:
3570 // struct-or-union-specifier (C99) or class-specifier (C++)
3572 case tok::kw_struct:
3573 case tok::kw___interface:
3579 case tok::annot_typename:
3584 /// isTypeSpecifierQualifier - Return true if the current token could be the
3585 /// start of a specifier-qualifier-list.
3586 bool Parser::isTypeSpecifierQualifier() {
3587 switch (Tok.getKind()) {
3588 default: return false;
3590 case tok::identifier: // foo::bar
3591 if (TryAltiVecVectorToken())
3594 case tok::kw_typename: // typename T::type
3595 // Annotate typenames and C++ scope specifiers. If we get one, just
3596 // recurse to handle whatever we get.
3597 if (TryAnnotateTypeOrScopeToken())
3599 if (Tok.is(tok::identifier))
3601 return isTypeSpecifierQualifier();
3603 case tok::coloncolon: // ::foo::bar
3604 if (NextToken().is(tok::kw_new) || // ::new
3605 NextToken().is(tok::kw_delete)) // ::delete
3608 if (TryAnnotateTypeOrScopeToken())
3610 return isTypeSpecifierQualifier();
3612 // GNU attributes support.
3613 case tok::kw___attribute:
3614 // GNU typeof support.
3615 case tok::kw_typeof:
3620 case tok::kw___int64:
3621 case tok::kw___int128:
3622 case tok::kw_signed:
3623 case tok::kw_unsigned:
3624 case tok::kw__Complex:
3625 case tok::kw__Imaginary:
3628 case tok::kw_wchar_t:
3629 case tok::kw_char16_t:
3630 case tok::kw_char32_t:
3634 case tok::kw_double:
3637 case tok::kw__Decimal32:
3638 case tok::kw__Decimal64:
3639 case tok::kw__Decimal128:
3640 case tok::kw___vector:
3642 // struct-or-union-specifier (C99) or class-specifier (C++)
3644 case tok::kw_struct:
3645 case tok::kw___interface:
3652 case tok::kw_volatile:
3653 case tok::kw_restrict:
3656 case tok::annot_typename:
3659 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3661 return getLangOpts().ObjC1;
3663 case tok::kw___cdecl:
3664 case tok::kw___stdcall:
3665 case tok::kw___fastcall:
3666 case tok::kw___thiscall:
3668 case tok::kw___ptr64:
3669 case tok::kw___ptr32:
3670 case tok::kw___pascal:
3671 case tok::kw___unaligned:
3673 case tok::kw___private:
3674 case tok::kw___local:
3675 case tok::kw___global:
3676 case tok::kw___constant:
3677 case tok::kw___read_only:
3678 case tok::kw___read_write:
3679 case tok::kw___write_only:
3683 case tok::kw_private:
3684 return getLangOpts().OpenCL;
3687 case tok::kw__Atomic:
3692 /// isDeclarationSpecifier() - Return true if the current token is part of a
3693 /// declaration specifier.
3695 /// \param DisambiguatingWithExpression True to indicate that the purpose of
3696 /// this check is to disambiguate between an expression and a declaration.
3697 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
3698 switch (Tok.getKind()) {
3699 default: return false;
3701 case tok::kw_private:
3702 return getLangOpts().OpenCL;
3704 case tok::identifier: // foo::bar
3705 // Unfortunate hack to support "Class.factoryMethod" notation.
3706 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
3708 if (TryAltiVecVectorToken())
3711 case tok::kw_decltype: // decltype(T())::type
3712 case tok::kw_typename: // typename T::type
3713 // Annotate typenames and C++ scope specifiers. If we get one, just
3714 // recurse to handle whatever we get.
3715 if (TryAnnotateTypeOrScopeToken())
3717 if (Tok.is(tok::identifier))
3720 // If we're in Objective-C and we have an Objective-C class type followed
3721 // by an identifier and then either ':' or ']', in a place where an
3722 // expression is permitted, then this is probably a class message send
3723 // missing the initial '['. In this case, we won't consider this to be
3724 // the start of a declaration.
3725 if (DisambiguatingWithExpression &&
3726 isStartOfObjCClassMessageMissingOpenBracket())
3729 return isDeclarationSpecifier();
3731 case tok::coloncolon: // ::foo::bar
3732 if (NextToken().is(tok::kw_new) || // ::new
3733 NextToken().is(tok::kw_delete)) // ::delete
3736 // Annotate typenames and C++ scope specifiers. If we get one, just
3737 // recurse to handle whatever we get.
3738 if (TryAnnotateTypeOrScopeToken())
3740 return isDeclarationSpecifier();
3742 // storage-class-specifier
3743 case tok::kw_typedef:
3744 case tok::kw_extern:
3745 case tok::kw___private_extern__:
3746 case tok::kw_static:
3748 case tok::kw_register:
3749 case tok::kw___thread:
3752 case tok::kw___module_private__:
3757 case tok::kw___int64:
3758 case tok::kw___int128:
3759 case tok::kw_signed:
3760 case tok::kw_unsigned:
3761 case tok::kw__Complex:
3762 case tok::kw__Imaginary:
3765 case tok::kw_wchar_t:
3766 case tok::kw_char16_t:
3767 case tok::kw_char32_t:
3772 case tok::kw_double:
3775 case tok::kw__Decimal32:
3776 case tok::kw__Decimal64:
3777 case tok::kw__Decimal128:
3778 case tok::kw___vector:
3780 // struct-or-union-specifier (C99) or class-specifier (C++)
3782 case tok::kw_struct:
3784 case tok::kw___interface:
3790 case tok::kw_volatile:
3791 case tok::kw_restrict:
3793 // function-specifier
3794 case tok::kw_inline:
3795 case tok::kw_virtual:
3796 case tok::kw_explicit:
3799 case tok::kw_friend:
3801 // static_assert-declaration
3802 case tok::kw__Static_assert:
3804 // GNU typeof support.
3805 case tok::kw_typeof:
3808 case tok::kw___attribute:
3810 // C++11 decltype and constexpr.
3811 case tok::annot_decltype:
3812 case tok::kw_constexpr:
3815 case tok::kw__Atomic:
3818 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3820 return getLangOpts().ObjC1;
3823 case tok::annot_typename:
3824 return !DisambiguatingWithExpression ||
3825 !isStartOfObjCClassMessageMissingOpenBracket();
3827 case tok::kw___declspec:
3828 case tok::kw___cdecl:
3829 case tok::kw___stdcall:
3830 case tok::kw___fastcall:
3831 case tok::kw___thiscall:
3833 case tok::kw___ptr64:
3834 case tok::kw___ptr32:
3835 case tok::kw___forceinline:
3836 case tok::kw___pascal:
3837 case tok::kw___unaligned:
3839 case tok::kw___private:
3840 case tok::kw___local:
3841 case tok::kw___global:
3842 case tok::kw___constant:
3843 case tok::kw___read_only:
3844 case tok::kw___read_write:
3845 case tok::kw___write_only:
3851 bool Parser::isConstructorDeclarator() {
3852 TentativeParsingAction TPA(*this);
3854 // Parse the C++ scope specifier.
3856 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3857 /*EnteringContext=*/true)) {
3862 // Parse the constructor name.
3863 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3864 // We already know that we have a constructor name; just consume
3872 // Current class name must be followed by a left parenthesis.
3873 if (Tok.isNot(tok::l_paren)) {
3879 // A right parenthesis, or ellipsis followed by a right parenthesis signals
3880 // that we have a constructor.
3881 if (Tok.is(tok::r_paren) ||
3882 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
3887 // If we need to, enter the specified scope.
3888 DeclaratorScopeObj DeclScopeObj(*this, SS);
3889 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3890 DeclScopeObj.EnterDeclaratorScope();
3892 // Optionally skip Microsoft attributes.
3893 ParsedAttributes Attrs(AttrFactory);
3894 MaybeParseMicrosoftAttributes(Attrs);
3896 // Check whether the next token(s) are part of a declaration
3897 // specifier, in which case we have the start of a parameter and,
3898 // therefore, we know that this is a constructor.
3899 bool IsConstructor = false;
3900 if (isDeclarationSpecifier())
3901 IsConstructor = true;
3902 else if (Tok.is(tok::identifier) ||
3903 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
3904 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
3905 // This might be a parenthesized member name, but is more likely to
3906 // be a constructor declaration with an invalid argument type. Keep
3908 if (Tok.is(tok::annot_cxxscope))
3912 // If this is not a constructor, we must be parsing a declarator,
3913 // which must have one of the following syntactic forms (see the
3914 // grammar extract at the start of ParseDirectDeclarator):
3915 switch (Tok.getKind()) {
3920 // C(X [ [attribute]]);
3921 case tok::coloncolon:
3926 // Assume this isn't a constructor, rather than assuming it's a
3927 // constructor with an unnamed parameter of an ill-formed type.
3931 IsConstructor = true;
3937 return IsConstructor;
3940 /// ParseTypeQualifierListOpt
3941 /// type-qualifier-list: [C99 6.7.5]
3943 /// [vendor] attributes
3944 /// [ only if VendorAttributesAllowed=true ]
3945 /// type-qualifier-list type-qualifier
3946 /// [vendor] type-qualifier-list attributes
3947 /// [ only if VendorAttributesAllowed=true ]
3948 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
3949 /// [ only if CXX0XAttributesAllowed=true ]
3950 /// Note: vendor can be GNU, MS, etc.
3952 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3953 bool VendorAttributesAllowed,
3954 bool CXX11AttributesAllowed) {
3955 if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
3956 isCXX11AttributeSpecifier()) {
3957 ParsedAttributesWithRange attrs(AttrFactory);
3958 ParseCXX11Attributes(attrs);
3959 DS.takeAttributesFrom(attrs);
3962 SourceLocation EndLoc;
3965 bool isInvalid = false;
3966 const char *PrevSpec = 0;
3967 unsigned DiagID = 0;
3968 SourceLocation Loc = Tok.getLocation();
3970 switch (Tok.getKind()) {
3971 case tok::code_completion:
3972 Actions.CodeCompleteTypeQualifiers(DS);
3973 return cutOffParsing();
3976 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
3979 case tok::kw_volatile:
3980 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3983 case tok::kw_restrict:
3984 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3988 // OpenCL qualifiers:
3989 case tok::kw_private:
3990 if (!getLangOpts().OpenCL)
3991 goto DoneWithTypeQuals;
3992 case tok::kw___private:
3993 case tok::kw___global:
3994 case tok::kw___local:
3995 case tok::kw___constant:
3996 case tok::kw___read_only:
3997 case tok::kw___write_only:
3998 case tok::kw___read_write:
3999 ParseOpenCLQualifiers(DS);
4003 case tok::kw___ptr64:
4004 case tok::kw___ptr32:
4005 case tok::kw___cdecl:
4006 case tok::kw___stdcall:
4007 case tok::kw___fastcall:
4008 case tok::kw___thiscall:
4009 case tok::kw___unaligned:
4010 if (VendorAttributesAllowed) {
4011 ParseMicrosoftTypeAttributes(DS.getAttributes());
4014 goto DoneWithTypeQuals;
4015 case tok::kw___pascal:
4016 if (VendorAttributesAllowed) {
4017 ParseBorlandTypeAttributes(DS.getAttributes());
4020 goto DoneWithTypeQuals;
4021 case tok::kw___attribute:
4022 if (VendorAttributesAllowed) {
4023 ParseGNUAttributes(DS.getAttributes());
4024 continue; // do *not* consume the next token!
4026 // otherwise, FALL THROUGH!
4029 // If this is not a type-qualifier token, we're done reading type
4030 // qualifiers. First verify that DeclSpec's are consistent.
4031 DS.Finish(Diags, PP);
4032 if (EndLoc.isValid())
4033 DS.SetRangeEnd(EndLoc);
4037 // If the specifier combination wasn't legal, issue a diagnostic.
4039 assert(PrevSpec && "Method did not return previous specifier!");
4040 Diag(Tok, DiagID) << PrevSpec;
4042 EndLoc = ConsumeToken();
4047 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4049 void Parser::ParseDeclarator(Declarator &D) {
4050 /// This implements the 'declarator' production in the C grammar, then checks
4051 /// for well-formedness and issues diagnostics.
4052 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4055 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4056 if (Kind == tok::star || Kind == tok::caret)
4059 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4060 if (!Lang.CPlusPlus)
4063 return Kind == tok::amp || Kind == tok::ampamp;
4066 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4067 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4068 /// isn't parsed at all, making this function effectively parse the C++
4069 /// ptr-operator production.
4071 /// If the grammar of this construct is extended, matching changes must also be
4072 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4073 /// isConstructorDeclarator.
4075 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4076 /// [C] pointer[opt] direct-declarator
4077 /// [C++] direct-declarator
4078 /// [C++] ptr-operator declarator
4080 /// pointer: [C99 6.7.5]
4081 /// '*' type-qualifier-list[opt]
4082 /// '*' type-qualifier-list[opt] pointer
4085 /// '*' cv-qualifier-seq[opt]
4088 /// [GNU] '&' restrict[opt] attributes[opt]
4089 /// [GNU?] '&&' restrict[opt] attributes[opt]
4090 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4091 void Parser::ParseDeclaratorInternal(Declarator &D,
4092 DirectDeclParseFunction DirectDeclParser) {
4093 if (Diags.hasAllExtensionsSilenced())
4096 // C++ member pointers start with a '::' or a nested-name.
4097 // Member pointers get special handling, since there's no place for the
4098 // scope spec in the generic path below.
4099 if (getLangOpts().CPlusPlus &&
4100 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
4101 Tok.is(tok::annot_cxxscope))) {
4102 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4103 D.getContext() == Declarator::MemberContext;
4105 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4107 if (SS.isNotEmpty()) {
4108 if (Tok.isNot(tok::star)) {
4109 // The scope spec really belongs to the direct-declarator.
4110 D.getCXXScopeSpec() = SS;
4111 if (DirectDeclParser)
4112 (this->*DirectDeclParser)(D);
4116 SourceLocation Loc = ConsumeToken();
4118 DeclSpec DS(AttrFactory);
4119 ParseTypeQualifierListOpt(DS);
4120 D.ExtendWithDeclSpec(DS);
4122 // Recurse to parse whatever is left.
4123 ParseDeclaratorInternal(D, DirectDeclParser);
4125 // Sema will have to catch (syntactically invalid) pointers into global
4126 // scope. It has to catch pointers into namespace scope anyway.
4127 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4130 /* Don't replace range end. */SourceLocation());
4135 tok::TokenKind Kind = Tok.getKind();
4136 // Not a pointer, C++ reference, or block.
4137 if (!isPtrOperatorToken(Kind, getLangOpts())) {
4138 if (DirectDeclParser)
4139 (this->*DirectDeclParser)(D);
4143 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4144 // '&&' -> rvalue reference
4145 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4148 if (Kind == tok::star || Kind == tok::caret) {
4150 DeclSpec DS(AttrFactory);
4152 // FIXME: GNU attributes are not allowed here in a new-type-id.
4153 ParseTypeQualifierListOpt(DS);
4154 D.ExtendWithDeclSpec(DS);
4156 // Recursively parse the declarator.
4157 ParseDeclaratorInternal(D, DirectDeclParser);
4158 if (Kind == tok::star)
4159 // Remember that we parsed a pointer type, and remember the type-quals.
4160 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4161 DS.getConstSpecLoc(),
4162 DS.getVolatileSpecLoc(),
4163 DS.getRestrictSpecLoc()),
4167 // Remember that we parsed a Block type, and remember the type-quals.
4168 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4174 DeclSpec DS(AttrFactory);
4176 // Complain about rvalue references in C++03, but then go on and build
4178 if (Kind == tok::ampamp)
4179 Diag(Loc, getLangOpts().CPlusPlus0x ?
4180 diag::warn_cxx98_compat_rvalue_reference :
4181 diag::ext_rvalue_reference);
4183 // GNU-style and C++11 attributes are allowed here, as is restrict.
4184 ParseTypeQualifierListOpt(DS);
4185 D.ExtendWithDeclSpec(DS);
4187 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4188 // cv-qualifiers are introduced through the use of a typedef or of a
4189 // template type argument, in which case the cv-qualifiers are ignored.
4190 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4191 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4192 Diag(DS.getConstSpecLoc(),
4193 diag::err_invalid_reference_qualifier_application) << "const";
4194 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4195 Diag(DS.getVolatileSpecLoc(),
4196 diag::err_invalid_reference_qualifier_application) << "volatile";
4199 // Recursively parse the declarator.
4200 ParseDeclaratorInternal(D, DirectDeclParser);
4202 if (D.getNumTypeObjects() > 0) {
4203 // C++ [dcl.ref]p4: There shall be no references to references.
4204 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4205 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4206 if (const IdentifierInfo *II = D.getIdentifier())
4207 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4210 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4213 // Once we've complained about the reference-to-reference, we
4214 // can go ahead and build the (technically ill-formed)
4215 // declarator: reference collapsing will take care of it.
4219 // Remember that we parsed a reference type. It doesn't have type-quals.
4220 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4227 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
4228 SourceLocation EllipsisLoc) {
4229 if (EllipsisLoc.isValid()) {
4230 FixItHint Insertion;
4231 if (!D.getEllipsisLoc().isValid()) {
4232 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
4233 D.setEllipsisLoc(EllipsisLoc);
4235 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
4236 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
4240 /// ParseDirectDeclarator
4241 /// direct-declarator: [C99 6.7.5]
4242 /// [C99] identifier
4243 /// '(' declarator ')'
4244 /// [GNU] '(' attributes declarator ')'
4245 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4246 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4247 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4248 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4249 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4250 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4251 /// attribute-specifier-seq[opt]
4252 /// direct-declarator '(' parameter-type-list ')'
4253 /// direct-declarator '(' identifier-list[opt] ')'
4254 /// [GNU] direct-declarator '(' parameter-forward-declarations
4255 /// parameter-type-list[opt] ')'
4256 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
4257 /// cv-qualifier-seq[opt] exception-specification[opt]
4258 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4259 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4260 /// ref-qualifier[opt] exception-specification[opt]
4261 /// [C++] declarator-id
4262 /// [C++11] declarator-id attribute-specifier-seq[opt]
4264 /// declarator-id: [C++ 8]
4265 /// '...'[opt] id-expression
4266 /// '::'[opt] nested-name-specifier[opt] type-name
4268 /// id-expression: [C++ 5.1]
4272 /// unqualified-id: [C++ 5.1]
4274 /// operator-function-id
4275 /// conversion-function-id
4279 /// Note, any additional constructs added here may need corresponding changes
4280 /// in isConstructorDeclarator.
4281 void Parser::ParseDirectDeclarator(Declarator &D) {
4282 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4284 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4285 // ParseDeclaratorInternal might already have parsed the scope.
4286 if (D.getCXXScopeSpec().isEmpty()) {
4287 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4288 D.getContext() == Declarator::MemberContext;
4289 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4293 if (D.getCXXScopeSpec().isValid()) {
4294 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4295 // Change the declaration context for name lookup, until this function
4296 // is exited (and the declarator has been parsed).
4297 DeclScopeObj.EnterDeclaratorScope();
4300 // C++0x [dcl.fct]p14:
4301 // There is a syntactic ambiguity when an ellipsis occurs at the end
4302 // of a parameter-declaration-clause without a preceding comma. In
4303 // this case, the ellipsis is parsed as part of the
4304 // abstract-declarator if the type of the parameter names a template
4305 // parameter pack that has not been expanded; otherwise, it is parsed
4306 // as part of the parameter-declaration-clause.
4307 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4308 !((D.getContext() == Declarator::PrototypeContext ||
4309 D.getContext() == Declarator::BlockLiteralContext) &&
4310 NextToken().is(tok::r_paren) &&
4311 !Actions.containsUnexpandedParameterPacks(D))) {
4312 SourceLocation EllipsisLoc = ConsumeToken();
4313 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4314 // The ellipsis was put in the wrong place. Recover, and explain to
4315 // the user what they should have done.
4317 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4320 D.setEllipsisLoc(EllipsisLoc);
4322 // The ellipsis can't be followed by a parenthesized declarator. We
4323 // check for that in ParseParenDeclarator, after we have disambiguated
4324 // the l_paren token.
4327 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4328 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4329 // We found something that indicates the start of an unqualified-id.
4330 // Parse that unqualified-id.
4331 bool AllowConstructorName;
4332 if (D.getDeclSpec().hasTypeSpecifier())
4333 AllowConstructorName = false;
4334 else if (D.getCXXScopeSpec().isSet())
4335 AllowConstructorName =
4336 (D.getContext() == Declarator::FileContext ||
4337 (D.getContext() == Declarator::MemberContext &&
4338 D.getDeclSpec().isFriendSpecified()));
4340 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4342 SourceLocation TemplateKWLoc;
4343 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4344 /*EnteringContext=*/true,
4345 /*AllowDestructorName=*/true,
4346 AllowConstructorName,
4350 // Once we're past the identifier, if the scope was bad, mark the
4351 // whole declarator bad.
4352 D.getCXXScopeSpec().isInvalid()) {
4353 D.SetIdentifier(0, Tok.getLocation());
4354 D.setInvalidType(true);
4356 // Parsed the unqualified-id; update range information and move along.
4357 if (D.getSourceRange().getBegin().isInvalid())
4358 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4359 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4361 goto PastIdentifier;
4363 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4364 assert(!getLangOpts().CPlusPlus &&
4365 "There's a C++-specific check for tok::identifier above");
4366 assert(Tok.getIdentifierInfo() && "Not an identifier?");
4367 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4369 goto PastIdentifier;
4372 if (Tok.is(tok::l_paren)) {
4373 // direct-declarator: '(' declarator ')'
4374 // direct-declarator: '(' attributes declarator ')'
4375 // Example: 'char (*X)' or 'int (*XX)(void)'
4376 ParseParenDeclarator(D);
4378 // If the declarator was parenthesized, we entered the declarator
4379 // scope when parsing the parenthesized declarator, then exited
4380 // the scope already. Re-enter the scope, if we need to.
4381 if (D.getCXXScopeSpec().isSet()) {
4382 // If there was an error parsing parenthesized declarator, declarator
4383 // scope may have been entered before. Don't do it again.
4384 if (!D.isInvalidType() &&
4385 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4386 // Change the declaration context for name lookup, until this function
4387 // is exited (and the declarator has been parsed).
4388 DeclScopeObj.EnterDeclaratorScope();
4390 } else if (D.mayOmitIdentifier()) {
4391 // This could be something simple like "int" (in which case the declarator
4392 // portion is empty), if an abstract-declarator is allowed.
4393 D.SetIdentifier(0, Tok.getLocation());
4395 if (Tok.getKind() == tok::annot_pragma_parser_crash)
4397 if (D.getContext() == Declarator::MemberContext)
4398 Diag(Tok, diag::err_expected_member_name_or_semi)
4399 << D.getDeclSpec().getSourceRange();
4400 else if (getLangOpts().CPlusPlus)
4401 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4403 Diag(Tok, diag::err_expected_ident_lparen);
4404 D.SetIdentifier(0, Tok.getLocation());
4405 D.setInvalidType(true);
4409 assert(D.isPastIdentifier() &&
4410 "Haven't past the location of the identifier yet?");
4412 // Don't parse attributes unless we have parsed an unparenthesized name.
4413 if (D.hasName() && !D.getNumTypeObjects())
4414 MaybeParseCXX0XAttributes(D);
4417 if (Tok.is(tok::l_paren)) {
4418 // Enter function-declaration scope, limiting any declarators to the
4419 // function prototype scope, including parameter declarators.
4420 ParseScope PrototypeScope(this,
4421 Scope::FunctionPrototypeScope|Scope::DeclScope);
4422 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4423 // In such a case, check if we actually have a function declarator; if it
4424 // is not, the declarator has been fully parsed.
4425 bool IsAmbiguous = false;
4426 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4427 // The name of the declarator, if any, is tentatively declared within
4428 // a possible direct initializer.
4429 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4430 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4431 TentativelyDeclaredIdentifiers.pop_back();
4432 if (!IsFunctionDecl)
4435 ParsedAttributes attrs(AttrFactory);
4436 BalancedDelimiterTracker T(*this, tok::l_paren);
4438 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4439 PrototypeScope.Exit();
4440 } else if (Tok.is(tok::l_square)) {
4441 ParseBracketDeclarator(D);
4448 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4449 /// only called before the identifier, so these are most likely just grouping
4450 /// parens for precedence. If we find that these are actually function
4451 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4453 /// direct-declarator:
4454 /// '(' declarator ')'
4455 /// [GNU] '(' attributes declarator ')'
4456 /// direct-declarator '(' parameter-type-list ')'
4457 /// direct-declarator '(' identifier-list[opt] ')'
4458 /// [GNU] direct-declarator '(' parameter-forward-declarations
4459 /// parameter-type-list[opt] ')'
4461 void Parser::ParseParenDeclarator(Declarator &D) {
4462 BalancedDelimiterTracker T(*this, tok::l_paren);
4465 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4467 // Eat any attributes before we look at whether this is a grouping or function
4468 // declarator paren. If this is a grouping paren, the attribute applies to
4469 // the type being built up, for example:
4470 // int (__attribute__(()) *x)(long y)
4471 // If this ends up not being a grouping paren, the attribute applies to the
4472 // first argument, for example:
4473 // int (__attribute__(()) int x)
4474 // In either case, we need to eat any attributes to be able to determine what
4475 // sort of paren this is.
4477 ParsedAttributes attrs(AttrFactory);
4478 bool RequiresArg = false;
4479 if (Tok.is(tok::kw___attribute)) {
4480 ParseGNUAttributes(attrs);
4482 // We require that the argument list (if this is a non-grouping paren) be
4483 // present even if the attribute list was empty.
4486 // Eat any Microsoft extensions.
4487 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
4488 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
4489 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
4490 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
4491 ParseMicrosoftTypeAttributes(attrs);
4493 // Eat any Borland extensions.
4494 if (Tok.is(tok::kw___pascal))
4495 ParseBorlandTypeAttributes(attrs);
4497 // If we haven't past the identifier yet (or where the identifier would be
4498 // stored, if this is an abstract declarator), then this is probably just
4499 // grouping parens. However, if this could be an abstract-declarator, then
4500 // this could also be the start of function arguments (consider 'void()').
4503 if (!D.mayOmitIdentifier()) {
4504 // If this can't be an abstract-declarator, this *must* be a grouping
4505 // paren, because we haven't seen the identifier yet.
4507 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
4508 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4509 NextToken().is(tok::r_paren)) || // C++ int(...)
4510 isDeclarationSpecifier() || // 'int(int)' is a function.
4511 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
4512 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4513 // considered to be a type, not a K&R identifier-list.
4516 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4520 // If this is a grouping paren, handle:
4521 // direct-declarator: '(' declarator ')'
4522 // direct-declarator: '(' attributes declarator ')'
4524 SourceLocation EllipsisLoc = D.getEllipsisLoc();
4525 D.setEllipsisLoc(SourceLocation());
4527 bool hadGroupingParens = D.hasGroupingParens();
4528 D.setGroupingParens(true);
4529 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4532 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4533 T.getCloseLocation()),
4534 attrs, T.getCloseLocation());
4536 D.setGroupingParens(hadGroupingParens);
4538 // An ellipsis cannot be placed outside parentheses.
4539 if (EllipsisLoc.isValid())
4540 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4545 // Okay, if this wasn't a grouping paren, it must be the start of a function
4546 // argument list. Recognize that this declarator will never have an
4547 // identifier (and remember where it would have been), then call into
4548 // ParseFunctionDeclarator to handle of argument list.
4549 D.SetIdentifier(0, Tok.getLocation());
4551 // Enter function-declaration scope, limiting any declarators to the
4552 // function prototype scope, including parameter declarators.
4553 ParseScope PrototypeScope(this,
4554 Scope::FunctionPrototypeScope|Scope::DeclScope);
4555 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
4556 PrototypeScope.Exit();
4559 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
4560 /// declarator D up to a paren, which indicates that we are parsing function
4563 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
4564 /// immediately after the open paren - they should be considered to be the
4565 /// first argument of a parameter.
4567 /// If RequiresArg is true, then the first argument of the function is required
4568 /// to be present and required to not be an identifier list.
4570 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4571 /// (C++11) ref-qualifier[opt], exception-specification[opt],
4572 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4574 /// [C++11] exception-specification:
4575 /// dynamic-exception-specification
4576 /// noexcept-specification
4578 void Parser::ParseFunctionDeclarator(Declarator &D,
4579 ParsedAttributes &FirstArgAttrs,
4580 BalancedDelimiterTracker &Tracker,
4583 assert(getCurScope()->isFunctionPrototypeScope() &&
4584 "Should call from a Function scope");
4585 // lparen is already consumed!
4586 assert(D.isPastIdentifier() && "Should not call before identifier!");
4588 // This should be true when the function has typed arguments.
4589 // Otherwise, it is treated as a K&R-style function.
4590 bool HasProto = false;
4591 // Build up an array of information about the parsed arguments.
4592 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4593 // Remember where we see an ellipsis, if any.
4594 SourceLocation EllipsisLoc;
4596 DeclSpec DS(AttrFactory);
4597 bool RefQualifierIsLValueRef = true;
4598 SourceLocation RefQualifierLoc;
4599 SourceLocation ConstQualifierLoc;
4600 SourceLocation VolatileQualifierLoc;
4601 ExceptionSpecificationType ESpecType = EST_None;
4602 SourceRange ESpecRange;
4603 SmallVector<ParsedType, 2> DynamicExceptions;
4604 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4605 ExprResult NoexceptExpr;
4606 ParsedAttributes FnAttrs(AttrFactory);
4607 TypeResult TrailingReturnType;
4609 Actions.ActOnStartFunctionDeclarator();
4611 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
4612 EndLoc is the end location for the function declarator.
4613 They differ for trailing return types. */
4614 SourceLocation StartLoc, LocalEndLoc, EndLoc;
4615 SourceLocation LParenLoc, RParenLoc;
4616 LParenLoc = Tracker.getOpenLocation();
4617 StartLoc = LParenLoc;
4619 if (isFunctionDeclaratorIdentifierList()) {
4621 Diag(Tok, diag::err_argument_required_after_attribute);
4623 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
4625 Tracker.consumeClose();
4626 RParenLoc = Tracker.getCloseLocation();
4627 LocalEndLoc = RParenLoc;
4630 if (Tok.isNot(tok::r_paren))
4631 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
4632 else if (RequiresArg)
4633 Diag(Tok, diag::err_argument_required_after_attribute);
4635 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
4637 // If we have the closing ')', eat it.
4638 Tracker.consumeClose();
4639 RParenLoc = Tracker.getCloseLocation();
4640 LocalEndLoc = RParenLoc;
4643 if (getLangOpts().CPlusPlus) {
4644 // FIXME: Accept these components in any order, and produce fixits to
4645 // correct the order if the user gets it wrong. Ideally we should deal
4646 // with the virt-specifier-seq and pure-specifier in the same way.
4648 // Parse cv-qualifier-seq[opt].
4649 ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
4650 if (!DS.getSourceRange().getEnd().isInvalid()) {
4651 EndLoc = DS.getSourceRange().getEnd();
4652 ConstQualifierLoc = DS.getConstSpecLoc();
4653 VolatileQualifierLoc = DS.getVolatileSpecLoc();
4656 // Parse ref-qualifier[opt].
4657 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
4658 Diag(Tok, getLangOpts().CPlusPlus0x ?
4659 diag::warn_cxx98_compat_ref_qualifier :
4660 diag::ext_ref_qualifier);
4662 RefQualifierIsLValueRef = Tok.is(tok::amp);
4663 RefQualifierLoc = ConsumeToken();
4664 EndLoc = RefQualifierLoc;
4667 // C++11 [expr.prim.general]p3:
4668 // If a declaration declares a member function or member function
4669 // template of a class X, the expression this is a prvalue of type
4670 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4671 // and the end of the function-definition, member-declarator, or
4673 bool IsCXX11MemberFunction =
4674 getLangOpts().CPlusPlus0x &&
4675 (D.getContext() == Declarator::MemberContext ||
4676 (D.getContext() == Declarator::FileContext &&
4677 D.getCXXScopeSpec().isValid() &&
4678 Actions.CurContext->isRecord()));
4679 Sema::CXXThisScopeRAII ThisScope(Actions,
4680 dyn_cast<CXXRecordDecl>(Actions.CurContext),
4681 DS.getTypeQualifiers(),
4682 IsCXX11MemberFunction);
4684 // Parse exception-specification[opt].
4685 ESpecType = tryParseExceptionSpecification(ESpecRange,
4687 DynamicExceptionRanges,
4689 if (ESpecType != EST_None)
4690 EndLoc = ESpecRange.getEnd();
4692 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
4693 // after the exception-specification.
4694 MaybeParseCXX0XAttributes(FnAttrs);
4696 // Parse trailing-return-type[opt].
4697 LocalEndLoc = EndLoc;
4698 if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
4699 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
4700 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
4701 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4702 LocalEndLoc = Tok.getLocation();
4704 TrailingReturnType = ParseTrailingReturnType(Range);
4705 EndLoc = Range.getEnd();
4710 // Remember that we parsed a function type, and remember the attributes.
4711 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
4714 ParamInfo.data(), ParamInfo.size(),
4715 EllipsisLoc, RParenLoc,
4716 DS.getTypeQualifiers(),
4717 RefQualifierIsLValueRef,
4718 RefQualifierLoc, ConstQualifierLoc,
4719 VolatileQualifierLoc,
4720 /*MutableLoc=*/SourceLocation(),
4721 ESpecType, ESpecRange.getBegin(),
4722 DynamicExceptions.data(),
4723 DynamicExceptionRanges.data(),
4724 DynamicExceptions.size(),
4725 NoexceptExpr.isUsable() ?
4726 NoexceptExpr.get() : 0,
4727 StartLoc, LocalEndLoc, D,
4728 TrailingReturnType),
4731 Actions.ActOnEndFunctionDeclarator();
4734 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
4735 /// identifier list form for a K&R-style function: void foo(a,b,c)
4737 /// Note that identifier-lists are only allowed for normal declarators, not for
4738 /// abstract-declarators.
4739 bool Parser::isFunctionDeclaratorIdentifierList() {
4740 return !getLangOpts().CPlusPlus
4741 && Tok.is(tok::identifier)
4742 && !TryAltiVecVectorToken()
4743 // K&R identifier lists can't have typedefs as identifiers, per C99
4745 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
4746 // Identifier lists follow a really simple grammar: the identifiers can
4747 // be followed *only* by a ", identifier" or ")". However, K&R
4748 // identifier lists are really rare in the brave new modern world, and
4749 // it is very common for someone to typo a type in a non-K&R style
4750 // list. If we are presented with something like: "void foo(intptr x,
4751 // float y)", we don't want to start parsing the function declarator as
4752 // though it is a K&R style declarator just because intptr is an
4755 // To handle this, we check to see if the token after the first
4756 // identifier is a "," or ")". Only then do we parse it as an
4758 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
4761 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
4762 /// we found a K&R-style identifier list instead of a typed parameter list.
4764 /// After returning, ParamInfo will hold the parsed parameters.
4766 /// identifier-list: [C99 6.7.5]
4768 /// identifier-list ',' identifier
4770 void Parser::ParseFunctionDeclaratorIdentifierList(
4772 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
4773 // If there was no identifier specified for the declarator, either we are in
4774 // an abstract-declarator, or we are in a parameter declarator which was found
4775 // to be abstract. In abstract-declarators, identifier lists are not valid:
4777 if (!D.getIdentifier())
4778 Diag(Tok, diag::ext_ident_list_in_param);
4780 // Maintain an efficient lookup of params we have seen so far.
4781 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
4784 // If this isn't an identifier, report the error and skip until ')'.
4785 if (Tok.isNot(tok::identifier)) {
4786 Diag(Tok, diag::err_expected_ident);
4787 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
4788 // Forget we parsed anything.
4793 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
4795 // Reject 'typedef int y; int test(x, y)', but continue parsing.
4796 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4797 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4799 // Verify that the argument identifier has not already been mentioned.
4800 if (!ParamsSoFar.insert(ParmII)) {
4801 Diag(Tok, diag::err_param_redefinition) << ParmII;
4803 // Remember this identifier in ParamInfo.
4804 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4809 // Eat the identifier.
4812 // The list continues if we see a comma.
4813 if (Tok.isNot(tok::comma))
4819 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
4820 /// after the opening parenthesis. This function will not parse a K&R-style
4821 /// identifier list.
4823 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
4824 /// caller parsed those arguments immediately after the open paren - they should
4825 /// be considered to be part of the first parameter.
4827 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
4828 /// be the location of the ellipsis, if any was parsed.
4830 /// parameter-type-list: [C99 6.7.5]
4832 /// parameter-list ',' '...'
4833 /// [C++] parameter-list '...'
4835 /// parameter-list: [C99 6.7.5]
4836 /// parameter-declaration
4837 /// parameter-list ',' parameter-declaration
4839 /// parameter-declaration: [C99 6.7.5]
4840 /// declaration-specifiers declarator
4841 /// [C++] declaration-specifiers declarator '=' assignment-expression
4842 /// [C++11] initializer-clause
4843 /// [GNU] declaration-specifiers declarator attributes
4844 /// declaration-specifiers abstract-declarator[opt]
4845 /// [C++] declaration-specifiers abstract-declarator[opt]
4846 /// '=' assignment-expression
4847 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
4848 /// [C++11] attribute-specifier-seq parameter-declaration
4850 void Parser::ParseParameterDeclarationClause(
4852 ParsedAttributes &FirstArgAttrs,
4853 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
4854 SourceLocation &EllipsisLoc) {
4857 if (Tok.is(tok::ellipsis)) {
4858 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
4859 // before deciding this was a parameter-declaration-clause.
4860 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4864 // Parse the declaration-specifiers.
4865 // Just use the ParsingDeclaration "scope" of the declarator.
4866 DeclSpec DS(AttrFactory);
4868 // Parse any C++11 attributes.
4869 MaybeParseCXX0XAttributes(DS.getAttributes());
4871 // Skip any Microsoft attributes before a param.
4872 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
4873 ParseMicrosoftAttributes(DS.getAttributes());
4875 SourceLocation DSStart = Tok.getLocation();
4877 // If the caller parsed attributes for the first argument, add them now.
4878 // Take them so that we only apply the attributes to the first parameter.
4879 // FIXME: If we can leave the attributes in the token stream somehow, we can
4880 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
4882 DS.takeAttributesFrom(FirstArgAttrs);
4884 ParseDeclarationSpecifiers(DS);
4886 // Parse the declarator. This is "PrototypeContext", because we must
4887 // accept either 'declarator' or 'abstract-declarator' here.
4888 Declarator ParmDecl(DS, Declarator::PrototypeContext);
4889 ParseDeclarator(ParmDecl);
4891 // Parse GNU attributes, if present.
4892 MaybeParseGNUAttributes(ParmDecl);
4894 // Remember this parsed parameter in ParamInfo.
4895 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
4897 // DefArgToks is used when the parsing of default arguments needs
4899 CachedTokens *DefArgToks = 0;
4901 // If no parameter was specified, verify that *something* was specified,
4902 // otherwise we have a missing type and identifier.
4903 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
4904 ParmDecl.getNumTypeObjects() == 0) {
4905 // Completely missing, emit error.
4906 Diag(DSStart, diag::err_missing_param);
4908 // Otherwise, we have something. Add it and let semantic analysis try
4909 // to grok it and add the result to the ParamInfo we are building.
4911 // Inform the actions module about the parameter declarator, so it gets
4912 // added to the current scope.
4913 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
4915 // Parse the default argument, if any. We parse the default
4916 // arguments in all dialects; the semantic analysis in
4917 // ActOnParamDefaultArgument will reject the default argument in
4919 if (Tok.is(tok::equal)) {
4920 SourceLocation EqualLoc = Tok.getLocation();
4922 // Parse the default argument
4923 if (D.getContext() == Declarator::MemberContext) {
4924 // If we're inside a class definition, cache the tokens
4925 // corresponding to the default argument. We'll actually parse
4926 // them when we see the end of the class definition.
4927 // FIXME: Can we use a smart pointer for Toks?
4928 DefArgToks = new CachedTokens;
4930 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
4931 /*StopAtSemi=*/true,
4932 /*ConsumeFinalToken=*/false)) {
4935 Actions.ActOnParamDefaultArgumentError(Param);
4937 // Mark the end of the default argument so that we know when to
4938 // stop when we parse it later on.
4940 DefArgEnd.startToken();
4941 DefArgEnd.setKind(tok::cxx_defaultarg_end);
4942 DefArgEnd.setLocation(Tok.getLocation());
4943 DefArgToks->push_back(DefArgEnd);
4944 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
4945 (*DefArgToks)[1].getLocation());
4951 // The argument isn't actually potentially evaluated unless it is
4953 EnterExpressionEvaluationContext Eval(Actions,
4954 Sema::PotentiallyEvaluatedIfUsed,
4957 ExprResult DefArgResult;
4958 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
4959 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
4960 DefArgResult = ParseBraceInitializer();
4962 DefArgResult = ParseAssignmentExpression();
4963 if (DefArgResult.isInvalid()) {
4964 Actions.ActOnParamDefaultArgumentError(Param);
4965 SkipUntil(tok::comma, tok::r_paren, true, true);
4967 // Inform the actions module about the default argument
4968 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
4969 DefArgResult.take());
4974 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4975 ParmDecl.getIdentifierLoc(), Param,
4979 // If the next token is a comma, consume it and keep reading arguments.
4980 if (Tok.isNot(tok::comma)) {
4981 if (Tok.is(tok::ellipsis)) {
4982 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
4984 if (!getLangOpts().CPlusPlus) {
4985 // We have ellipsis without a preceding ',', which is ill-formed
4986 // in C. Complain and provide the fix.
4987 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
4988 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
4995 // Consume the comma.
5001 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5002 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5003 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5004 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5005 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5006 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5007 /// attribute-specifier-seq[opt]
5008 void Parser::ParseBracketDeclarator(Declarator &D) {
5009 if (CheckProhibitedCXX11Attribute())
5012 BalancedDelimiterTracker T(*this, tok::l_square);
5015 // C array syntax has many features, but by-far the most common is [] and [4].
5016 // This code does a fast path to handle some of the most obvious cases.
5017 if (Tok.getKind() == tok::r_square) {
5019 ParsedAttributes attrs(AttrFactory);
5020 MaybeParseCXX0XAttributes(attrs);
5022 // Remember that we parsed the empty array type.
5023 ExprResult NumElements;
5024 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
5025 T.getOpenLocation(),
5026 T.getCloseLocation()),
5027 attrs, T.getCloseLocation());
5029 } else if (Tok.getKind() == tok::numeric_constant &&
5030 GetLookAheadToken(1).is(tok::r_square)) {
5031 // [4] is very common. Parse the numeric constant expression.
5032 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5036 ParsedAttributes attrs(AttrFactory);
5037 MaybeParseCXX0XAttributes(attrs);
5039 // Remember that we parsed a array type, and remember its features.
5040 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
5042 T.getOpenLocation(),
5043 T.getCloseLocation()),
5044 attrs, T.getCloseLocation());
5048 // If valid, this location is the position where we read the 'static' keyword.
5049 SourceLocation StaticLoc;
5050 if (Tok.is(tok::kw_static))
5051 StaticLoc = ConsumeToken();
5053 // If there is a type-qualifier-list, read it now.
5054 // Type qualifiers in an array subscript are a C99 feature.
5055 DeclSpec DS(AttrFactory);
5056 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5058 // If we haven't already read 'static', check to see if there is one after the
5059 // type-qualifier-list.
5060 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
5061 StaticLoc = ConsumeToken();
5063 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5064 bool isStar = false;
5065 ExprResult NumElements;
5067 // Handle the case where we have '[*]' as the array size. However, a leading
5068 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5069 // the token after the star is a ']'. Since stars in arrays are
5070 // infrequent, use of lookahead is not costly here.
5071 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5072 ConsumeToken(); // Eat the '*'.
5074 if (StaticLoc.isValid()) {
5075 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5076 StaticLoc = SourceLocation(); // Drop the static.
5079 } else if (Tok.isNot(tok::r_square)) {
5080 // Note, in C89, this production uses the constant-expr production instead
5081 // of assignment-expr. The only difference is that assignment-expr allows
5082 // things like '=' and '*='. Sema rejects these in C89 mode because they
5083 // are not i-c-e's, so we don't need to distinguish between the two here.
5085 // Parse the constant-expression or assignment-expression now (depending
5087 if (getLangOpts().CPlusPlus) {
5088 NumElements = ParseConstantExpression();
5090 EnterExpressionEvaluationContext Unevaluated(Actions,
5091 Sema::ConstantEvaluated);
5092 NumElements = ParseAssignmentExpression();
5096 // If there was an error parsing the assignment-expression, recover.
5097 if (NumElements.isInvalid()) {
5098 D.setInvalidType(true);
5099 // If the expression was invalid, skip it.
5100 SkipUntil(tok::r_square);
5106 ParsedAttributes attrs(AttrFactory);
5107 MaybeParseCXX0XAttributes(attrs);
5109 // Remember that we parsed a array type, and remember its features.
5110 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5111 StaticLoc.isValid(), isStar,
5112 NumElements.release(),
5113 T.getOpenLocation(),
5114 T.getCloseLocation()),
5115 attrs, T.getCloseLocation());
5118 /// [GNU] typeof-specifier:
5119 /// typeof ( expressions )
5120 /// typeof ( type-name )
5121 /// [GNU/C++] typeof unary-expression
5123 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5124 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5126 SourceLocation StartLoc = ConsumeToken();
5128 const bool hasParens = Tok.is(tok::l_paren);
5130 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5131 Sema::ReuseLambdaContextDecl);
5135 SourceRange CastRange;
5136 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5139 DS.setTypeofParensRange(CastRange);
5141 if (CastRange.getEnd().isInvalid())
5142 // FIXME: Not accurate, the range gets one token more than it should.
5143 DS.SetRangeEnd(Tok.getLocation());
5145 DS.SetRangeEnd(CastRange.getEnd());
5149 DS.SetTypeSpecError();
5153 const char *PrevSpec = 0;
5155 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5156 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5158 Diag(StartLoc, DiagID) << PrevSpec;
5162 // If we get here, the operand to the typeof was an expresion.
5163 if (Operand.isInvalid()) {
5164 DS.SetTypeSpecError();
5168 // We might need to transform the operand if it is potentially evaluated.
5169 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5170 if (Operand.isInvalid()) {
5171 DS.SetTypeSpecError();
5175 const char *PrevSpec = 0;
5177 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5178 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5179 DiagID, Operand.get()))
5180 Diag(StartLoc, DiagID) << PrevSpec;
5183 /// [C11] atomic-specifier:
5184 /// _Atomic ( type-name )
5186 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5187 assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
5189 SourceLocation StartLoc = ConsumeToken();
5190 BalancedDelimiterTracker T(*this, tok::l_paren);
5191 if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
5192 SkipUntil(tok::r_paren);
5196 TypeResult Result = ParseTypeName();
5197 if (Result.isInvalid()) {
5198 SkipUntil(tok::r_paren);
5205 if (T.getCloseLocation().isInvalid())
5208 DS.setTypeofParensRange(T.getRange());
5209 DS.SetRangeEnd(T.getCloseLocation());
5211 const char *PrevSpec = 0;
5213 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5214 DiagID, Result.release()))
5215 Diag(StartLoc, DiagID) << PrevSpec;
5219 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5220 /// from TryAltiVecVectorToken.
5221 bool Parser::TryAltiVecVectorTokenOutOfLine() {
5222 Token Next = NextToken();
5223 switch (Next.getKind()) {
5224 default: return false;
5227 case tok::kw_signed:
5228 case tok::kw_unsigned:
5233 case tok::kw_double:
5235 case tok::kw___pixel:
5236 Tok.setKind(tok::kw___vector);
5238 case tok::identifier:
5239 if (Next.getIdentifierInfo() == Ident_pixel) {
5240 Tok.setKind(tok::kw___vector);
5247 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5248 const char *&PrevSpec, unsigned &DiagID,
5250 if (Tok.getIdentifierInfo() == Ident_vector) {
5251 Token Next = NextToken();
5252 switch (Next.getKind()) {
5255 case tok::kw_signed:
5256 case tok::kw_unsigned:
5261 case tok::kw_double:
5263 case tok::kw___pixel:
5264 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5266 case tok::identifier:
5267 if (Next.getIdentifierInfo() == Ident_pixel) {
5268 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5275 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5276 DS.isTypeAltiVecVector()) {
5277 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);