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 "RAIIObjectsForParser.h"
16 #include "clang/Basic/AddressSpaces.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Basic/OpenCL.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/PrettyDeclStackTrace.h"
23 #include "clang/Sema/Scope.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringSwitch.h"
27 using namespace clang;
29 //===----------------------------------------------------------------------===//
30 // C99 6.7: Declarations.
31 //===----------------------------------------------------------------------===//
34 /// type-name: [C99 6.7.6]
35 /// specifier-qualifier-list abstract-declarator[opt]
37 /// Called type-id in C++.
38 TypeResult Parser::ParseTypeName(SourceRange *Range,
39 Declarator::TheContext Context,
42 ParsedAttributes *Attrs) {
43 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
44 if (DSC == DSC_normal)
45 DSC = DSC_type_specifier;
47 // Parse the common declaration-specifiers piece.
48 DeclSpec DS(AttrFactory);
50 DS.addAttributes(Attrs->getList());
51 ParseSpecifierQualifierList(DS, AS, DSC);
53 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
55 // Parse the abstract-declarator, if present.
56 Declarator DeclaratorInfo(DS, Context);
57 ParseDeclarator(DeclaratorInfo);
59 *Range = DeclaratorInfo.getSourceRange();
61 if (DeclaratorInfo.isInvalidType())
64 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
68 /// isAttributeLateParsed - Return true if the attribute has arguments that
69 /// require late parsing.
70 static bool isAttributeLateParsed(const IdentifierInfo &II) {
71 return llvm::StringSwitch<bool>(II.getName())
72 #include "clang/Parse/AttrLateParsed.inc"
76 /// ParseGNUAttributes - Parse a non-empty attributes list.
80 /// attributes attribute
83 /// '__attribute__' '(' '(' attribute-list ')' ')'
85 /// [GNU] attribute-list:
87 /// attribute_list ',' attrib
92 /// attrib-name '(' identifier ')'
93 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
94 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
96 /// [GNU] attrib-name:
102 /// FIXME: The GCC grammar/code for this construct implies we need two
103 /// token lookahead. Comment from gcc: "If they start with an identifier
104 /// which is followed by a comma or close parenthesis, then the arguments
105 /// start with that identifier; otherwise they are an expression list."
107 /// GCC does not require the ',' between attribs in an attribute-list.
109 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
110 /// any attributes that don't work (based on my limited testing). Most
111 /// attributes are very simple in practice. Until we find a bug, I don't see
112 /// a pressing need to implement the 2 token lookahead.
114 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
115 SourceLocation *endLoc,
116 LateParsedAttrList *LateAttrs) {
117 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
119 while (Tok.is(tok::kw___attribute)) {
121 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
123 SkipUntil(tok::r_paren, true); // skip until ) or ;
126 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
127 SkipUntil(tok::r_paren, true); // skip until ) or ;
130 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
131 while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
132 Tok.is(tok::comma)) {
133 if (Tok.is(tok::comma)) {
134 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
138 // we have an identifier or declaration specifier (const, int, etc.)
139 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
140 SourceLocation AttrNameLoc = ConsumeToken();
142 if (Tok.is(tok::l_paren)) {
143 // handle "parameterized" attributes
144 if (LateAttrs && isAttributeLateParsed(*AttrName)) {
145 LateParsedAttribute *LA =
146 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
147 LateAttrs->push_back(LA);
149 // Attributes in a class are parsed at the end of the class, along
150 // with other late-parsed declarations.
151 if (!ClassStack.empty() && !LateAttrs->parseSoon())
152 getCurrentClass().LateParsedDeclarations.push_back(LA);
154 // consume everything up to and including the matching right parens
155 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
159 Eof.setLocation(Tok.getLocation());
160 LA->Toks.push_back(Eof);
162 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc,
163 0, SourceLocation(), AttributeList::AS_GNU);
166 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
167 0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
170 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
171 SkipUntil(tok::r_paren, false);
172 SourceLocation Loc = Tok.getLocation();
173 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
174 SkipUntil(tok::r_paren, false);
181 /// \brief Determine whether the given attribute has all expression arguments.
182 static bool attributeHasExprArgs(const IdentifierInfo &II) {
183 return llvm::StringSwitch<bool>(II.getName())
184 #include "clang/Parse/AttrExprArgs.inc"
188 /// Parse the arguments to a parameterized GNU attribute or
189 /// a C++11 attribute in "gnu" namespace.
190 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
191 SourceLocation AttrNameLoc,
192 ParsedAttributes &Attrs,
193 SourceLocation *EndLoc,
194 IdentifierInfo *ScopeName,
195 SourceLocation ScopeLoc,
196 AttributeList::Syntax Syntax) {
198 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
200 // Availability attributes have their own grammar.
201 if (AttrName->isStr("availability")) {
202 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
205 // Thread safety attributes fit into the FIXME case above, so we
206 // just parse the arguments as a list of expressions
207 if (IsThreadSafetyAttribute(AttrName->getName())) {
208 ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
211 // Type safety attributes have their own grammar.
212 if (AttrName->isStr("type_tag_for_datatype")) {
213 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
217 ConsumeParen(); // ignore the left paren loc for now
219 IdentifierInfo *ParmName = 0;
220 SourceLocation ParmLoc;
221 bool BuiltinType = false;
224 SourceRange TypeRange;
225 bool TypeParsed = false;
227 switch (Tok.getKind()) {
229 case tok::kw_wchar_t:
230 case tok::kw_char16_t:
231 case tok::kw_char32_t:
236 case tok::kw___int64:
237 case tok::kw___int128:
239 case tok::kw_unsigned:
244 // __attribute__(( vec_type_hint(char) ))
246 T = ParseTypeName(&TypeRange);
250 case tok::identifier:
251 if (AttrName->isStr("vec_type_hint")) {
252 T = ParseTypeName(&TypeRange);
256 // If the attribute has all expression arguments, and not a "parameter",
257 // break out to handle it below.
258 if (attributeHasExprArgs(*AttrName))
260 ParmName = Tok.getIdentifierInfo();
261 ParmLoc = ConsumeToken();
269 bool isInvalid = false;
270 bool isParmType = false;
272 if (!BuiltinType && !AttrName->isStr("vec_type_hint") &&
273 (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
275 if (ParmLoc.isValid())
278 // Parse the non-empty comma-separated list of expressions.
280 ExprResult ArgExpr(ParseAssignmentExpression());
281 if (ArgExpr.isInvalid()) {
282 SkipUntil(tok::r_paren);
285 ArgExprs.push_back(ArgExpr.release());
286 if (Tok.isNot(tok::comma))
288 ConsumeToken(); // Eat the comma, move to the next argument
291 else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
292 if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
294 while (Tok.is(tok::identifier)) {
296 if (Tok.is(tok::greater))
298 if (Tok.is(tok::comma)) {
303 if (Tok.isNot(tok::greater))
304 Diag(Tok, diag::err_iboutletcollection_with_protocol);
305 SkipUntil(tok::r_paren, false, true); // skip until ')'
307 } else if (AttrName->isStr("vec_type_hint")) {
308 if (T.get() && !T.isInvalid())
311 if (Tok.is(tok::identifier))
318 SourceLocation RParen = Tok.getLocation();
319 if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen) &&
321 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
323 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrLoc, RParen), ScopeName,
324 ScopeLoc, ParmName, ParmLoc, T.get(), Syntax);
326 AttributeList *attr = Attrs.addNew(
327 AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, ParmName,
328 ParmLoc, ArgExprs.data(), ArgExprs.size(), Syntax);
330 attr->getKind() == AttributeList::AT_IBOutletCollection)
331 Diag(Tok, diag::err_iboutletcollection_builtintype);
336 /// \brief Parses a single argument for a declspec, including the
337 /// surrounding parens.
338 void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
339 SourceLocation AttrNameLoc,
340 ParsedAttributes &Attrs)
342 BalancedDelimiterTracker T(*this, tok::l_paren);
343 if (T.expectAndConsume(diag::err_expected_lparen_after,
344 AttrName->getNameStart(), tok::r_paren))
347 ExprResult ArgExpr(ParseConstantExpression());
348 if (ArgExpr.isInvalid()) {
352 Expr *ExprList = ArgExpr.take();
353 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
354 &ExprList, 1, AttributeList::AS_Declspec);
359 /// \brief Determines whether a declspec is a "simple" one requiring no
361 bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
362 return llvm::StringSwitch<bool>(Ident->getName())
363 .Case("dllimport", true)
364 .Case("dllexport", true)
365 .Case("noreturn", true)
366 .Case("nothrow", true)
367 .Case("noinline", true)
369 .Case("appdomain", true)
370 .Case("process", true)
371 .Case("jitintrinsic", true)
372 .Case("noalias", true)
373 .Case("restrict", true)
374 .Case("novtable", true)
375 .Case("selectany", true)
376 .Case("thread", true)
377 .Case("safebuffers", true )
381 /// \brief Attempts to parse a declspec which is not simple (one that takes
382 /// parameters). Will return false if we properly handled the declspec, or
383 /// true if it is an unknown declspec.
384 void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
386 ParsedAttributes &Attrs) {
387 // Try to handle the easy case first -- these declspecs all take a single
388 // parameter as their argument.
389 if (llvm::StringSwitch<bool>(Ident->getName())
392 .Case("allocate", true)
394 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
395 } else if (Ident->getName() == "deprecated") {
396 // The deprecated declspec has an optional single argument, so we will
397 // check for a l-paren to decide whether we should parse an argument or
399 if (Tok.getKind() == tok::l_paren)
400 ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
402 Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
403 AttributeList::AS_Declspec);
404 } else if (Ident->getName() == "property") {
405 // The property declspec is more complex in that it can take one or two
406 // assignment expressions as a parameter, but the lhs of the assignment
407 // must be named get or put.
408 if (Tok.isNot(tok::l_paren)) {
409 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
410 << Ident->getNameStart();
413 BalancedDelimiterTracker T(*this, tok::l_paren);
414 T.expectAndConsume(diag::err_expected_lparen_after,
415 Ident->getNameStart(), tok::r_paren);
419 AK_Put = 0, AK_Get = 1 // indices into AccessorNames
421 IdentifierInfo *AccessorNames[] = { 0, 0 };
422 bool HasInvalidAccessor = false;
424 // Parse the accessor specifications.
426 // Stop if this doesn't look like an accessor spec.
427 if (!Tok.is(tok::identifier)) {
428 // If the user wrote a completely empty list, use a special diagnostic.
429 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
430 AccessorNames[AK_Put] == 0 && AccessorNames[AK_Get] == 0) {
431 Diag(Loc, diag::err_ms_property_no_getter_or_putter);
435 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
440 SourceLocation KindLoc = Tok.getLocation();
441 StringRef KindStr = Tok.getIdentifierInfo()->getName();
442 if (KindStr == "get") {
444 } else if (KindStr == "put") {
447 // Recover from the common mistake of using 'set' instead of 'put'.
448 } else if (KindStr == "set") {
449 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
450 << FixItHint::CreateReplacement(KindLoc, "put");
453 // Handle the mistake of forgetting the accessor kind by skipping
455 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
456 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
458 HasInvalidAccessor = true;
459 goto next_property_accessor;
461 // Otherwise, complain about the unknown accessor kind.
463 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
464 HasInvalidAccessor = true;
467 // Try to keep parsing unless it doesn't look like an accessor spec.
468 if (!NextToken().is(tok::equal)) break;
471 // Consume the identifier.
475 if (Tok.is(tok::equal)) {
478 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
483 // Expect the method name.
484 if (!Tok.is(tok::identifier)) {
485 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
489 if (Kind == AK_Invalid) {
490 // Just drop invalid accessors.
491 } else if (AccessorNames[Kind] != NULL) {
492 // Complain about the repeated accessor, ignore it, and keep parsing.
493 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
495 AccessorNames[Kind] = Tok.getIdentifierInfo();
499 next_property_accessor:
500 // Keep processing accessors until we run out.
501 if (Tok.is(tok::comma)) {
505 // If we run into the ')', stop without consuming it.
506 } else if (Tok.is(tok::r_paren)) {
509 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
514 // Only add the property attribute if it was well-formed.
515 if (!HasInvalidAccessor) {
516 Attrs.addNewPropertyAttr(Ident, Loc, 0, SourceLocation(), 0,
518 AccessorNames[AK_Get], AccessorNames[AK_Put],
519 AttributeList::AS_Declspec);
523 // We don't recognize this as a valid declspec, but instead of creating the
524 // attribute and allowing sema to warn about it, we will warn here instead.
525 // This is because some attributes have multiple spellings, but we need to
526 // disallow that for declspecs (such as align vs aligned). If we made the
527 // attribute, we'd have to split the valid declspec spelling logic into
529 Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
531 // If there's an open paren, we should eat the open and close parens under
532 // the assumption that this unknown declspec has parameters.
533 BalancedDelimiterTracker T(*this, tok::l_paren);
534 if (!T.consumeOpen())
539 /// [MS] decl-specifier:
540 /// __declspec ( extended-decl-modifier-seq )
542 /// [MS] extended-decl-modifier-seq:
543 /// extended-decl-modifier[opt]
544 /// extended-decl-modifier extended-decl-modifier-seq
545 void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
546 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
549 BalancedDelimiterTracker T(*this, tok::l_paren);
550 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
554 // An empty declspec is perfectly legal and should not warn. Additionally,
555 // you can specify multiple attributes per declspec.
556 while (Tok.getKind() != tok::r_paren) {
557 // We expect either a well-known identifier or a generic string. Anything
558 // else is a malformed declspec.
559 bool IsString = Tok.getKind() == tok::string_literal ? true : false;
560 if (!IsString && Tok.getKind() != tok::identifier &&
561 Tok.getKind() != tok::kw_restrict) {
562 Diag(Tok, diag::err_ms_declspec_type);
567 IdentifierInfo *AttrName;
568 SourceLocation AttrNameLoc;
570 SmallString<8> StrBuffer;
571 bool Invalid = false;
572 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
577 AttrName = PP.getIdentifierInfo(Str);
578 AttrNameLoc = ConsumeStringToken();
580 AttrName = Tok.getIdentifierInfo();
581 AttrNameLoc = ConsumeToken();
584 if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
585 // If we have a generic string, we will allow it because there is no
586 // documented list of allowable string declspecs, but we know they exist
587 // (for instance, SAL declspecs in older versions of MSVC).
589 // Alternatively, if the identifier is a simple one, then it requires no
590 // arguments and can be turned into an attribute directly.
591 Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
592 0, 0, AttributeList::AS_Declspec);
594 ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
599 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
600 // Treat these like attributes
601 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
602 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
603 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
604 Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
605 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
606 SourceLocation AttrNameLoc = ConsumeToken();
607 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
608 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
612 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
613 // Treat these like attributes
614 while (Tok.is(tok::kw___pascal)) {
615 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
616 SourceLocation AttrNameLoc = ConsumeToken();
617 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
618 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
622 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
623 // Treat these like attributes
624 while (Tok.is(tok::kw___kernel)) {
625 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
626 SourceLocation AttrNameLoc = ConsumeToken();
627 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
628 SourceLocation(), 0, 0, AttributeList::AS_Keyword);
632 void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
633 // FIXME: The mapping from attribute spelling to semantics should be
634 // performed in Sema, not here.
635 SourceLocation Loc = Tok.getLocation();
636 switch(Tok.getKind()) {
637 // OpenCL qualifiers:
638 case tok::kw___private:
639 case tok::kw_private:
640 DS.getAttributes().addNewInteger(
641 Actions.getASTContext(),
642 PP.getIdentifierInfo("address_space"), Loc, 0);
645 case tok::kw___global:
646 DS.getAttributes().addNewInteger(
647 Actions.getASTContext(),
648 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
651 case tok::kw___local:
652 DS.getAttributes().addNewInteger(
653 Actions.getASTContext(),
654 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
657 case tok::kw___constant:
658 DS.getAttributes().addNewInteger(
659 Actions.getASTContext(),
660 PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
663 case tok::kw___read_only:
664 DS.getAttributes().addNewInteger(
665 Actions.getASTContext(),
666 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
669 case tok::kw___write_only:
670 DS.getAttributes().addNewInteger(
671 Actions.getASTContext(),
672 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
675 case tok::kw___read_write:
676 DS.getAttributes().addNewInteger(
677 Actions.getASTContext(),
678 PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
684 /// \brief Parse a version number.
688 /// simple-integer ',' simple-integer
689 /// simple-integer ',' simple-integer ',' simple-integer
690 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
691 Range = Tok.getLocation();
693 if (!Tok.is(tok::numeric_constant)) {
694 Diag(Tok, diag::err_expected_version);
695 SkipUntil(tok::comma, tok::r_paren, true, true, true);
696 return VersionTuple();
699 // Parse the major (and possibly minor and subminor) versions, which
700 // are stored in the numeric constant. We utilize a quirk of the
701 // lexer, which is that it handles something like 1.2.3 as a single
702 // numeric constant, rather than two separate tokens.
703 SmallString<512> Buffer;
704 Buffer.resize(Tok.getLength()+1);
705 const char *ThisTokBegin = &Buffer[0];
707 // Get the spelling of the token, which eliminates trigraphs, etc.
708 bool Invalid = false;
709 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
711 return VersionTuple();
713 // Parse the major version.
714 unsigned AfterMajor = 0;
716 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
717 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
721 if (AfterMajor == 0) {
722 Diag(Tok, diag::err_expected_version);
723 SkipUntil(tok::comma, tok::r_paren, true, true, true);
724 return VersionTuple();
727 if (AfterMajor == ActualLength) {
730 // We only had a single version component.
732 Diag(Tok, diag::err_zero_version);
733 return VersionTuple();
736 return VersionTuple(Major);
739 if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
740 Diag(Tok, diag::err_expected_version);
741 SkipUntil(tok::comma, tok::r_paren, true, true, true);
742 return VersionTuple();
745 // Parse the minor version.
746 unsigned AfterMinor = AfterMajor + 1;
748 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
749 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
753 if (AfterMinor == ActualLength) {
756 // We had major.minor.
757 if (Major == 0 && Minor == 0) {
758 Diag(Tok, diag::err_zero_version);
759 return VersionTuple();
762 return VersionTuple(Major, Minor);
765 // If what follows is not a '.', we have a problem.
766 if (ThisTokBegin[AfterMinor] != '.') {
767 Diag(Tok, diag::err_expected_version);
768 SkipUntil(tok::comma, tok::r_paren, true, true, true);
769 return VersionTuple();
772 // Parse the subminor version.
773 unsigned AfterSubminor = AfterMinor + 1;
774 unsigned Subminor = 0;
775 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
776 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
780 if (AfterSubminor != ActualLength) {
781 Diag(Tok, diag::err_expected_version);
782 SkipUntil(tok::comma, tok::r_paren, true, true, true);
783 return VersionTuple();
786 return VersionTuple(Major, Minor, Subminor);
789 /// \brief Parse the contents of the "availability" attribute.
791 /// availability-attribute:
792 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
797 /// version-arg-list:
799 /// version-arg ',' version-arg-list
802 /// 'introduced' '=' version
803 /// 'deprecated' '=' version
804 /// 'obsoleted' = version
807 /// 'message' '=' <string>
808 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
809 SourceLocation AvailabilityLoc,
810 ParsedAttributes &attrs,
811 SourceLocation *endLoc) {
812 SourceLocation PlatformLoc;
813 IdentifierInfo *Platform = 0;
815 enum { Introduced, Deprecated, Obsoleted, Unknown };
816 AvailabilityChange Changes[Unknown];
817 ExprResult MessageExpr;
820 BalancedDelimiterTracker T(*this, tok::l_paren);
821 if (T.consumeOpen()) {
822 Diag(Tok, diag::err_expected_lparen);
826 // Parse the platform name,
827 if (Tok.isNot(tok::identifier)) {
828 Diag(Tok, diag::err_availability_expected_platform);
829 SkipUntil(tok::r_paren);
832 Platform = Tok.getIdentifierInfo();
833 PlatformLoc = ConsumeToken();
835 // Parse the ',' following the platform name.
836 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
839 // If we haven't grabbed the pointers for the identifiers
840 // "introduced", "deprecated", and "obsoleted", do so now.
841 if (!Ident_introduced) {
842 Ident_introduced = PP.getIdentifierInfo("introduced");
843 Ident_deprecated = PP.getIdentifierInfo("deprecated");
844 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
845 Ident_unavailable = PP.getIdentifierInfo("unavailable");
846 Ident_message = PP.getIdentifierInfo("message");
849 // Parse the set of introductions/deprecations/removals.
850 SourceLocation UnavailableLoc;
852 if (Tok.isNot(tok::identifier)) {
853 Diag(Tok, diag::err_availability_expected_change);
854 SkipUntil(tok::r_paren);
857 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
858 SourceLocation KeywordLoc = ConsumeToken();
860 if (Keyword == Ident_unavailable) {
861 if (UnavailableLoc.isValid()) {
862 Diag(KeywordLoc, diag::err_availability_redundant)
863 << Keyword << SourceRange(UnavailableLoc);
865 UnavailableLoc = KeywordLoc;
867 if (Tok.isNot(tok::comma))
874 if (Tok.isNot(tok::equal)) {
875 Diag(Tok, diag::err_expected_equal_after)
877 SkipUntil(tok::r_paren);
881 if (Keyword == Ident_message) {
882 if (!isTokenStringLiteral()) {
883 Diag(Tok, diag::err_expected_string_literal)
884 << /*Source='availability attribute'*/2;
885 SkipUntil(tok::r_paren);
888 MessageExpr = ParseStringLiteralExpression();
892 SourceRange VersionRange;
893 VersionTuple Version = ParseVersionTuple(VersionRange);
895 if (Version.empty()) {
896 SkipUntil(tok::r_paren);
901 if (Keyword == Ident_introduced)
903 else if (Keyword == Ident_deprecated)
905 else if (Keyword == Ident_obsoleted)
910 if (Index < Unknown) {
911 if (!Changes[Index].KeywordLoc.isInvalid()) {
912 Diag(KeywordLoc, diag::err_availability_redundant)
914 << SourceRange(Changes[Index].KeywordLoc,
915 Changes[Index].VersionRange.getEnd());
918 Changes[Index].KeywordLoc = KeywordLoc;
919 Changes[Index].Version = Version;
920 Changes[Index].VersionRange = VersionRange;
922 Diag(KeywordLoc, diag::err_availability_unknown_change)
923 << Keyword << VersionRange;
926 if (Tok.isNot(tok::comma))
933 if (T.consumeClose())
937 *endLoc = T.getCloseLocation();
939 // The 'unavailable' availability cannot be combined with any other
940 // availability changes. Make sure that hasn't happened.
941 if (UnavailableLoc.isValid()) {
942 bool Complained = false;
943 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
944 if (Changes[Index].KeywordLoc.isValid()) {
946 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
947 << SourceRange(Changes[Index].KeywordLoc,
948 Changes[Index].VersionRange.getEnd());
952 // Clear out the availability.
953 Changes[Index] = AvailabilityChange();
958 // Record this attribute
959 attrs.addNew(&Availability,
960 SourceRange(AvailabilityLoc, T.getCloseLocation()),
962 Platform, PlatformLoc,
966 UnavailableLoc, MessageExpr.take(),
967 AttributeList::AS_GNU);
971 // Late Parsed Attributes:
972 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
974 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
976 void Parser::LateParsedClass::ParseLexedAttributes() {
977 Self->ParseLexedAttributes(*Class);
980 void Parser::LateParsedAttribute::ParseLexedAttributes() {
981 Self->ParseLexedAttribute(*this, true, false);
984 /// Wrapper class which calls ParseLexedAttribute, after setting up the
985 /// scope appropriately.
986 void Parser::ParseLexedAttributes(ParsingClass &Class) {
987 // Deal with templates
988 // FIXME: Test cases to make sure this does the right thing for templates.
989 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
990 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
992 if (HasTemplateScope)
993 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
995 // Set or update the scope flags.
996 bool AlreadyHasClassScope = Class.TopLevelClass;
997 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
998 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
999 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1001 // Enter the scope of nested classes
1002 if (!AlreadyHasClassScope)
1003 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1004 Class.TagOrTemplate);
1005 if (!Class.LateParsedDeclarations.empty()) {
1006 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1007 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1011 if (!AlreadyHasClassScope)
1012 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1013 Class.TagOrTemplate);
1017 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1018 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1019 bool EnterScope, bool OnDefinition) {
1020 assert(LAs.parseSoon() &&
1021 "Attribute list should be marked for immediate parsing.");
1022 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1025 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1032 /// \brief Finish parsing an attribute for which parsing was delayed.
1033 /// This will be called at the end of parsing a class declaration
1034 /// for each LateParsedAttribute. We consume the saved tokens and
1035 /// create an attribute with the arguments filled in. We add this
1036 /// to the Attribute list for the decl.
1037 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1038 bool EnterScope, bool OnDefinition) {
1039 // Save the current token position.
1040 SourceLocation OrigLoc = Tok.getLocation();
1042 // Append the current token at the end of the new token stream so that it
1043 // doesn't get lost.
1044 LA.Toks.push_back(Tok);
1045 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1046 // Consume the previously pushed token.
1047 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1049 if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
1050 // FIXME: Do not warn on C++11 attributes, once we start supporting
1052 Diag(Tok, diag::warn_attribute_on_function_definition)
1053 << LA.AttrName.getName();
1056 ParsedAttributes Attrs(AttrFactory);
1057 SourceLocation endLoc;
1059 if (LA.Decls.size() > 0) {
1060 Decl *D = LA.Decls[0];
1061 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1062 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1064 // Allow 'this' within late-parsed attributes.
1065 Sema::CXXThisScopeRAII ThisScope(Actions, RD,
1067 ND && RD && ND->isCXXInstanceMember());
1069 if (LA.Decls.size() == 1) {
1070 // If the Decl is templatized, add template parameters to scope.
1071 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1072 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1073 if (HasTemplateScope)
1074 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1076 // If the Decl is on a function, add function parameters to the scope.
1077 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1078 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1080 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1082 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1083 0, SourceLocation(), AttributeList::AS_GNU);
1086 Actions.ActOnExitFunctionContext();
1087 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1089 if (HasTemplateScope) {
1093 // If there are multiple decls, then the decl cannot be within the
1095 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1096 0, SourceLocation(), AttributeList::AS_GNU);
1099 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1102 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
1103 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1106 if (Tok.getLocation() != OrigLoc) {
1107 // Due to a parsing error, we either went over the cached tokens or
1108 // there are still cached tokens left, so we skip the leftover tokens.
1109 // Since this is an uncommon situation that should be avoided, use the
1110 // expensive isBeforeInTranslationUnit call.
1111 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
1113 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
1118 /// \brief Wrapper around a case statement checking if AttrName is
1119 /// one of the thread safety attributes
1120 bool Parser::IsThreadSafetyAttribute(StringRef AttrName) {
1121 return llvm::StringSwitch<bool>(AttrName)
1122 .Case("guarded_by", true)
1123 .Case("guarded_var", true)
1124 .Case("pt_guarded_by", true)
1125 .Case("pt_guarded_var", true)
1126 .Case("lockable", true)
1127 .Case("scoped_lockable", true)
1128 .Case("no_thread_safety_analysis", true)
1129 .Case("acquired_after", true)
1130 .Case("acquired_before", true)
1131 .Case("exclusive_lock_function", true)
1132 .Case("shared_lock_function", true)
1133 .Case("exclusive_trylock_function", true)
1134 .Case("shared_trylock_function", true)
1135 .Case("unlock_function", true)
1136 .Case("lock_returned", true)
1137 .Case("locks_excluded", true)
1138 .Case("exclusive_locks_required", true)
1139 .Case("shared_locks_required", true)
1143 /// \brief Parse the contents of thread safety attributes. These
1144 /// should always be parsed as an expression list.
1146 /// We need to special case the parsing due to the fact that if the first token
1147 /// of the first argument is an identifier, the main parse loop will store
1148 /// that token as a "parameter" and the rest of
1149 /// the arguments will be added to a list of "arguments". However,
1150 /// subsequent tokens in the first argument are lost. We instead parse each
1151 /// argument as an expression and add all arguments to the list of "arguments".
1152 /// In future, we will take advantage of this special case to also
1153 /// deal with some argument scoping issues here (for example, referring to a
1154 /// function parameter in the attribute on that function).
1155 void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
1156 SourceLocation AttrNameLoc,
1157 ParsedAttributes &Attrs,
1158 SourceLocation *EndLoc) {
1159 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1161 BalancedDelimiterTracker T(*this, tok::l_paren);
1164 ExprVector ArgExprs;
1165 bool ArgExprsOk = true;
1167 // now parse the list of expressions
1168 while (Tok.isNot(tok::r_paren)) {
1169 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1170 ExprResult ArgExpr(ParseAssignmentExpression());
1171 if (ArgExpr.isInvalid()) {
1176 ArgExprs.push_back(ArgExpr.release());
1178 if (Tok.isNot(tok::comma))
1180 ConsumeToken(); // Eat the comma, move to the next argument
1183 if (ArgExprsOk && !T.consumeClose()) {
1184 Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
1185 ArgExprs.data(), ArgExprs.size(), AttributeList::AS_GNU);
1188 *EndLoc = T.getCloseLocation();
1191 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1192 SourceLocation AttrNameLoc,
1193 ParsedAttributes &Attrs,
1194 SourceLocation *EndLoc) {
1195 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1197 BalancedDelimiterTracker T(*this, tok::l_paren);
1200 if (Tok.isNot(tok::identifier)) {
1201 Diag(Tok, diag::err_expected_ident);
1205 IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
1206 SourceLocation ArgumentKindLoc = ConsumeToken();
1208 if (Tok.isNot(tok::comma)) {
1209 Diag(Tok, diag::err_expected_comma);
1215 SourceRange MatchingCTypeRange;
1216 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1217 if (MatchingCType.isInvalid()) {
1222 bool LayoutCompatible = false;
1223 bool MustBeNull = false;
1224 while (Tok.is(tok::comma)) {
1226 if (Tok.isNot(tok::identifier)) {
1227 Diag(Tok, diag::err_expected_ident);
1231 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1232 if (Flag->isStr("layout_compatible"))
1233 LayoutCompatible = true;
1234 else if (Flag->isStr("must_be_null"))
1237 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1241 ConsumeToken(); // consume flag
1244 if (!T.consumeClose()) {
1245 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
1246 ArgumentKind, ArgumentKindLoc,
1247 MatchingCType.release(), LayoutCompatible,
1248 MustBeNull, AttributeList::AS_GNU);
1252 *EndLoc = T.getCloseLocation();
1255 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1256 /// of a C++11 attribute-specifier in a location where an attribute is not
1257 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1260 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1261 /// this doesn't appear to actually be an attribute-specifier, and the caller
1262 /// should try to parse it.
1263 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1264 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1266 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1267 case CAK_NotAttributeSpecifier:
1268 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1271 case CAK_InvalidAttributeSpecifier:
1272 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1275 case CAK_AttributeSpecifier:
1276 // Parse and discard the attributes.
1277 SourceLocation BeginLoc = ConsumeBracket();
1279 SkipUntil(tok::r_square, /*StopAtSemi*/ false);
1280 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1281 SourceLocation EndLoc = ConsumeBracket();
1282 Diag(BeginLoc, diag::err_attributes_not_allowed)
1283 << SourceRange(BeginLoc, EndLoc);
1286 llvm_unreachable("All cases handled above.");
1289 /// \brief We have found the opening square brackets of a C++11
1290 /// attribute-specifier in a location where an attribute is not permitted, but
1291 /// we know where the attributes ought to be written. Parse them anyway, and
1292 /// provide a fixit moving them to the right place.
1293 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1294 SourceLocation CorrectLocation) {
1295 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1296 Tok.is(tok::kw_alignas));
1298 // Consume the attributes.
1299 SourceLocation Loc = Tok.getLocation();
1300 ParseCXX11Attributes(Attrs);
1301 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1303 Diag(Loc, diag::err_attributes_not_allowed)
1304 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1305 << FixItHint::CreateRemoval(AttrRange);
1308 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1309 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1313 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1314 AttributeList *AttrList = attrs.getList();
1316 if (AttrList->isCXX11Attribute()) {
1317 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1318 << AttrList->getName();
1319 AttrList->setInvalid();
1321 AttrList = AttrList->getNext();
1325 /// ParseDeclaration - Parse a full 'declaration', which consists of
1326 /// declaration-specifiers, some number of declarators, and a semicolon.
1327 /// 'Context' should be a Declarator::TheContext value. This returns the
1328 /// location of the semicolon in DeclEnd.
1330 /// declaration: [C99 6.7]
1331 /// block-declaration ->
1332 /// simple-declaration
1334 /// [C++] template-declaration
1335 /// [C++] namespace-definition
1336 /// [C++] using-directive
1337 /// [C++] using-declaration
1338 /// [C++11/C11] static_assert-declaration
1339 /// others... [FIXME]
1341 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
1343 SourceLocation &DeclEnd,
1344 ParsedAttributesWithRange &attrs) {
1345 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1346 // Must temporarily exit the objective-c container scope for
1347 // parsing c none objective-c decls.
1348 ObjCDeclContextSwitch ObjCDC(*this);
1350 Decl *SingleDecl = 0;
1351 Decl *OwnedType = 0;
1352 switch (Tok.getKind()) {
1353 case tok::kw_template:
1354 case tok::kw_export:
1355 ProhibitAttributes(attrs);
1356 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1358 case tok::kw_inline:
1359 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1360 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1361 ProhibitAttributes(attrs);
1362 SourceLocation InlineLoc = ConsumeToken();
1363 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1366 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
1368 case tok::kw_namespace:
1369 ProhibitAttributes(attrs);
1370 SingleDecl = ParseNamespace(Context, DeclEnd);
1373 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1374 DeclEnd, attrs, &OwnedType);
1376 case tok::kw_static_assert:
1377 case tok::kw__Static_assert:
1378 ProhibitAttributes(attrs);
1379 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1382 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
1385 // This routine returns a DeclGroup, if the thing we parsed only contains a
1386 // single decl, convert it now. Alias declarations can also declare a type;
1387 // include that too if it is present.
1388 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1391 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1392 /// declaration-specifiers init-declarator-list[opt] ';'
1393 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1394 /// init-declarator-list ';'
1395 ///[C90/C++]init-declarator-list ';' [TODO]
1396 /// [OMP] threadprivate-directive [TODO]
1398 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1399 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1401 /// If RequireSemi is false, this does not check for a ';' at the end of the
1402 /// declaration. If it is true, it checks for and eats it.
1404 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1405 /// of a simple-declaration. If we find that we are, we also parse the
1406 /// for-range-initializer, and place it here.
1407 Parser::DeclGroupPtrTy
1408 Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
1409 SourceLocation &DeclEnd,
1410 ParsedAttributesWithRange &Attrs,
1411 bool RequireSemi, ForRangeInit *FRI) {
1412 // Parse the common declaration-specifiers piece.
1413 ParsingDeclSpec DS(*this);
1415 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
1416 getDeclSpecContextFromDeclaratorContext(Context));
1418 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1419 // declaration-specifiers init-declarator-list[opt] ';'
1420 if (Tok.is(tok::semi)) {
1421 ProhibitAttributes(Attrs);
1422 DeclEnd = Tok.getLocation();
1423 if (RequireSemi) ConsumeToken();
1424 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1426 DS.complete(TheDecl);
1427 return Actions.ConvertDeclToDeclGroup(TheDecl);
1430 DS.takeAttributesFrom(Attrs);
1431 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
1434 /// Returns true if this might be the start of a declarator, or a common typo
1435 /// for a declarator.
1436 bool Parser::MightBeDeclarator(unsigned Context) {
1437 switch (Tok.getKind()) {
1438 case tok::annot_cxxscope:
1439 case tok::annot_template_id:
1441 case tok::code_completion:
1442 case tok::coloncolon:
1444 case tok::kw___attribute:
1445 case tok::kw_operator:
1452 return getLangOpts().CPlusPlus;
1454 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1455 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1456 NextToken().is(tok::l_square);
1458 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1459 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1461 case tok::identifier:
1462 switch (NextToken().getKind()) {
1463 case tok::code_completion:
1464 case tok::coloncolon:
1467 case tok::equalequal: // Might be a typo for '='.
1468 case tok::kw_alignas:
1470 case tok::kw___attribute:
1482 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1483 // and in block scope it's probably a label. Inside a class definition,
1484 // this is a bit-field.
1485 return Context == Declarator::MemberContext ||
1486 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1488 case tok::identifier: // Possible virt-specifier.
1489 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1500 /// Skip until we reach something which seems like a sensible place to pick
1501 /// up parsing after a malformed declaration. This will sometimes stop sooner
1502 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1503 void Parser::SkipMalformedDecl() {
1505 switch (Tok.getKind()) {
1507 // Skip until matching }, then stop. We've probably skipped over
1508 // a malformed class or function definition or similar.
1510 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1511 if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
1512 // This declaration isn't over yet. Keep skipping.
1515 if (Tok.is(tok::semi))
1521 SkipUntil(tok::r_square, /*StopAtSemi*/false);
1526 SkipUntil(tok::r_paren, /*StopAtSemi*/false);
1536 case tok::kw_inline:
1537 // 'inline namespace' at the start of a line is almost certainly
1538 // a good place to pick back up parsing, except in an Objective-C
1539 // @interface context.
1540 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1541 (!ParsingInObjCContainer || CurParsedObjCImpl))
1545 case tok::kw_namespace:
1546 // 'namespace' at the start of a line is almost certainly a good
1547 // place to pick back up parsing, except in an Objective-C
1548 // @interface context.
1549 if (Tok.isAtStartOfLine() &&
1550 (!ParsingInObjCContainer || CurParsedObjCImpl))
1555 // @end is very much like } in Objective-C contexts.
1556 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1557 ParsingInObjCContainer)
1563 // - and + probably start new method declarations in Objective-C contexts.
1564 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1579 /// ParseDeclGroup - Having concluded that this is either a function
1580 /// definition or a group of object declarations, actually parse the
1582 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1584 bool AllowFunctionDefinitions,
1585 SourceLocation *DeclEnd,
1586 ForRangeInit *FRI) {
1587 // Parse the first declarator.
1588 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1591 // Bail out if the first declarator didn't seem well-formed.
1592 if (!D.hasName() && !D.mayOmitIdentifier()) {
1593 SkipMalformedDecl();
1594 return DeclGroupPtrTy();
1597 // Save late-parsed attributes for now; they need to be parsed in the
1598 // appropriate function scope after the function Decl has been constructed.
1599 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1600 LateParsedAttrList LateParsedAttrs(true);
1601 if (D.isFunctionDeclarator())
1602 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1604 // Check to see if we have a function *definition* which must have a body.
1605 if (D.isFunctionDeclarator() &&
1606 // Look at the next token to make sure that this isn't a function
1607 // declaration. We have to check this because __attribute__ might be the
1608 // start of a function definition in GCC-extended K&R C.
1609 !isDeclarationAfterDeclarator()) {
1611 if (AllowFunctionDefinitions) {
1612 if (isStartOfFunctionDefinition(D)) {
1613 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1614 Diag(Tok, diag::err_function_declared_typedef);
1616 // Recover by treating the 'typedef' as spurious.
1617 DS.ClearStorageClassSpecs();
1621 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1622 return Actions.ConvertDeclToDeclGroup(TheDecl);
1625 if (isDeclarationSpecifier()) {
1626 // If there is an invalid declaration specifier right after the function
1627 // prototype, then we must be in a missing semicolon case where this isn't
1628 // actually a body. Just fall through into the code that handles it as a
1629 // prototype, and let the top-level code handle the erroneous declspec
1630 // where it would otherwise expect a comma or semicolon.
1632 Diag(Tok, diag::err_expected_fn_body);
1633 SkipUntil(tok::semi);
1634 return DeclGroupPtrTy();
1637 if (Tok.is(tok::l_brace)) {
1638 Diag(Tok, diag::err_function_definition_not_allowed);
1639 SkipUntil(tok::r_brace, true, true);
1644 if (ParseAsmAttributesAfterDeclarator(D))
1645 return DeclGroupPtrTy();
1647 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1648 // must parse and analyze the for-range-initializer before the declaration is
1651 // Handle the Objective-C for-in loop variable similarly, although we
1652 // don't need to parse the container in advance.
1653 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1654 bool IsForRangeLoop = false;
1655 if (Tok.is(tok::colon)) {
1656 IsForRangeLoop = true;
1657 FRI->ColonLoc = ConsumeToken();
1658 if (Tok.is(tok::l_brace))
1659 FRI->RangeExpr = ParseBraceInitializer();
1661 FRI->RangeExpr = ParseExpression();
1664 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1666 Actions.ActOnCXXForRangeDecl(ThisDecl);
1667 Actions.FinalizeDeclaration(ThisDecl);
1668 D.complete(ThisDecl);
1669 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
1672 SmallVector<Decl *, 8> DeclsInGroup;
1673 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
1674 if (LateParsedAttrs.size() > 0)
1675 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1676 D.complete(FirstDecl);
1678 DeclsInGroup.push_back(FirstDecl);
1680 bool ExpectSemi = Context != Declarator::ForContext;
1682 // If we don't have a comma, it is either the end of the list (a ';') or an
1684 while (Tok.is(tok::comma)) {
1685 SourceLocation CommaLoc = ConsumeToken();
1687 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1688 // This comma was followed by a line-break and something which can't be
1689 // the start of a declarator. The comma was probably a typo for a
1691 Diag(CommaLoc, diag::err_expected_semi_declaration)
1692 << FixItHint::CreateReplacement(CommaLoc, ";");
1697 // Parse the next declarator.
1699 D.setCommaLoc(CommaLoc);
1701 // Accept attributes in an init-declarator. In the first declarator in a
1702 // declaration, these would be part of the declspec. In subsequent
1703 // declarators, they become part of the declarator itself, so that they
1704 // don't apply to declarators after *this* one. Examples:
1705 // short __attribute__((common)) var; -> declspec
1706 // short var __attribute__((common)); -> declarator
1707 // short x, __attribute__((common)) var; -> declarator
1708 MaybeParseGNUAttributes(D);
1711 if (!D.isInvalidType()) {
1712 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1713 D.complete(ThisDecl);
1715 DeclsInGroup.push_back(ThisDecl);
1720 *DeclEnd = Tok.getLocation();
1723 ExpectAndConsumeSemi(Context == Declarator::FileContext
1724 ? diag::err_invalid_token_after_toplevel_declarator
1725 : diag::err_expected_semi_declaration)) {
1726 // Okay, there was no semicolon and one was expected. If we see a
1727 // declaration specifier, just assume it was missing and continue parsing.
1728 // Otherwise things are very confused and we skip to recover.
1729 if (!isDeclarationSpecifier()) {
1730 SkipUntil(tok::r_brace, true, true);
1731 if (Tok.is(tok::semi))
1736 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
1737 DeclsInGroup.data(),
1738 DeclsInGroup.size());
1741 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1742 /// declarator. Returns true on an error.
1743 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1744 // If a simple-asm-expr is present, parse it.
1745 if (Tok.is(tok::kw_asm)) {
1747 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1748 if (AsmLabel.isInvalid()) {
1749 SkipUntil(tok::semi, true, true);
1753 D.setAsmLabel(AsmLabel.release());
1757 MaybeParseGNUAttributes(D);
1761 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1762 /// declarator'. This method parses the remainder of the declaration
1763 /// (including any attributes or initializer, among other things) and
1764 /// finalizes the declaration.
1766 /// init-declarator: [C99 6.7]
1768 /// declarator '=' initializer
1769 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1770 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1771 /// [C++] declarator initializer[opt]
1773 /// [C++] initializer:
1774 /// [C++] '=' initializer-clause
1775 /// [C++] '(' expression-list ')'
1776 /// [C++0x] '=' 'default' [TODO]
1777 /// [C++0x] '=' 'delete'
1778 /// [C++0x] braced-init-list
1780 /// According to the standard grammar, =default and =delete are function
1781 /// definitions, but that definitely doesn't fit with the parser here.
1783 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
1784 const ParsedTemplateInfo &TemplateInfo) {
1785 if (ParseAsmAttributesAfterDeclarator(D))
1788 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1791 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
1792 const ParsedTemplateInfo &TemplateInfo) {
1793 // Inform the current actions module that we just parsed this declarator.
1795 switch (TemplateInfo.Kind) {
1796 case ParsedTemplateInfo::NonTemplate:
1797 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1800 case ParsedTemplateInfo::Template:
1801 case ParsedTemplateInfo::ExplicitSpecialization:
1802 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1803 *TemplateInfo.TemplateParams,
1807 case ParsedTemplateInfo::ExplicitInstantiation: {
1809 = Actions.ActOnExplicitInstantiation(getCurScope(),
1810 TemplateInfo.ExternLoc,
1811 TemplateInfo.TemplateLoc,
1813 if (ThisRes.isInvalid()) {
1814 SkipUntil(tok::semi, true, true);
1818 ThisDecl = ThisRes.get();
1823 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1825 // Parse declarator '=' initializer.
1826 // If a '==' or '+=' is found, suggest a fixit to '='.
1827 if (isTokenEqualOrEqualTypo()) {
1829 if (Tok.is(tok::kw_delete)) {
1830 if (D.isFunctionDeclarator())
1831 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1834 Diag(ConsumeToken(), diag::err_deleted_non_function);
1835 } else if (Tok.is(tok::kw_default)) {
1836 if (D.isFunctionDeclarator())
1837 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
1840 Diag(ConsumeToken(), diag::err_default_special_members);
1842 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1844 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1847 if (Tok.is(tok::code_completion)) {
1848 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
1849 Actions.FinalizeDeclaration(ThisDecl);
1854 ExprResult Init(ParseInitializer());
1856 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1857 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1861 if (Init.isInvalid()) {
1862 SkipUntil(tok::comma, true, true);
1863 Actions.ActOnInitializerError(ThisDecl);
1865 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1866 /*DirectInit=*/false, TypeContainsAuto);
1868 } else if (Tok.is(tok::l_paren)) {
1869 // Parse C++ direct initializer: '(' expression-list ')'
1870 BalancedDelimiterTracker T(*this, tok::l_paren);
1874 CommaLocsTy CommaLocs;
1876 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1878 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1881 if (ParseExpressionList(Exprs, CommaLocs)) {
1882 Actions.ActOnInitializerError(ThisDecl);
1883 SkipUntil(tok::r_paren);
1885 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1886 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1893 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1894 "Unexpected number of commas!");
1896 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1897 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1901 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
1902 T.getCloseLocation(),
1904 Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
1905 /*DirectInit=*/true, TypeContainsAuto);
1907 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
1908 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
1909 // Parse C++0x braced-init-list.
1910 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1912 if (D.getCXXScopeSpec().isSet()) {
1914 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1917 ExprResult Init(ParseBraceInitializer());
1919 if (D.getCXXScopeSpec().isSet()) {
1920 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1924 if (Init.isInvalid()) {
1925 Actions.ActOnInitializerError(ThisDecl);
1927 Actions.AddInitializerToDecl(ThisDecl, Init.take(),
1928 /*DirectInit=*/true, TypeContainsAuto);
1931 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1934 Actions.FinalizeDeclaration(ThisDecl);
1939 /// ParseSpecifierQualifierList
1940 /// specifier-qualifier-list:
1941 /// type-specifier specifier-qualifier-list[opt]
1942 /// type-qualifier specifier-qualifier-list[opt]
1943 /// [GNU] attributes specifier-qualifier-list[opt]
1945 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
1946 DeclSpecContext DSC) {
1947 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
1948 /// parse declaration-specifiers and complain about extra stuff.
1949 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
1950 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
1952 // Validate declspec for type-name.
1953 unsigned Specs = DS.getParsedSpecifiers();
1954 if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
1955 !DS.hasTypeSpecifier()) {
1956 Diag(Tok, diag::err_expected_type);
1957 DS.SetTypeSpecError();
1958 } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1959 !DS.hasAttributes()) {
1960 Diag(Tok, diag::err_typename_requires_specqual);
1961 if (!DS.hasTypeSpecifier())
1962 DS.SetTypeSpecError();
1965 // Issue diagnostic and remove storage class if present.
1966 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1967 if (DS.getStorageClassSpecLoc().isValid())
1968 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1970 Diag(DS.getThreadStorageClassSpecLoc(),
1971 diag::err_typename_invalid_storageclass);
1972 DS.ClearStorageClassSpecs();
1975 // Issue diagnostic and remove function specfier if present.
1976 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1977 if (DS.isInlineSpecified())
1978 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1979 if (DS.isVirtualSpecified())
1980 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1981 if (DS.isExplicitSpecified())
1982 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1983 DS.ClearFunctionSpecs();
1986 // Issue diagnostic and remove constexpr specfier if present.
1987 if (DS.isConstexprSpecified()) {
1988 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
1989 DS.ClearConstexprSpec();
1993 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1994 /// specified token is valid after the identifier in a declarator which
1995 /// immediately follows the declspec. For example, these things are valid:
1997 /// int x [ 4]; // direct-declarator
1998 /// int x ( int y); // direct-declarator
1999 /// int(int x ) // direct-declarator
2000 /// int x ; // simple-declaration
2001 /// int x = 17; // init-declarator-list
2002 /// int x , y; // init-declarator-list
2003 /// int x __asm__ ("foo"); // init-declarator-list
2004 /// int x : 4; // struct-declarator
2005 /// int x { 5}; // C++'0x unified initializers
2007 /// This is not, because 'x' does not immediately follow the declspec (though
2008 /// ')' happens to be valid anyway).
2011 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2012 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
2013 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
2014 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
2018 /// ParseImplicitInt - This method is called when we have an non-typename
2019 /// identifier in a declspec (which normally terminates the decl spec) when
2020 /// the declspec has no type specifier. In this case, the declspec is either
2021 /// malformed or is "implicit int" (in K&R and C89).
2023 /// This method handles diagnosing this prettily and returns false if the
2024 /// declspec is done being processed. If it recovers and thinks there may be
2025 /// other pieces of declspec after it, it returns true.
2027 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2028 const ParsedTemplateInfo &TemplateInfo,
2029 AccessSpecifier AS, DeclSpecContext DSC,
2030 ParsedAttributesWithRange &Attrs) {
2031 assert(Tok.is(tok::identifier) && "should have identifier");
2033 SourceLocation Loc = Tok.getLocation();
2034 // If we see an identifier that is not a type name, we normally would
2035 // parse it as the identifer being declared. However, when a typename
2036 // is typo'd or the definition is not included, this will incorrectly
2037 // parse the typename as the identifier name and fall over misparsing
2038 // later parts of the diagnostic.
2040 // As such, we try to do some look-ahead in cases where this would
2041 // otherwise be an "implicit-int" case to see if this is invalid. For
2042 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2043 // an identifier with implicit int, we'd get a parse error because the
2044 // next token is obviously invalid for a type. Parse these as a case
2045 // with an invalid type specifier.
2046 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2048 // Since we know that this either implicit int (which is rare) or an
2049 // error, do lookahead to try to do better recovery. This never applies
2050 // within a type specifier. Outside of C++, we allow this even if the
2051 // language doesn't "officially" support implicit int -- we support
2052 // implicit int as an extension in C99 and C11.
2053 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2054 !getLangOpts().CPlusPlus &&
2055 isValidAfterIdentifierInDeclarator(NextToken())) {
2056 // If this token is valid for implicit int, e.g. "static x = 4", then
2057 // we just avoid eating the identifier, so it will be parsed as the
2058 // identifier in the declarator.
2062 if (getLangOpts().CPlusPlus &&
2063 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2064 // Don't require a type specifier if we have the 'auto' storage class
2065 // specifier in C++98 -- we'll promote it to a type specifier.
2069 // Otherwise, if we don't consume this token, we are going to emit an
2070 // error anyway. Try to recover from various common problems. Check
2071 // to see if this was a reference to a tag name without a tag specified.
2072 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2074 // C++ doesn't need this, and isTagName doesn't take SS.
2076 const char *TagName = 0, *FixitTagName = 0;
2077 tok::TokenKind TagKind = tok::unknown;
2079 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2081 case DeclSpec::TST_enum:
2082 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2083 case DeclSpec::TST_union:
2084 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2085 case DeclSpec::TST_struct:
2086 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2087 case DeclSpec::TST_interface:
2088 TagName="__interface"; FixitTagName = "__interface ";
2089 TagKind=tok::kw___interface;break;
2090 case DeclSpec::TST_class:
2091 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2095 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2096 LookupResult R(Actions, TokenName, SourceLocation(),
2097 Sema::LookupOrdinaryName);
2099 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2100 << TokenName << TagName << getLangOpts().CPlusPlus
2101 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2103 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2104 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2106 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2107 << TokenName << TagName;
2110 // Parse this as a tag as if the missing tag were present.
2111 if (TagKind == tok::kw_enum)
2112 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2114 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2115 /*EnteringContext*/ false, DSC_normal, Attrs);
2120 // Determine whether this identifier could plausibly be the name of something
2121 // being declared (with a missing type).
2122 if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
2123 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2124 // Look ahead to the next token to try to figure out what this declaration
2125 // was supposed to be.
2126 switch (NextToken().getKind()) {
2133 // This looks like a variable declaration. The type is probably missing.
2134 // We're done parsing decl-specifiers.
2137 case tok::l_paren: {
2138 // static x(4); // 'x' is not a type
2139 // x(int n); // 'x' is not a type
2140 // x (*p)[]; // 'x' is a type
2142 // Since we're in an error case (or the rare 'implicit int in C++' MS
2143 // extension), we can afford to perform a tentative parse to determine
2144 // which case we're in.
2145 TentativeParsingAction PA(*this);
2147 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2149 if (TPR == TPResult::False())
2151 // The identifier is followed by a parenthesized declarator.
2152 // It's supposed to be a type.
2157 // This is probably supposed to be a type. This includes cases like:
2159 // struct S { unsinged : 4; };
2164 // This is almost certainly an invalid type name. Let the action emit a
2165 // diagnostic and attempt to recover.
2167 IdentifierInfo *II = Tok.getIdentifierInfo();
2168 if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
2169 // The action emitted a diagnostic, so we don't have to.
2171 // The action has suggested that the type T could be used. Set that as
2172 // the type in the declaration specifiers, consume the would-be type
2173 // name token, and we're done.
2174 const char *PrevSpec;
2176 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
2177 DS.SetRangeEnd(Tok.getLocation());
2179 // There may be other declaration specifiers after this.
2181 } else if (II != Tok.getIdentifierInfo()) {
2182 // If no type was suggested, the correction is to a keyword
2183 Tok.setKind(II->getTokenID());
2184 // There may be other declaration specifiers after this.
2188 // Fall through; the action had no suggestion for us.
2190 // The action did not emit a diagnostic, so emit one now.
2192 if (SS) R = SS->getRange();
2193 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
2196 // Mark this as an error.
2197 DS.SetTypeSpecError();
2198 DS.SetRangeEnd(Tok.getLocation());
2201 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2202 // avoid rippling error messages on subsequent uses of the same type,
2203 // could be useful if #include was forgotten.
2207 /// \brief Determine the declaration specifier context from the declarator
2210 /// \param Context the declarator context, which is one of the
2211 /// Declarator::TheContext enumerator values.
2212 Parser::DeclSpecContext
2213 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2214 if (Context == Declarator::MemberContext)
2216 if (Context == Declarator::FileContext)
2217 return DSC_top_level;
2218 if (Context == Declarator::TrailingReturnContext)
2219 return DSC_trailing;
2223 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2225 /// FIXME: Simply returns an alignof() expression if the argument is a
2226 /// type. Ideally, the type should be propagated directly into Sema.
2229 /// [C11] constant-expression
2230 /// [C++0x] type-id ...[opt]
2231 /// [C++0x] assignment-expression ...[opt]
2232 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2233 SourceLocation &EllipsisLoc) {
2235 if (isTypeIdInParens()) {
2236 SourceLocation TypeLoc = Tok.getLocation();
2237 ParsedType Ty = ParseTypeName().get();
2238 SourceRange TypeRange(Start, Tok.getLocation());
2239 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2240 Ty.getAsOpaquePtr(), TypeRange);
2242 ER = ParseConstantExpression();
2244 if (getLangOpts().CPlusPlus11 && Tok.is(tok::ellipsis))
2245 EllipsisLoc = ConsumeToken();
2250 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2251 /// attribute to Attrs.
2253 /// alignment-specifier:
2254 /// [C11] '_Alignas' '(' type-id ')'
2255 /// [C11] '_Alignas' '(' constant-expression ')'
2256 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2257 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2258 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2259 SourceLocation *EndLoc) {
2260 assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
2261 "Not an alignment-specifier!");
2263 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2264 SourceLocation KWLoc = ConsumeToken();
2266 BalancedDelimiterTracker T(*this, tok::l_paren);
2267 if (T.expectAndConsume(diag::err_expected_lparen))
2270 SourceLocation EllipsisLoc;
2271 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2272 if (ArgExpr.isInvalid()) {
2273 SkipUntil(tok::r_paren);
2279 *EndLoc = T.getCloseLocation();
2281 ExprVector ArgExprs;
2282 ArgExprs.push_back(ArgExpr.release());
2283 Attrs.addNew(KWName, KWLoc, 0, KWLoc, 0, T.getOpenLocation(),
2284 ArgExprs.data(), 1, AttributeList::AS_Keyword, EllipsisLoc);
2287 /// ParseDeclarationSpecifiers
2288 /// declaration-specifiers: [C99 6.7]
2289 /// storage-class-specifier declaration-specifiers[opt]
2290 /// type-specifier declaration-specifiers[opt]
2291 /// [C99] function-specifier declaration-specifiers[opt]
2292 /// [C11] alignment-specifier declaration-specifiers[opt]
2293 /// [GNU] attributes declaration-specifiers[opt]
2294 /// [Clang] '__module_private__' declaration-specifiers[opt]
2296 /// storage-class-specifier: [C99 6.7.1]
2303 /// [C++11] 'thread_local'
2304 /// [C11] '_Thread_local'
2305 /// [GNU] '__thread'
2306 /// function-specifier: [C99 6.7.4]
2309 /// [C++] 'explicit'
2310 /// [OpenCL] '__kernel'
2311 /// 'friend': [C++ dcl.friend]
2312 /// 'constexpr': [C++0x dcl.constexpr]
2315 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2316 const ParsedTemplateInfo &TemplateInfo,
2318 DeclSpecContext DSContext,
2319 LateParsedAttrList *LateAttrs) {
2320 if (DS.getSourceRange().isInvalid()) {
2321 DS.SetRangeStart(Tok.getLocation());
2322 DS.SetRangeEnd(Tok.getLocation());
2325 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2326 bool AttrsLastTime = false;
2327 ParsedAttributesWithRange attrs(AttrFactory);
2329 bool isInvalid = false;
2330 const char *PrevSpec = 0;
2331 unsigned DiagID = 0;
2333 SourceLocation Loc = Tok.getLocation();
2335 switch (Tok.getKind()) {
2339 ProhibitAttributes(attrs);
2341 // Reject C++11 attributes that appertain to decl specifiers as
2342 // we don't support any C++11 attributes that appertain to decl
2343 // specifiers. This also conforms to what g++ 4.8 is doing.
2344 ProhibitCXX11Attributes(attrs);
2346 DS.takeAttributesFrom(attrs);
2349 // If this is not a declaration specifier token, we're done reading decl
2350 // specifiers. First verify that DeclSpec's are consistent.
2351 DS.Finish(Diags, PP);
2355 case tok::kw_alignas:
2356 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2357 goto DoneWithDeclSpec;
2359 ProhibitAttributes(attrs);
2360 // FIXME: It would be good to recover by accepting the attributes,
2361 // but attempting to do that now would cause serious
2362 // madness in terms of diagnostics.
2364 attrs.Range = SourceRange();
2366 ParseCXX11Attributes(attrs);
2367 AttrsLastTime = true;
2370 case tok::code_completion: {
2371 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2372 if (DS.hasTypeSpecifier()) {
2373 bool AllowNonIdentifiers
2374 = (getCurScope()->getFlags() & (Scope::ControlScope |
2376 Scope::TemplateParamScope |
2377 Scope::FunctionPrototypeScope |
2378 Scope::AtCatchScope)) == 0;
2379 bool AllowNestedNameSpecifiers
2380 = DSContext == DSC_top_level ||
2381 (DSContext == DSC_class && DS.isFriendSpecified());
2383 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2384 AllowNonIdentifiers,
2385 AllowNestedNameSpecifiers);
2386 return cutOffParsing();
2389 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2390 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2391 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2392 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2393 : Sema::PCC_Template;
2394 else if (DSContext == DSC_class)
2395 CCC = Sema::PCC_Class;
2396 else if (CurParsedObjCImpl)
2397 CCC = Sema::PCC_ObjCImplementation;
2399 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2400 return cutOffParsing();
2403 case tok::coloncolon: // ::foo::bar
2404 // C++ scope specifier. Annotate and loop, or bail out on error.
2405 if (TryAnnotateCXXScopeToken(true)) {
2406 if (!DS.hasTypeSpecifier())
2407 DS.SetTypeSpecError();
2408 goto DoneWithDeclSpec;
2410 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2411 goto DoneWithDeclSpec;
2414 case tok::annot_cxxscope: {
2415 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2416 goto DoneWithDeclSpec;
2419 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2420 Tok.getAnnotationRange(),
2423 // We are looking for a qualified typename.
2424 Token Next = NextToken();
2425 if (Next.is(tok::annot_template_id) &&
2426 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2427 ->Kind == TNK_Type_template) {
2428 // We have a qualified template-id, e.g., N::A<int>
2430 // C++ [class.qual]p2:
2431 // In a lookup in which the constructor is an acceptable lookup
2432 // result and the nested-name-specifier nominates a class C:
2434 // - if the name specified after the
2435 // nested-name-specifier, when looked up in C, is the
2436 // injected-class-name of C (Clause 9), or
2438 // - if the name specified after the nested-name-specifier
2439 // is the same as the identifier or the
2440 // simple-template-id's template-name in the last
2441 // component of the nested-name-specifier,
2443 // the name is instead considered to name the constructor of
2446 // Thus, if the template-name is actually the constructor
2447 // name, then the code is ill-formed; this interpretation is
2448 // reinforced by the NAD status of core issue 635.
2449 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2450 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2452 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2453 if (isConstructorDeclarator()) {
2454 // The user meant this to be an out-of-line constructor
2455 // definition, but template arguments are not allowed
2456 // there. Just allow this as a constructor; we'll
2457 // complain about it later.
2458 goto DoneWithDeclSpec;
2461 // The user meant this to name a type, but it actually names
2462 // a constructor with some extraneous template
2463 // arguments. Complain, then parse it as a type as the user
2465 Diag(TemplateId->TemplateNameLoc,
2466 diag::err_out_of_line_template_id_names_constructor)
2467 << TemplateId->Name;
2470 DS.getTypeSpecScope() = SS;
2471 ConsumeToken(); // The C++ scope.
2472 assert(Tok.is(tok::annot_template_id) &&
2473 "ParseOptionalCXXScopeSpecifier not working");
2474 AnnotateTemplateIdTokenAsType();
2478 if (Next.is(tok::annot_typename)) {
2479 DS.getTypeSpecScope() = SS;
2480 ConsumeToken(); // The C++ scope.
2481 if (Tok.getAnnotationValue()) {
2482 ParsedType T = getTypeAnnotation(Tok);
2483 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2484 Tok.getAnnotationEndLoc(),
2485 PrevSpec, DiagID, T);
2490 DS.SetTypeSpecError();
2491 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2492 ConsumeToken(); // The typename
2495 if (Next.isNot(tok::identifier))
2496 goto DoneWithDeclSpec;
2498 // If we're in a context where the identifier could be a class name,
2499 // check whether this is a constructor declaration.
2500 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2501 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2503 if (isConstructorDeclarator())
2504 goto DoneWithDeclSpec;
2506 // As noted in C++ [class.qual]p2 (cited above), when the name
2507 // of the class is qualified in a context where it could name
2508 // a constructor, its a constructor name. However, we've
2509 // looked at the declarator, and the user probably meant this
2510 // to be a type. Complain that it isn't supposed to be treated
2511 // as a type, then proceed to parse it as a type.
2512 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2513 << Next.getIdentifierInfo();
2516 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2519 false, false, ParsedType(),
2520 /*IsCtorOrDtorName=*/false,
2521 /*NonTrivialSourceInfo=*/true);
2523 // If the referenced identifier is not a type, then this declspec is
2524 // erroneous: We already checked about that it has no type specifier, and
2525 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2528 ConsumeToken(); // Eat the scope spec so the identifier is current.
2529 ParsedAttributesWithRange Attrs(AttrFactory);
2530 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2531 if (!Attrs.empty()) {
2532 AttrsLastTime = true;
2533 attrs.takeAllFrom(Attrs);
2537 goto DoneWithDeclSpec;
2540 DS.getTypeSpecScope() = SS;
2541 ConsumeToken(); // The C++ scope.
2543 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2548 DS.SetRangeEnd(Tok.getLocation());
2549 ConsumeToken(); // The typename.
2554 case tok::annot_typename: {
2555 if (Tok.getAnnotationValue()) {
2556 ParsedType T = getTypeAnnotation(Tok);
2557 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2560 DS.SetTypeSpecError();
2565 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2566 ConsumeToken(); // The typename
2568 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2569 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2570 // Objective-C interface.
2571 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2572 ParseObjCProtocolQualifiers(DS);
2577 case tok::kw___is_signed:
2578 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2579 // typically treats it as a trait. If we see __is_signed as it appears
2580 // in libstdc++, e.g.,
2582 // static const bool __is_signed;
2584 // then treat __is_signed as an identifier rather than as a keyword.
2585 if (DS.getTypeSpecType() == TST_bool &&
2586 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2587 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2588 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
2589 Tok.setKind(tok::identifier);
2592 // We're done with the declaration-specifiers.
2593 goto DoneWithDeclSpec;
2596 case tok::kw_decltype:
2597 case tok::identifier: {
2598 // In C++, check to see if this is a scope specifier like foo::bar::, if
2599 // so handle it as such. This is important for ctor parsing.
2600 if (getLangOpts().CPlusPlus) {
2601 if (TryAnnotateCXXScopeToken(true)) {
2602 if (!DS.hasTypeSpecifier())
2603 DS.SetTypeSpecError();
2604 goto DoneWithDeclSpec;
2606 if (!Tok.is(tok::identifier))
2610 // This identifier can only be a typedef name if we haven't already seen
2611 // a type-specifier. Without this check we misparse:
2612 // typedef int X; struct Y { short X; }; as 'short int'.
2613 if (DS.hasTypeSpecifier())
2614 goto DoneWithDeclSpec;
2616 // Check for need to substitute AltiVec keyword tokens.
2617 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2620 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2621 // allow the use of a typedef name as a type specifier.
2622 if (DS.isTypeAltiVecVector())
2623 goto DoneWithDeclSpec;
2625 ParsedType TypeRep =
2626 Actions.getTypeName(*Tok.getIdentifierInfo(),
2627 Tok.getLocation(), getCurScope());
2629 // If this is not a typedef name, don't parse it as part of the declspec,
2630 // it must be an implicit int or an error.
2632 ParsedAttributesWithRange Attrs(AttrFactory);
2633 if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext, Attrs)) {
2634 if (!Attrs.empty()) {
2635 AttrsLastTime = true;
2636 attrs.takeAllFrom(Attrs);
2640 goto DoneWithDeclSpec;
2643 // If we're in a context where the identifier could be a class name,
2644 // check whether this is a constructor declaration.
2645 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2646 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2647 isConstructorDeclarator())
2648 goto DoneWithDeclSpec;
2650 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2655 DS.SetRangeEnd(Tok.getLocation());
2656 ConsumeToken(); // The identifier
2658 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
2659 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
2660 // Objective-C interface.
2661 if (Tok.is(tok::less) && getLangOpts().ObjC1)
2662 ParseObjCProtocolQualifiers(DS);
2664 // Need to support trailing type qualifiers (e.g. "id<p> const").
2665 // If a type specifier follows, it will be diagnosed elsewhere.
2670 case tok::annot_template_id: {
2671 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2672 if (TemplateId->Kind != TNK_Type_template) {
2673 // This template-id does not refer to a type name, so we're
2674 // done with the type-specifiers.
2675 goto DoneWithDeclSpec;
2678 // If we're in a context where the template-id could be a
2679 // constructor name or specialization, check whether this is a
2680 // constructor declaration.
2681 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2682 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
2683 isConstructorDeclarator())
2684 goto DoneWithDeclSpec;
2686 // Turn the template-id annotation token into a type annotation
2687 // token, then try again to parse it as a type-specifier.
2688 AnnotateTemplateIdTokenAsType();
2692 // GNU attributes support.
2693 case tok::kw___attribute:
2694 ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
2697 // Microsoft declspec support.
2698 case tok::kw___declspec:
2699 ParseMicrosoftDeclSpec(DS.getAttributes());
2702 // Microsoft single token adornments.
2703 case tok::kw___forceinline: {
2704 isInvalid = DS.setFunctionSpecInline(Loc);
2705 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
2706 SourceLocation AttrNameLoc = Tok.getLocation();
2707 // FIXME: This does not work correctly if it is set to be a declspec
2708 // attribute, and a GNU attribute is simply incorrect.
2709 DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
2710 SourceLocation(), 0, 0, AttributeList::AS_GNU);
2714 case tok::kw___ptr64:
2715 case tok::kw___ptr32:
2717 case tok::kw___cdecl:
2718 case tok::kw___stdcall:
2719 case tok::kw___fastcall:
2720 case tok::kw___thiscall:
2721 case tok::kw___unaligned:
2722 ParseMicrosoftTypeAttributes(DS.getAttributes());
2725 // Borland single token adornments.
2726 case tok::kw___pascal:
2727 ParseBorlandTypeAttributes(DS.getAttributes());
2730 // OpenCL single token adornments.
2731 case tok::kw___kernel:
2732 ParseOpenCLAttributes(DS.getAttributes());
2735 // storage-class-specifier
2736 case tok::kw_typedef:
2737 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
2740 case tok::kw_extern:
2741 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2742 Diag(Tok, diag::ext_thread_before) << "extern";
2743 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
2746 case tok::kw___private_extern__:
2747 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
2748 Loc, PrevSpec, DiagID);
2750 case tok::kw_static:
2751 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
2752 Diag(Tok, diag::ext_thread_before) << "static";
2753 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
2757 if (getLangOpts().CPlusPlus11) {
2758 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
2759 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2762 Diag(Tok, diag::ext_auto_storage_class)
2763 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2765 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
2768 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
2771 case tok::kw_register:
2772 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
2775 case tok::kw_mutable:
2776 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
2779 case tok::kw___thread:
2780 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
2783 case tok::kw_thread_local:
2784 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
2787 case tok::kw__Thread_local:
2788 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
2789 Loc, PrevSpec, DiagID);
2792 // function-specifier
2793 case tok::kw_inline:
2794 isInvalid = DS.setFunctionSpecInline(Loc);
2796 case tok::kw_virtual:
2797 isInvalid = DS.setFunctionSpecVirtual(Loc);
2799 case tok::kw_explicit:
2800 isInvalid = DS.setFunctionSpecExplicit(Loc);
2802 case tok::kw__Noreturn:
2803 if (!getLangOpts().C11)
2804 Diag(Loc, diag::ext_c11_noreturn);
2805 isInvalid = DS.setFunctionSpecNoreturn(Loc);
2808 // alignment-specifier
2809 case tok::kw__Alignas:
2810 if (!getLangOpts().C11)
2811 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
2812 ParseAlignmentSpecifier(DS.getAttributes());
2816 case tok::kw_friend:
2817 if (DSContext == DSC_class)
2818 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
2820 PrevSpec = ""; // not actually used by the diagnostic
2821 DiagID = diag::err_friend_invalid_in_context;
2827 case tok::kw___module_private__:
2828 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
2832 case tok::kw_constexpr:
2833 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
2838 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
2842 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2843 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2846 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2849 case tok::kw___int64:
2850 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2853 case tok::kw_signed:
2854 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
2857 case tok::kw_unsigned:
2858 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2861 case tok::kw__Complex:
2862 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2865 case tok::kw__Imaginary:
2866 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2870 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
2874 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
2878 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
2881 case tok::kw___int128:
2882 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
2886 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
2890 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
2893 case tok::kw_double:
2894 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
2897 case tok::kw_wchar_t:
2898 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
2901 case tok::kw_char16_t:
2902 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
2905 case tok::kw_char32_t:
2906 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
2911 if (Tok.is(tok::kw_bool) &&
2912 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
2913 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2914 PrevSpec = ""; // Not used by the diagnostic.
2915 DiagID = diag::err_bool_redeclaration;
2916 // For better error recovery.
2917 Tok.setKind(tok::identifier);
2920 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
2924 case tok::kw__Decimal32:
2925 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2928 case tok::kw__Decimal64:
2929 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2932 case tok::kw__Decimal128:
2933 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2936 case tok::kw___vector:
2937 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2939 case tok::kw___pixel:
2940 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2942 case tok::kw_image1d_t:
2943 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_t, Loc,
2946 case tok::kw_image1d_array_t:
2947 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_array_t, Loc,
2950 case tok::kw_image1d_buffer_t:
2951 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image1d_buffer_t, Loc,
2954 case tok::kw_image2d_t:
2955 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_t, Loc,
2958 case tok::kw_image2d_array_t:
2959 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image2d_array_t, Loc,
2962 case tok::kw_image3d_t:
2963 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_image3d_t, Loc,
2966 case tok::kw_sampler_t:
2967 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_sampler_t, Loc,
2970 case tok::kw_event_t:
2971 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_event_t, Loc,
2974 case tok::kw___unknown_anytype:
2975 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
2981 case tok::kw_struct:
2982 case tok::kw___interface:
2983 case tok::kw_union: {
2984 tok::TokenKind Kind = Tok.getKind();
2987 // These are attributes following class specifiers.
2988 // To produce better diagnostic, we parse them when
2989 // parsing class specifier.
2990 ParsedAttributesWithRange Attributes(AttrFactory);
2991 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
2992 EnteringContext, DSContext, Attributes);
2994 // If there are attributes following class specifier,
2995 // take them over and handle them here.
2996 if (!Attributes.empty()) {
2997 AttrsLastTime = true;
2998 attrs.takeAllFrom(Attributes);
3006 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3011 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3014 case tok::kw_volatile:
3015 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3018 case tok::kw_restrict:
3019 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3023 // C++ typename-specifier:
3024 case tok::kw_typename:
3025 if (TryAnnotateTypeOrScopeToken()) {
3026 DS.SetTypeSpecError();
3027 goto DoneWithDeclSpec;
3029 if (!Tok.is(tok::kw_typename))
3033 // GNU typeof support.
3034 case tok::kw_typeof:
3035 ParseTypeofSpecifier(DS);
3038 case tok::annot_decltype:
3039 ParseDecltypeSpecifier(DS);
3042 case tok::kw___underlying_type:
3043 ParseUnderlyingTypeSpecifier(DS);
3046 case tok::kw__Atomic:
3048 // If the _Atomic keyword is immediately followed by a left parenthesis,
3049 // it is interpreted as a type specifier (with a type name), not as a
3051 if (NextToken().is(tok::l_paren)) {
3052 ParseAtomicSpecifier(DS);
3055 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3059 // OpenCL qualifiers:
3060 case tok::kw_private:
3061 if (!getLangOpts().OpenCL)
3062 goto DoneWithDeclSpec;
3063 case tok::kw___private:
3064 case tok::kw___global:
3065 case tok::kw___local:
3066 case tok::kw___constant:
3067 case tok::kw___read_only:
3068 case tok::kw___write_only:
3069 case tok::kw___read_write:
3070 ParseOpenCLQualifiers(DS);
3074 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3075 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3076 // but we support it.
3077 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3078 goto DoneWithDeclSpec;
3080 if (!ParseObjCProtocolQualifiers(DS))
3081 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
3082 << FixItHint::CreateInsertion(Loc, "id")
3083 << SourceRange(Loc, DS.getSourceRange().getEnd());
3085 // Need to support trailing type qualifiers (e.g. "id<p> const").
3086 // If a type specifier follows, it will be diagnosed elsewhere.
3089 // If the specifier wasn't legal, issue a diagnostic.
3091 assert(PrevSpec && "Method did not return previous specifier!");
3094 if (DiagID == diag::ext_duplicate_declspec)
3096 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3098 Diag(Tok, DiagID) << PrevSpec;
3101 DS.SetRangeEnd(Tok.getLocation());
3102 if (DiagID != diag::err_bool_redeclaration)
3105 AttrsLastTime = false;
3109 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3112 /// struct-declaration:
3113 /// specifier-qualifier-list struct-declarator-list
3114 /// [GNU] __extension__ struct-declaration
3115 /// [GNU] specifier-qualifier-list
3116 /// struct-declarator-list:
3117 /// struct-declarator
3118 /// struct-declarator-list ',' struct-declarator
3119 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3120 /// struct-declarator:
3122 /// [GNU] declarator attributes[opt]
3123 /// declarator[opt] ':' constant-expression
3124 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3127 ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
3129 if (Tok.is(tok::kw___extension__)) {
3130 // __extension__ silences extension warnings in the subexpression.
3131 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3133 return ParseStructDeclaration(DS, Fields);
3136 // Parse the common specifier-qualifiers-list piece.
3137 ParseSpecifierQualifierList(DS);
3139 // If there are no declarators, this is a free-standing declaration
3140 // specifier. Let the actions module cope with it.
3141 if (Tok.is(tok::semi)) {
3142 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3144 DS.complete(TheDecl);
3148 // Read struct-declarators until we find the semicolon.
3149 bool FirstDeclarator = true;
3150 SourceLocation CommaLoc;
3152 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3153 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3155 // Attributes are only allowed here on successive declarators.
3156 if (!FirstDeclarator)
3157 MaybeParseGNUAttributes(DeclaratorInfo.D);
3159 /// struct-declarator: declarator
3160 /// struct-declarator: declarator[opt] ':' constant-expression
3161 if (Tok.isNot(tok::colon)) {
3162 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3163 ColonProtectionRAIIObject X(*this);
3164 ParseDeclarator(DeclaratorInfo.D);
3167 if (Tok.is(tok::colon)) {
3169 ExprResult Res(ParseConstantExpression());
3170 if (Res.isInvalid())
3171 SkipUntil(tok::semi, true, true);
3173 DeclaratorInfo.BitfieldSize = Res.release();
3176 // If attributes exist after the declarator, parse them.
3177 MaybeParseGNUAttributes(DeclaratorInfo.D);
3179 // We're done with this declarator; invoke the callback.
3180 Fields.invoke(DeclaratorInfo);
3182 // If we don't have a comma, it is either the end of the list (a ';')
3183 // or an error, bail out.
3184 if (Tok.isNot(tok::comma))
3187 // Consume the comma.
3188 CommaLoc = ConsumeToken();
3190 FirstDeclarator = false;
3194 /// ParseStructUnionBody
3195 /// struct-contents:
3196 /// struct-declaration-list
3198 /// [GNU] "struct-declaration-list" without terminatoring ';'
3199 /// struct-declaration-list:
3200 /// struct-declaration
3201 /// struct-declaration-list struct-declaration
3202 /// [OBC] '@' 'defs' '(' class-name ')'
3204 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3205 unsigned TagType, Decl *TagDecl) {
3206 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3207 "parsing struct/union body");
3208 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3210 BalancedDelimiterTracker T(*this, tok::l_brace);
3211 if (T.consumeOpen())
3214 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3215 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3217 // Empty structs are an extension in C (C99 6.7.2.1p7).
3218 if (Tok.is(tok::r_brace)) {
3219 Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
3220 Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
3223 SmallVector<Decl *, 32> FieldDecls;
3225 // While we still have something to read, read the declarations in the struct.
3226 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3227 // Each iteration of this loop reads one struct-declaration.
3229 // Check for extraneous top-level semicolon.
3230 if (Tok.is(tok::semi)) {
3231 ConsumeExtraSemi(InsideStruct, TagType);
3235 // Parse _Static_assert declaration.
3236 if (Tok.is(tok::kw__Static_assert)) {
3237 SourceLocation DeclEnd;
3238 ParseStaticAssertDeclaration(DeclEnd);
3242 if (Tok.is(tok::annot_pragma_pack)) {
3247 if (Tok.is(tok::annot_pragma_align)) {
3248 HandlePragmaAlign();
3252 if (!Tok.is(tok::at)) {
3253 struct CFieldCallback : FieldCallback {
3256 SmallVectorImpl<Decl *> &FieldDecls;
3258 CFieldCallback(Parser &P, Decl *TagDecl,
3259 SmallVectorImpl<Decl *> &FieldDecls) :
3260 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
3262 void invoke(ParsingFieldDeclarator &FD) {
3263 // Install the declarator into the current TagDecl.
3264 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
3265 FD.D.getDeclSpec().getSourceRange().getBegin(),
3266 FD.D, FD.BitfieldSize);
3267 FieldDecls.push_back(Field);
3270 } Callback(*this, TagDecl, FieldDecls);
3272 // Parse all the comma separated declarators.
3273 ParsingDeclSpec DS(*this);
3274 ParseStructDeclaration(DS, Callback);
3275 } else { // Handle @defs
3277 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3278 Diag(Tok, diag::err_unexpected_at);
3279 SkipUntil(tok::semi, true);
3283 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
3284 if (!Tok.is(tok::identifier)) {
3285 Diag(Tok, diag::err_expected_ident);
3286 SkipUntil(tok::semi, true);
3289 SmallVector<Decl *, 16> Fields;
3290 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3291 Tok.getIdentifierInfo(), Fields);
3292 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3294 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
3297 if (Tok.is(tok::semi)) {
3299 } else if (Tok.is(tok::r_brace)) {
3300 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3303 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3304 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3305 SkipUntil(tok::r_brace, true, true);
3306 // If we stopped at a ';', eat it.
3307 if (Tok.is(tok::semi)) ConsumeToken();
3313 ParsedAttributes attrs(AttrFactory);
3314 // If attributes exist after struct contents, parse them.
3315 MaybeParseGNUAttributes(attrs);
3317 Actions.ActOnFields(getCurScope(),
3318 RecordLoc, TagDecl, FieldDecls,
3319 T.getOpenLocation(), T.getCloseLocation(),
3322 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3323 T.getCloseLocation());
3326 /// ParseEnumSpecifier
3327 /// enum-specifier: [C99 6.7.2.2]
3328 /// 'enum' identifier[opt] '{' enumerator-list '}'
3329 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3330 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3331 /// '}' attributes[opt]
3332 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3334 /// 'enum' identifier
3335 /// [GNU] 'enum' attributes[opt] identifier
3337 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3338 /// [C++11] enum-head '{' enumerator-list ',' '}'
3340 /// enum-head: [C++11]
3341 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3342 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3343 /// identifier enum-base[opt]
3345 /// enum-key: [C++11]
3350 /// enum-base: [C++11]
3351 /// ':' type-specifier-seq
3353 /// [C++] elaborated-type-specifier:
3354 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3356 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3357 const ParsedTemplateInfo &TemplateInfo,
3358 AccessSpecifier AS, DeclSpecContext DSC) {
3359 // Parse the tag portion of this.
3360 if (Tok.is(tok::code_completion)) {
3361 // Code completion for an enum name.
3362 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3363 return cutOffParsing();
3366 // If attributes exist after tag, parse them.
3367 ParsedAttributesWithRange attrs(AttrFactory);
3368 MaybeParseGNUAttributes(attrs);
3369 MaybeParseCXX11Attributes(attrs);
3371 // If declspecs exist after tag, parse them.
3372 while (Tok.is(tok::kw___declspec))
3373 ParseMicrosoftDeclSpec(attrs);
3375 SourceLocation ScopedEnumKWLoc;
3376 bool IsScopedUsingClassTag = false;
3378 // In C++11, recognize 'enum class' and 'enum struct'.
3379 if (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct)) {
3380 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3381 : diag::ext_scoped_enum);
3382 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3383 ScopedEnumKWLoc = ConsumeToken();
3385 // Attributes are not allowed between these keywords. Diagnose,
3386 // but then just treat them like they appeared in the right place.
3387 ProhibitAttributes(attrs);
3389 // They are allowed afterwards, though.
3390 MaybeParseGNUAttributes(attrs);
3391 MaybeParseCXX11Attributes(attrs);
3392 while (Tok.is(tok::kw___declspec))
3393 ParseMicrosoftDeclSpec(attrs);
3396 // C++11 [temp.explicit]p12:
3397 // The usual access controls do not apply to names used to specify
3398 // explicit instantiations.
3399 // We extend this to also cover explicit specializations. Note that
3400 // we don't suppress if this turns out to be an elaborated type
3402 bool shouldDelayDiagsInTag =
3403 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3404 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3405 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3407 // Enum definitions should not be parsed in a trailing-return-type.
3408 bool AllowDeclaration = DSC != DSC_trailing;
3410 bool AllowFixedUnderlyingType = AllowDeclaration &&
3411 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3412 getLangOpts().ObjC2);
3414 CXXScopeSpec &SS = DS.getTypeSpecScope();
3415 if (getLangOpts().CPlusPlus) {
3416 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3417 // if a fixed underlying type is allowed.
3418 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3420 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
3421 /*EnteringContext=*/true))
3424 if (SS.isSet() && Tok.isNot(tok::identifier)) {
3425 Diag(Tok, diag::err_expected_ident);
3426 if (Tok.isNot(tok::l_brace)) {
3427 // Has no name and is not a definition.
3428 // Skip the rest of this declarator, up until the comma or semicolon.
3429 SkipUntil(tok::comma, true);
3435 // Must have either 'enum name' or 'enum {...}'.
3436 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3437 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3438 Diag(Tok, diag::err_expected_ident_lbrace);
3440 // Skip the rest of this declarator, up until the comma or semicolon.
3441 SkipUntil(tok::comma, true);
3445 // If an identifier is present, consume and remember it.
3446 IdentifierInfo *Name = 0;
3447 SourceLocation NameLoc;
3448 if (Tok.is(tok::identifier)) {
3449 Name = Tok.getIdentifierInfo();
3450 NameLoc = ConsumeToken();
3453 if (!Name && ScopedEnumKWLoc.isValid()) {
3454 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3455 // declaration of a scoped enumeration.
3456 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3457 ScopedEnumKWLoc = SourceLocation();
3458 IsScopedUsingClassTag = false;
3461 // Okay, end the suppression area. We'll decide whether to emit the
3462 // diagnostics in a second.
3463 if (shouldDelayDiagsInTag)
3464 diagsFromTag.done();
3466 TypeResult BaseType;
3468 // Parse the fixed underlying type.
3469 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3470 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3471 bool PossibleBitfield = false;
3472 if (CanBeBitfield) {
3473 // If we're in class scope, this can either be an enum declaration with
3474 // an underlying type, or a declaration of a bitfield member. We try to
3475 // use a simple disambiguation scheme first to catch the common cases
3476 // (integer literal, sizeof); if it's still ambiguous, we then consider
3477 // anything that's a simple-type-specifier followed by '(' as an
3478 // expression. This suffices because function types are not valid
3479 // underlying types anyway.
3480 EnterExpressionEvaluationContext Unevaluated(Actions,
3481 Sema::ConstantEvaluated);
3482 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3483 // If the next token starts an expression, we know we're parsing a
3484 // bit-field. This is the common case.
3485 if (TPR == TPResult::True())
3486 PossibleBitfield = true;
3487 // If the next token starts a type-specifier-seq, it may be either a
3488 // a fixed underlying type or the start of a function-style cast in C++;
3489 // lookahead one more token to see if it's obvious that we have a
3490 // fixed underlying type.
3491 else if (TPR == TPResult::False() &&
3492 GetLookAheadToken(2).getKind() == tok::semi) {
3496 // We have the start of a type-specifier-seq, so we have to perform
3497 // tentative parsing to determine whether we have an expression or a
3499 TentativeParsingAction TPA(*this);
3504 // If we see a type specifier followed by an open-brace, we have an
3505 // ambiguity between an underlying type and a C++11 braced
3506 // function-style cast. Resolve this by always treating it as an
3508 // FIXME: The standard is not entirely clear on how to disambiguate in
3510 if ((getLangOpts().CPlusPlus &&
3511 isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
3512 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3513 // We'll parse this as a bitfield later.
3514 PossibleBitfield = true;
3517 // We have a type-specifier-seq.
3526 if (!PossibleBitfield) {
3528 BaseType = ParseTypeName(&Range);
3530 if (getLangOpts().CPlusPlus11) {
3531 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3532 } else if (!getLangOpts().ObjC2) {
3533 if (getLangOpts().CPlusPlus)
3534 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3536 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3541 // There are four options here. If we have 'friend enum foo;' then this is a
3542 // friend declaration, and cannot have an accompanying definition. If we have
3543 // 'enum foo;', then this is a forward declaration. If we have
3544 // 'enum foo {...' then this is a definition. Otherwise we have something
3545 // like 'enum foo xyz', a reference.
3547 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3548 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3549 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3551 Sema::TagUseKind TUK;
3552 if (!AllowDeclaration) {
3553 TUK = Sema::TUK_Reference;
3554 } else if (Tok.is(tok::l_brace)) {
3555 if (DS.isFriendSpecified()) {
3556 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3557 << SourceRange(DS.getFriendSpecLoc());
3559 SkipUntil(tok::r_brace);
3560 TUK = Sema::TUK_Friend;
3562 TUK = Sema::TUK_Definition;
3564 } else if (DSC != DSC_type_specifier &&
3565 (Tok.is(tok::semi) ||
3566 (Tok.isAtStartOfLine() &&
3567 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3568 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3569 if (Tok.isNot(tok::semi)) {
3570 // A semicolon was missing after this declaration. Diagnose and recover.
3571 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
3574 Tok.setKind(tok::semi);
3577 TUK = Sema::TUK_Reference;
3580 // If this is an elaborated type specifier, and we delayed
3581 // diagnostics before, just merge them into the current pool.
3582 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3583 diagsFromTag.redelay();
3586 MultiTemplateParamsArg TParams;
3587 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3588 TUK != Sema::TUK_Reference) {
3589 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3590 // Skip the rest of this declarator, up until the comma or semicolon.
3591 Diag(Tok, diag::err_enum_template);
3592 SkipUntil(tok::comma, true);
3596 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3597 // Enumerations can't be explicitly instantiated.
3598 DS.SetTypeSpecError();
3599 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3603 assert(TemplateInfo.TemplateParams && "no template parameters");
3604 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3605 TemplateInfo.TemplateParams->size());
3608 if (TUK == Sema::TUK_Reference)
3609 ProhibitAttributes(attrs);
3611 if (!Name && TUK != Sema::TUK_Definition) {
3612 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3614 // Skip the rest of this declarator, up until the comma or semicolon.
3615 SkipUntil(tok::comma, true);
3620 bool IsDependent = false;
3621 const char *PrevSpec = 0;
3623 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3624 StartLoc, SS, Name, NameLoc, attrs.getList(),
3625 AS, DS.getModulePrivateSpecLoc(), TParams,
3626 Owned, IsDependent, ScopedEnumKWLoc,
3627 IsScopedUsingClassTag, BaseType);
3630 // This enum has a dependent nested-name-specifier. Handle it as a
3633 DS.SetTypeSpecError();
3634 Diag(Tok, diag::err_expected_type_name_after_typename);
3638 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
3639 TUK, SS, Name, StartLoc,
3641 if (Type.isInvalid()) {
3642 DS.SetTypeSpecError();
3646 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
3647 NameLoc.isValid() ? NameLoc : StartLoc,
3648 PrevSpec, DiagID, Type.get()))
3649 Diag(StartLoc, DiagID) << PrevSpec;
3655 // The action failed to produce an enumeration tag. If this is a
3656 // definition, consume the entire definition.
3657 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
3659 SkipUntil(tok::r_brace);
3662 DS.SetTypeSpecError();
3666 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
3667 ParseEnumBody(StartLoc, TagDecl);
3669 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3670 NameLoc.isValid() ? NameLoc : StartLoc,
3671 PrevSpec, DiagID, TagDecl, Owned))
3672 Diag(StartLoc, DiagID) << PrevSpec;
3675 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
3676 /// enumerator-list:
3678 /// enumerator-list ',' enumerator
3680 /// enumeration-constant
3681 /// enumeration-constant '=' constant-expression
3682 /// enumeration-constant:
3685 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
3686 // Enter the scope of the enum body and start the definition.
3687 ParseScope EnumScope(this, Scope::DeclScope);
3688 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
3690 BalancedDelimiterTracker T(*this, tok::l_brace);
3693 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
3694 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
3695 Diag(Tok, diag::error_empty_enum);
3697 SmallVector<Decl *, 32> EnumConstantDecls;
3699 Decl *LastEnumConstDecl = 0;
3701 // Parse the enumerator-list.
3702 while (Tok.is(tok::identifier)) {
3703 IdentifierInfo *Ident = Tok.getIdentifierInfo();
3704 SourceLocation IdentLoc = ConsumeToken();
3706 // If attributes exist after the enumerator, parse them.
3707 ParsedAttributesWithRange attrs(AttrFactory);
3708 MaybeParseGNUAttributes(attrs);
3709 MaybeParseCXX11Attributes(attrs);
3710 ProhibitAttributes(attrs);
3712 SourceLocation EqualLoc;
3713 ExprResult AssignedVal;
3714 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
3716 if (Tok.is(tok::equal)) {
3717 EqualLoc = ConsumeToken();
3718 AssignedVal = ParseConstantExpression();
3719 if (AssignedVal.isInvalid())
3720 SkipUntil(tok::comma, tok::r_brace, true, true);
3723 // Install the enumerator constant into EnumDecl.
3724 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
3727 attrs.getList(), EqualLoc,
3728 AssignedVal.release());
3729 PD.complete(EnumConstDecl);
3731 EnumConstantDecls.push_back(EnumConstDecl);
3732 LastEnumConstDecl = EnumConstDecl;
3734 if (Tok.is(tok::identifier)) {
3735 // We're missing a comma between enumerators.
3736 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3737 Diag(Loc, diag::err_enumerator_list_missing_comma)
3738 << FixItHint::CreateInsertion(Loc, ", ");
3742 if (Tok.isNot(tok::comma))
3744 SourceLocation CommaLoc = ConsumeToken();
3746 if (Tok.isNot(tok::identifier)) {
3747 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
3748 Diag(CommaLoc, getLangOpts().CPlusPlus ?
3749 diag::ext_enumerator_list_comma_cxx :
3750 diag::ext_enumerator_list_comma_c)
3751 << FixItHint::CreateRemoval(CommaLoc);
3752 else if (getLangOpts().CPlusPlus11)
3753 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
3754 << FixItHint::CreateRemoval(CommaLoc);
3761 // If attributes exist after the identifier list, parse them.
3762 ParsedAttributes attrs(AttrFactory);
3763 MaybeParseGNUAttributes(attrs);
3765 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
3766 EnumDecl, EnumConstantDecls,
3771 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
3772 T.getCloseLocation());
3774 // The next token must be valid after an enum definition. If not, a ';'
3775 // was probably forgotten.
3776 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3777 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
3778 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
3779 // Push this token back into the preprocessor and change our current token
3780 // to ';' so that the rest of the code recovers as though there were an
3781 // ';' after the definition.
3783 Tok.setKind(tok::semi);
3787 /// isTypeSpecifierQualifier - Return true if the current token could be the
3788 /// start of a type-qualifier-list.
3789 bool Parser::isTypeQualifier() const {
3790 switch (Tok.getKind()) {
3791 default: return false;
3793 // type-qualifier only in OpenCL
3794 case tok::kw_private:
3795 return getLangOpts().OpenCL;
3799 case tok::kw_volatile:
3800 case tok::kw_restrict:
3801 case tok::kw___private:
3802 case tok::kw___local:
3803 case tok::kw___global:
3804 case tok::kw___constant:
3805 case tok::kw___read_only:
3806 case tok::kw___read_write:
3807 case tok::kw___write_only:
3812 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
3813 /// is definitely a type-specifier. Return false if it isn't part of a type
3814 /// specifier or if we're not sure.
3815 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
3816 switch (Tok.getKind()) {
3817 default: return false;
3821 case tok::kw___int64:
3822 case tok::kw___int128:
3823 case tok::kw_signed:
3824 case tok::kw_unsigned:
3825 case tok::kw__Complex:
3826 case tok::kw__Imaginary:
3829 case tok::kw_wchar_t:
3830 case tok::kw_char16_t:
3831 case tok::kw_char32_t:
3835 case tok::kw_double:
3838 case tok::kw__Decimal32:
3839 case tok::kw__Decimal64:
3840 case tok::kw__Decimal128:
3841 case tok::kw___vector:
3843 // OpenCL specific types:
3844 case tok::kw_image1d_t:
3845 case tok::kw_image1d_array_t:
3846 case tok::kw_image1d_buffer_t:
3847 case tok::kw_image2d_t:
3848 case tok::kw_image2d_array_t:
3849 case tok::kw_image3d_t:
3850 case tok::kw_sampler_t:
3851 case tok::kw_event_t:
3853 // struct-or-union-specifier (C99) or class-specifier (C++)
3855 case tok::kw_struct:
3856 case tok::kw___interface:
3862 case tok::annot_typename:
3867 /// isTypeSpecifierQualifier - Return true if the current token could be the
3868 /// start of a specifier-qualifier-list.
3869 bool Parser::isTypeSpecifierQualifier() {
3870 switch (Tok.getKind()) {
3871 default: return false;
3873 case tok::identifier: // foo::bar
3874 if (TryAltiVecVectorToken())
3877 case tok::kw_typename: // typename T::type
3878 // Annotate typenames and C++ scope specifiers. If we get one, just
3879 // recurse to handle whatever we get.
3880 if (TryAnnotateTypeOrScopeToken())
3882 if (Tok.is(tok::identifier))
3884 return isTypeSpecifierQualifier();
3886 case tok::coloncolon: // ::foo::bar
3887 if (NextToken().is(tok::kw_new) || // ::new
3888 NextToken().is(tok::kw_delete)) // ::delete
3891 if (TryAnnotateTypeOrScopeToken())
3893 return isTypeSpecifierQualifier();
3895 // GNU attributes support.
3896 case tok::kw___attribute:
3897 // GNU typeof support.
3898 case tok::kw_typeof:
3903 case tok::kw___int64:
3904 case tok::kw___int128:
3905 case tok::kw_signed:
3906 case tok::kw_unsigned:
3907 case tok::kw__Complex:
3908 case tok::kw__Imaginary:
3911 case tok::kw_wchar_t:
3912 case tok::kw_char16_t:
3913 case tok::kw_char32_t:
3917 case tok::kw_double:
3920 case tok::kw__Decimal32:
3921 case tok::kw__Decimal64:
3922 case tok::kw__Decimal128:
3923 case tok::kw___vector:
3925 // OpenCL specific types:
3926 case tok::kw_image1d_t:
3927 case tok::kw_image1d_array_t:
3928 case tok::kw_image1d_buffer_t:
3929 case tok::kw_image2d_t:
3930 case tok::kw_image2d_array_t:
3931 case tok::kw_image3d_t:
3932 case tok::kw_sampler_t:
3933 case tok::kw_event_t:
3935 // struct-or-union-specifier (C99) or class-specifier (C++)
3937 case tok::kw_struct:
3938 case tok::kw___interface:
3945 case tok::kw_volatile:
3946 case tok::kw_restrict:
3948 // Debugger support.
3949 case tok::kw___unknown_anytype:
3952 case tok::annot_typename:
3955 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
3957 return getLangOpts().ObjC1;
3959 case tok::kw___cdecl:
3960 case tok::kw___stdcall:
3961 case tok::kw___fastcall:
3962 case tok::kw___thiscall:
3964 case tok::kw___ptr64:
3965 case tok::kw___ptr32:
3966 case tok::kw___pascal:
3967 case tok::kw___unaligned:
3969 case tok::kw___private:
3970 case tok::kw___local:
3971 case tok::kw___global:
3972 case tok::kw___constant:
3973 case tok::kw___read_only:
3974 case tok::kw___read_write:
3975 case tok::kw___write_only:
3979 case tok::kw_private:
3980 return getLangOpts().OpenCL;
3983 case tok::kw__Atomic:
3988 /// isDeclarationSpecifier() - Return true if the current token is part of a
3989 /// declaration specifier.
3991 /// \param DisambiguatingWithExpression True to indicate that the purpose of
3992 /// this check is to disambiguate between an expression and a declaration.
3993 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
3994 switch (Tok.getKind()) {
3995 default: return false;
3997 case tok::kw_private:
3998 return getLangOpts().OpenCL;
4000 case tok::identifier: // foo::bar
4001 // Unfortunate hack to support "Class.factoryMethod" notation.
4002 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4004 if (TryAltiVecVectorToken())
4007 case tok::kw_decltype: // decltype(T())::type
4008 case tok::kw_typename: // typename T::type
4009 // Annotate typenames and C++ scope specifiers. If we get one, just
4010 // recurse to handle whatever we get.
4011 if (TryAnnotateTypeOrScopeToken())
4013 if (Tok.is(tok::identifier))
4016 // If we're in Objective-C and we have an Objective-C class type followed
4017 // by an identifier and then either ':' or ']', in a place where an
4018 // expression is permitted, then this is probably a class message send
4019 // missing the initial '['. In this case, we won't consider this to be
4020 // the start of a declaration.
4021 if (DisambiguatingWithExpression &&
4022 isStartOfObjCClassMessageMissingOpenBracket())
4025 return isDeclarationSpecifier();
4027 case tok::coloncolon: // ::foo::bar
4028 if (NextToken().is(tok::kw_new) || // ::new
4029 NextToken().is(tok::kw_delete)) // ::delete
4032 // Annotate typenames and C++ scope specifiers. If we get one, just
4033 // recurse to handle whatever we get.
4034 if (TryAnnotateTypeOrScopeToken())
4036 return isDeclarationSpecifier();
4038 // storage-class-specifier
4039 case tok::kw_typedef:
4040 case tok::kw_extern:
4041 case tok::kw___private_extern__:
4042 case tok::kw_static:
4044 case tok::kw_register:
4045 case tok::kw___thread:
4046 case tok::kw_thread_local:
4047 case tok::kw__Thread_local:
4050 case tok::kw___module_private__:
4053 case tok::kw___unknown_anytype:
4058 case tok::kw___int64:
4059 case tok::kw___int128:
4060 case tok::kw_signed:
4061 case tok::kw_unsigned:
4062 case tok::kw__Complex:
4063 case tok::kw__Imaginary:
4066 case tok::kw_wchar_t:
4067 case tok::kw_char16_t:
4068 case tok::kw_char32_t:
4073 case tok::kw_double:
4076 case tok::kw__Decimal32:
4077 case tok::kw__Decimal64:
4078 case tok::kw__Decimal128:
4079 case tok::kw___vector:
4081 // OpenCL specific types:
4082 case tok::kw_image1d_t:
4083 case tok::kw_image1d_array_t:
4084 case tok::kw_image1d_buffer_t:
4085 case tok::kw_image2d_t:
4086 case tok::kw_image2d_array_t:
4087 case tok::kw_image3d_t:
4088 case tok::kw_sampler_t:
4089 case tok::kw_event_t:
4091 // struct-or-union-specifier (C99) or class-specifier (C++)
4093 case tok::kw_struct:
4095 case tok::kw___interface:
4101 case tok::kw_volatile:
4102 case tok::kw_restrict:
4104 // function-specifier
4105 case tok::kw_inline:
4106 case tok::kw_virtual:
4107 case tok::kw_explicit:
4108 case tok::kw__Noreturn:
4110 // alignment-specifier
4111 case tok::kw__Alignas:
4114 case tok::kw_friend:
4116 // static_assert-declaration
4117 case tok::kw__Static_assert:
4119 // GNU typeof support.
4120 case tok::kw_typeof:
4123 case tok::kw___attribute:
4125 // C++11 decltype and constexpr.
4126 case tok::annot_decltype:
4127 case tok::kw_constexpr:
4130 case tok::kw__Atomic:
4133 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4135 return getLangOpts().ObjC1;
4138 case tok::annot_typename:
4139 return !DisambiguatingWithExpression ||
4140 !isStartOfObjCClassMessageMissingOpenBracket();
4142 case tok::kw___declspec:
4143 case tok::kw___cdecl:
4144 case tok::kw___stdcall:
4145 case tok::kw___fastcall:
4146 case tok::kw___thiscall:
4148 case tok::kw___ptr64:
4149 case tok::kw___ptr32:
4150 case tok::kw___forceinline:
4151 case tok::kw___pascal:
4152 case tok::kw___unaligned:
4154 case tok::kw___private:
4155 case tok::kw___local:
4156 case tok::kw___global:
4157 case tok::kw___constant:
4158 case tok::kw___read_only:
4159 case tok::kw___read_write:
4160 case tok::kw___write_only:
4166 bool Parser::isConstructorDeclarator() {
4167 TentativeParsingAction TPA(*this);
4169 // Parse the C++ scope specifier.
4171 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4172 /*EnteringContext=*/true)) {
4177 // Parse the constructor name.
4178 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
4179 // We already know that we have a constructor name; just consume
4187 // Current class name must be followed by a left parenthesis.
4188 if (Tok.isNot(tok::l_paren)) {
4194 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4195 // that we have a constructor.
4196 if (Tok.is(tok::r_paren) ||
4197 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4202 // If we need to, enter the specified scope.
4203 DeclaratorScopeObj DeclScopeObj(*this, SS);
4204 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4205 DeclScopeObj.EnterDeclaratorScope();
4207 // Optionally skip Microsoft attributes.
4208 ParsedAttributes Attrs(AttrFactory);
4209 MaybeParseMicrosoftAttributes(Attrs);
4211 // Check whether the next token(s) are part of a declaration
4212 // specifier, in which case we have the start of a parameter and,
4213 // therefore, we know that this is a constructor.
4214 bool IsConstructor = false;
4215 if (isDeclarationSpecifier())
4216 IsConstructor = true;
4217 else if (Tok.is(tok::identifier) ||
4218 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4219 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4220 // This might be a parenthesized member name, but is more likely to
4221 // be a constructor declaration with an invalid argument type. Keep
4223 if (Tok.is(tok::annot_cxxscope))
4227 // If this is not a constructor, we must be parsing a declarator,
4228 // which must have one of the following syntactic forms (see the
4229 // grammar extract at the start of ParseDirectDeclarator):
4230 switch (Tok.getKind()) {
4235 // C(X [ [attribute]]);
4236 case tok::coloncolon:
4241 // Assume this isn't a constructor, rather than assuming it's a
4242 // constructor with an unnamed parameter of an ill-formed type.
4246 IsConstructor = true;
4252 return IsConstructor;
4255 /// ParseTypeQualifierListOpt
4256 /// type-qualifier-list: [C99 6.7.5]
4258 /// [vendor] attributes
4259 /// [ only if VendorAttributesAllowed=true ]
4260 /// type-qualifier-list type-qualifier
4261 /// [vendor] type-qualifier-list attributes
4262 /// [ only if VendorAttributesAllowed=true ]
4263 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4264 /// [ only if CXX11AttributesAllowed=true ]
4265 /// Note: vendor can be GNU, MS, etc.
4267 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
4268 bool VendorAttributesAllowed,
4269 bool CXX11AttributesAllowed,
4270 bool AtomicAllowed) {
4271 if (getLangOpts().CPlusPlus11 && CXX11AttributesAllowed &&
4272 isCXX11AttributeSpecifier()) {
4273 ParsedAttributesWithRange attrs(AttrFactory);
4274 ParseCXX11Attributes(attrs);
4275 DS.takeAttributesFrom(attrs);
4278 SourceLocation EndLoc;
4281 bool isInvalid = false;
4282 const char *PrevSpec = 0;
4283 unsigned DiagID = 0;
4284 SourceLocation Loc = Tok.getLocation();
4286 switch (Tok.getKind()) {
4287 case tok::code_completion:
4288 Actions.CodeCompleteTypeQualifiers(DS);
4289 return cutOffParsing();
4292 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4295 case tok::kw_volatile:
4296 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4299 case tok::kw_restrict:
4300 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4303 case tok::kw__Atomic:
4305 goto DoneWithTypeQuals;
4306 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4310 // OpenCL qualifiers:
4311 case tok::kw_private:
4312 if (!getLangOpts().OpenCL)
4313 goto DoneWithTypeQuals;
4314 case tok::kw___private:
4315 case tok::kw___global:
4316 case tok::kw___local:
4317 case tok::kw___constant:
4318 case tok::kw___read_only:
4319 case tok::kw___write_only:
4320 case tok::kw___read_write:
4321 ParseOpenCLQualifiers(DS);
4325 case tok::kw___ptr64:
4326 case tok::kw___ptr32:
4327 case tok::kw___cdecl:
4328 case tok::kw___stdcall:
4329 case tok::kw___fastcall:
4330 case tok::kw___thiscall:
4331 case tok::kw___unaligned:
4332 if (VendorAttributesAllowed) {
4333 ParseMicrosoftTypeAttributes(DS.getAttributes());
4336 goto DoneWithTypeQuals;
4337 case tok::kw___pascal:
4338 if (VendorAttributesAllowed) {
4339 ParseBorlandTypeAttributes(DS.getAttributes());
4342 goto DoneWithTypeQuals;
4343 case tok::kw___attribute:
4344 if (VendorAttributesAllowed) {
4345 ParseGNUAttributes(DS.getAttributes());
4346 continue; // do *not* consume the next token!
4348 // otherwise, FALL THROUGH!
4351 // If this is not a type-qualifier token, we're done reading type
4352 // qualifiers. First verify that DeclSpec's are consistent.
4353 DS.Finish(Diags, PP);
4354 if (EndLoc.isValid())
4355 DS.SetRangeEnd(EndLoc);
4359 // If the specifier combination wasn't legal, issue a diagnostic.
4361 assert(PrevSpec && "Method did not return previous specifier!");
4362 Diag(Tok, DiagID) << PrevSpec;
4364 EndLoc = ConsumeToken();
4369 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4371 void Parser::ParseDeclarator(Declarator &D) {
4372 /// This implements the 'declarator' production in the C grammar, then checks
4373 /// for well-formedness and issues diagnostics.
4374 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4377 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
4378 if (Kind == tok::star || Kind == tok::caret)
4381 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4382 if (!Lang.CPlusPlus)
4385 return Kind == tok::amp || Kind == tok::ampamp;
4388 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4389 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4390 /// isn't parsed at all, making this function effectively parse the C++
4391 /// ptr-operator production.
4393 /// If the grammar of this construct is extended, matching changes must also be
4394 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4395 /// isConstructorDeclarator.
4397 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4398 /// [C] pointer[opt] direct-declarator
4399 /// [C++] direct-declarator
4400 /// [C++] ptr-operator declarator
4402 /// pointer: [C99 6.7.5]
4403 /// '*' type-qualifier-list[opt]
4404 /// '*' type-qualifier-list[opt] pointer
4407 /// '*' cv-qualifier-seq[opt]
4410 /// [GNU] '&' restrict[opt] attributes[opt]
4411 /// [GNU?] '&&' restrict[opt] attributes[opt]
4412 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4413 void Parser::ParseDeclaratorInternal(Declarator &D,
4414 DirectDeclParseFunction DirectDeclParser) {
4415 if (Diags.hasAllExtensionsSilenced())
4418 // C++ member pointers start with a '::' or a nested-name.
4419 // Member pointers get special handling, since there's no place for the
4420 // scope spec in the generic path below.
4421 if (getLangOpts().CPlusPlus &&
4422 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
4423 Tok.is(tok::annot_cxxscope))) {
4424 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4425 D.getContext() == Declarator::MemberContext;
4427 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4429 if (SS.isNotEmpty()) {
4430 if (Tok.isNot(tok::star)) {
4431 // The scope spec really belongs to the direct-declarator.
4432 if (D.mayHaveIdentifier())
4433 D.getCXXScopeSpec() = SS;
4435 AnnotateScopeToken(SS, true);
4437 if (DirectDeclParser)
4438 (this->*DirectDeclParser)(D);
4442 SourceLocation Loc = ConsumeToken();
4444 DeclSpec DS(AttrFactory);
4445 ParseTypeQualifierListOpt(DS);
4446 D.ExtendWithDeclSpec(DS);
4448 // Recurse to parse whatever is left.
4449 ParseDeclaratorInternal(D, DirectDeclParser);
4451 // Sema will have to catch (syntactically invalid) pointers into global
4452 // scope. It has to catch pointers into namespace scope anyway.
4453 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4456 /* Don't replace range end. */SourceLocation());
4461 tok::TokenKind Kind = Tok.getKind();
4462 // Not a pointer, C++ reference, or block.
4463 if (!isPtrOperatorToken(Kind, getLangOpts())) {
4464 if (DirectDeclParser)
4465 (this->*DirectDeclParser)(D);
4469 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4470 // '&&' -> rvalue reference
4471 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4474 if (Kind == tok::star || Kind == tok::caret) {
4476 DeclSpec DS(AttrFactory);
4478 // FIXME: GNU attributes are not allowed here in a new-type-id.
4479 ParseTypeQualifierListOpt(DS);
4480 D.ExtendWithDeclSpec(DS);
4482 // Recursively parse the declarator.
4483 ParseDeclaratorInternal(D, DirectDeclParser);
4484 if (Kind == tok::star)
4485 // Remember that we parsed a pointer type, and remember the type-quals.
4486 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4487 DS.getConstSpecLoc(),
4488 DS.getVolatileSpecLoc(),
4489 DS.getRestrictSpecLoc()),
4493 // Remember that we parsed a Block type, and remember the type-quals.
4494 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4500 DeclSpec DS(AttrFactory);
4502 // Complain about rvalue references in C++03, but then go on and build
4504 if (Kind == tok::ampamp)
4505 Diag(Loc, getLangOpts().CPlusPlus11 ?
4506 diag::warn_cxx98_compat_rvalue_reference :
4507 diag::ext_rvalue_reference);
4509 // GNU-style and C++11 attributes are allowed here, as is restrict.
4510 ParseTypeQualifierListOpt(DS);
4511 D.ExtendWithDeclSpec(DS);
4513 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4514 // cv-qualifiers are introduced through the use of a typedef or of a
4515 // template type argument, in which case the cv-qualifiers are ignored.
4516 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4517 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4518 Diag(DS.getConstSpecLoc(),
4519 diag::err_invalid_reference_qualifier_application) << "const";
4520 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4521 Diag(DS.getVolatileSpecLoc(),
4522 diag::err_invalid_reference_qualifier_application) << "volatile";
4523 // 'restrict' is permitted as an extension.
4524 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4525 Diag(DS.getAtomicSpecLoc(),
4526 diag::err_invalid_reference_qualifier_application) << "_Atomic";
4529 // Recursively parse the declarator.
4530 ParseDeclaratorInternal(D, DirectDeclParser);
4532 if (D.getNumTypeObjects() > 0) {
4533 // C++ [dcl.ref]p4: There shall be no references to references.
4534 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
4535 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
4536 if (const IdentifierInfo *II = D.getIdentifier())
4537 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4540 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
4543 // Once we've complained about the reference-to-reference, we
4544 // can go ahead and build the (technically ill-formed)
4545 // declarator: reference collapsing will take care of it.
4549 // Remember that we parsed a reference type.
4550 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
4557 static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
4558 SourceLocation EllipsisLoc) {
4559 if (EllipsisLoc.isValid()) {
4560 FixItHint Insertion;
4561 if (!D.getEllipsisLoc().isValid()) {
4562 Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
4563 D.setEllipsisLoc(EllipsisLoc);
4565 P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
4566 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
4570 /// ParseDirectDeclarator
4571 /// direct-declarator: [C99 6.7.5]
4572 /// [C99] identifier
4573 /// '(' declarator ')'
4574 /// [GNU] '(' attributes declarator ')'
4575 /// [C90] direct-declarator '[' constant-expression[opt] ']'
4576 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4577 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4578 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4579 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
4580 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
4581 /// attribute-specifier-seq[opt]
4582 /// direct-declarator '(' parameter-type-list ')'
4583 /// direct-declarator '(' identifier-list[opt] ')'
4584 /// [GNU] direct-declarator '(' parameter-forward-declarations
4585 /// parameter-type-list[opt] ')'
4586 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
4587 /// cv-qualifier-seq[opt] exception-specification[opt]
4588 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
4589 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
4590 /// ref-qualifier[opt] exception-specification[opt]
4591 /// [C++] declarator-id
4592 /// [C++11] declarator-id attribute-specifier-seq[opt]
4594 /// declarator-id: [C++ 8]
4595 /// '...'[opt] id-expression
4596 /// '::'[opt] nested-name-specifier[opt] type-name
4598 /// id-expression: [C++ 5.1]
4602 /// unqualified-id: [C++ 5.1]
4604 /// operator-function-id
4605 /// conversion-function-id
4609 /// Note, any additional constructs added here may need corresponding changes
4610 /// in isConstructorDeclarator.
4611 void Parser::ParseDirectDeclarator(Declarator &D) {
4612 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
4614 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
4615 // ParseDeclaratorInternal might already have parsed the scope.
4616 if (D.getCXXScopeSpec().isEmpty()) {
4617 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4618 D.getContext() == Declarator::MemberContext;
4619 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
4623 if (D.getCXXScopeSpec().isValid()) {
4624 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4625 // Change the declaration context for name lookup, until this function
4626 // is exited (and the declarator has been parsed).
4627 DeclScopeObj.EnterDeclaratorScope();
4630 // C++0x [dcl.fct]p14:
4631 // There is a syntactic ambiguity when an ellipsis occurs at the end
4632 // of a parameter-declaration-clause without a preceding comma. In
4633 // this case, the ellipsis is parsed as part of the
4634 // abstract-declarator if the type of the parameter names a template
4635 // parameter pack that has not been expanded; otherwise, it is parsed
4636 // as part of the parameter-declaration-clause.
4637 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
4638 !((D.getContext() == Declarator::PrototypeContext ||
4639 D.getContext() == Declarator::BlockLiteralContext) &&
4640 NextToken().is(tok::r_paren) &&
4641 !D.hasGroupingParens() &&
4642 !Actions.containsUnexpandedParameterPacks(D))) {
4643 SourceLocation EllipsisLoc = ConsumeToken();
4644 if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
4645 // The ellipsis was put in the wrong place. Recover, and explain to
4646 // the user what they should have done.
4648 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4651 D.setEllipsisLoc(EllipsisLoc);
4653 // The ellipsis can't be followed by a parenthesized declarator. We
4654 // check for that in ParseParenDeclarator, after we have disambiguated
4655 // the l_paren token.
4658 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
4659 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
4660 // We found something that indicates the start of an unqualified-id.
4661 // Parse that unqualified-id.
4662 bool AllowConstructorName;
4663 if (D.getDeclSpec().hasTypeSpecifier())
4664 AllowConstructorName = false;
4665 else if (D.getCXXScopeSpec().isSet())
4666 AllowConstructorName =
4667 (D.getContext() == Declarator::FileContext ||
4668 D.getContext() == Declarator::MemberContext);
4670 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
4672 SourceLocation TemplateKWLoc;
4673 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
4674 /*EnteringContext=*/true,
4675 /*AllowDestructorName=*/true,
4676 AllowConstructorName,
4680 // Once we're past the identifier, if the scope was bad, mark the
4681 // whole declarator bad.
4682 D.getCXXScopeSpec().isInvalid()) {
4683 D.SetIdentifier(0, Tok.getLocation());
4684 D.setInvalidType(true);
4686 // Parsed the unqualified-id; update range information and move along.
4687 if (D.getSourceRange().getBegin().isInvalid())
4688 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
4689 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
4691 goto PastIdentifier;
4693 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
4694 assert(!getLangOpts().CPlusPlus &&
4695 "There's a C++-specific check for tok::identifier above");
4696 assert(Tok.getIdentifierInfo() && "Not an identifier?");
4697 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
4699 goto PastIdentifier;
4702 if (Tok.is(tok::l_paren)) {
4703 // direct-declarator: '(' declarator ')'
4704 // direct-declarator: '(' attributes declarator ')'
4705 // Example: 'char (*X)' or 'int (*XX)(void)'
4706 ParseParenDeclarator(D);
4708 // If the declarator was parenthesized, we entered the declarator
4709 // scope when parsing the parenthesized declarator, then exited
4710 // the scope already. Re-enter the scope, if we need to.
4711 if (D.getCXXScopeSpec().isSet()) {
4712 // If there was an error parsing parenthesized declarator, declarator
4713 // scope may have been entered before. Don't do it again.
4714 if (!D.isInvalidType() &&
4715 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
4716 // Change the declaration context for name lookup, until this function
4717 // is exited (and the declarator has been parsed).
4718 DeclScopeObj.EnterDeclaratorScope();
4720 } else if (D.mayOmitIdentifier()) {
4721 // This could be something simple like "int" (in which case the declarator
4722 // portion is empty), if an abstract-declarator is allowed.
4723 D.SetIdentifier(0, Tok.getLocation());
4725 // The grammar for abstract-pack-declarator does not allow grouping parens.
4726 // FIXME: Revisit this once core issue 1488 is resolved.
4727 if (D.hasEllipsis() && D.hasGroupingParens())
4728 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
4729 diag::ext_abstract_pack_declarator_parens);
4731 if (Tok.getKind() == tok::annot_pragma_parser_crash)
4733 if (D.getContext() == Declarator::MemberContext)
4734 Diag(Tok, diag::err_expected_member_name_or_semi)
4735 << D.getDeclSpec().getSourceRange();
4736 else if (getLangOpts().CPlusPlus) {
4737 if (Tok.is(tok::period) || Tok.is(tok::arrow))
4738 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
4740 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
4742 Diag(Tok, diag::err_expected_ident_lparen);
4743 D.SetIdentifier(0, Tok.getLocation());
4744 D.setInvalidType(true);
4748 assert(D.isPastIdentifier() &&
4749 "Haven't past the location of the identifier yet?");
4751 // Don't parse attributes unless we have parsed an unparenthesized name.
4752 if (D.hasName() && !D.getNumTypeObjects())
4753 MaybeParseCXX11Attributes(D);
4756 if (Tok.is(tok::l_paren)) {
4757 // Enter function-declaration scope, limiting any declarators to the
4758 // function prototype scope, including parameter declarators.
4759 ParseScope PrototypeScope(this,
4760 Scope::FunctionPrototypeScope|Scope::DeclScope|
4761 (D.isFunctionDeclaratorAFunctionDeclaration()
4762 ? Scope::FunctionDeclarationScope : 0));
4764 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
4765 // In such a case, check if we actually have a function declarator; if it
4766 // is not, the declarator has been fully parsed.
4767 bool IsAmbiguous = false;
4768 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
4769 // The name of the declarator, if any, is tentatively declared within
4770 // a possible direct initializer.
4771 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
4772 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
4773 TentativelyDeclaredIdentifiers.pop_back();
4774 if (!IsFunctionDecl)
4777 ParsedAttributes attrs(AttrFactory);
4778 BalancedDelimiterTracker T(*this, tok::l_paren);
4780 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
4781 PrototypeScope.Exit();
4782 } else if (Tok.is(tok::l_square)) {
4783 ParseBracketDeclarator(D);
4790 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
4791 /// only called before the identifier, so these are most likely just grouping
4792 /// parens for precedence. If we find that these are actually function
4793 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
4795 /// direct-declarator:
4796 /// '(' declarator ')'
4797 /// [GNU] '(' attributes declarator ')'
4798 /// direct-declarator '(' parameter-type-list ')'
4799 /// direct-declarator '(' identifier-list[opt] ')'
4800 /// [GNU] direct-declarator '(' parameter-forward-declarations
4801 /// parameter-type-list[opt] ')'
4803 void Parser::ParseParenDeclarator(Declarator &D) {
4804 BalancedDelimiterTracker T(*this, tok::l_paren);
4807 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
4809 // Eat any attributes before we look at whether this is a grouping or function
4810 // declarator paren. If this is a grouping paren, the attribute applies to
4811 // the type being built up, for example:
4812 // int (__attribute__(()) *x)(long y)
4813 // If this ends up not being a grouping paren, the attribute applies to the
4814 // first argument, for example:
4815 // int (__attribute__(()) int x)
4816 // In either case, we need to eat any attributes to be able to determine what
4817 // sort of paren this is.
4819 ParsedAttributes attrs(AttrFactory);
4820 bool RequiresArg = false;
4821 if (Tok.is(tok::kw___attribute)) {
4822 ParseGNUAttributes(attrs);
4824 // We require that the argument list (if this is a non-grouping paren) be
4825 // present even if the attribute list was empty.
4829 // Eat any Microsoft extensions.
4830 ParseMicrosoftTypeAttributes(attrs);
4832 // Eat any Borland extensions.
4833 if (Tok.is(tok::kw___pascal))
4834 ParseBorlandTypeAttributes(attrs);
4836 // If we haven't past the identifier yet (or where the identifier would be
4837 // stored, if this is an abstract declarator), then this is probably just
4838 // grouping parens. However, if this could be an abstract-declarator, then
4839 // this could also be the start of function arguments (consider 'void()').
4842 if (!D.mayOmitIdentifier()) {
4843 // If this can't be an abstract-declarator, this *must* be a grouping
4844 // paren, because we haven't seen the identifier yet.
4846 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
4847 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
4848 NextToken().is(tok::r_paren)) || // C++ int(...)
4849 isDeclarationSpecifier() || // 'int(int)' is a function.
4850 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
4851 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
4852 // considered to be a type, not a K&R identifier-list.
4855 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
4859 // If this is a grouping paren, handle:
4860 // direct-declarator: '(' declarator ')'
4861 // direct-declarator: '(' attributes declarator ')'
4863 SourceLocation EllipsisLoc = D.getEllipsisLoc();
4864 D.setEllipsisLoc(SourceLocation());
4866 bool hadGroupingParens = D.hasGroupingParens();
4867 D.setGroupingParens(true);
4868 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4871 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
4872 T.getCloseLocation()),
4873 attrs, T.getCloseLocation());
4875 D.setGroupingParens(hadGroupingParens);
4877 // An ellipsis cannot be placed outside parentheses.
4878 if (EllipsisLoc.isValid())
4879 diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
4884 // Okay, if this wasn't a grouping paren, it must be the start of a function
4885 // argument list. Recognize that this declarator will never have an
4886 // identifier (and remember where it would have been), then call into
4887 // ParseFunctionDeclarator to handle of argument list.
4888 D.SetIdentifier(0, Tok.getLocation());
4890 // Enter function-declaration scope, limiting any declarators to the
4891 // function prototype scope, including parameter declarators.
4892 ParseScope PrototypeScope(this,
4893 Scope::FunctionPrototypeScope | Scope::DeclScope |
4894 (D.isFunctionDeclaratorAFunctionDeclaration()
4895 ? Scope::FunctionDeclarationScope : 0));
4896 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
4897 PrototypeScope.Exit();
4900 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
4901 /// declarator D up to a paren, which indicates that we are parsing function
4904 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
4905 /// immediately after the open paren - they should be considered to be the
4906 /// first argument of a parameter.
4908 /// If RequiresArg is true, then the first argument of the function is required
4909 /// to be present and required to not be an identifier list.
4911 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
4912 /// (C++11) ref-qualifier[opt], exception-specification[opt],
4913 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
4915 /// [C++11] exception-specification:
4916 /// dynamic-exception-specification
4917 /// noexcept-specification
4919 void Parser::ParseFunctionDeclarator(Declarator &D,
4920 ParsedAttributes &FirstArgAttrs,
4921 BalancedDelimiterTracker &Tracker,
4924 assert(getCurScope()->isFunctionPrototypeScope() &&
4925 "Should call from a Function scope");
4926 // lparen is already consumed!
4927 assert(D.isPastIdentifier() && "Should not call before identifier!");
4929 // This should be true when the function has typed arguments.
4930 // Otherwise, it is treated as a K&R-style function.
4931 bool HasProto = false;
4932 // Build up an array of information about the parsed arguments.
4933 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
4934 // Remember where we see an ellipsis, if any.
4935 SourceLocation EllipsisLoc;
4937 DeclSpec DS(AttrFactory);
4938 bool RefQualifierIsLValueRef = true;
4939 SourceLocation RefQualifierLoc;
4940 SourceLocation ConstQualifierLoc;
4941 SourceLocation VolatileQualifierLoc;
4942 ExceptionSpecificationType ESpecType = EST_None;
4943 SourceRange ESpecRange;
4944 SmallVector<ParsedType, 2> DynamicExceptions;
4945 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4946 ExprResult NoexceptExpr;
4947 ParsedAttributes FnAttrs(AttrFactory);
4948 TypeResult TrailingReturnType;
4950 Actions.ActOnStartFunctionDeclarator();
4952 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
4953 EndLoc is the end location for the function declarator.
4954 They differ for trailing return types. */
4955 SourceLocation StartLoc, LocalEndLoc, EndLoc;
4956 SourceLocation LParenLoc, RParenLoc;
4957 LParenLoc = Tracker.getOpenLocation();
4958 StartLoc = LParenLoc;
4960 if (isFunctionDeclaratorIdentifierList()) {
4962 Diag(Tok, diag::err_argument_required_after_attribute);
4964 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
4966 Tracker.consumeClose();
4967 RParenLoc = Tracker.getCloseLocation();
4968 LocalEndLoc = RParenLoc;
4971 if (Tok.isNot(tok::r_paren))
4972 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
4973 else if (RequiresArg)
4974 Diag(Tok, diag::err_argument_required_after_attribute);
4976 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
4978 // If we have the closing ')', eat it.
4979 Tracker.consumeClose();
4980 RParenLoc = Tracker.getCloseLocation();
4981 LocalEndLoc = RParenLoc;
4984 if (getLangOpts().CPlusPlus) {
4985 // FIXME: Accept these components in any order, and produce fixits to
4986 // correct the order if the user gets it wrong. Ideally we should deal
4987 // with the virt-specifier-seq and pure-specifier in the same way.
4989 // Parse cv-qualifier-seq[opt].
4990 ParseTypeQualifierListOpt(DS, /*VendorAttributesAllowed*/ false,
4991 /*CXX11AttributesAllowed*/ false,
4992 /*AtomicAllowed*/ false);
4993 if (!DS.getSourceRange().getEnd().isInvalid()) {
4994 EndLoc = DS.getSourceRange().getEnd();
4995 ConstQualifierLoc = DS.getConstSpecLoc();
4996 VolatileQualifierLoc = DS.getVolatileSpecLoc();
4999 // Parse ref-qualifier[opt].
5000 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
5001 Diag(Tok, getLangOpts().CPlusPlus11 ?
5002 diag::warn_cxx98_compat_ref_qualifier :
5003 diag::ext_ref_qualifier);
5005 RefQualifierIsLValueRef = Tok.is(tok::amp);
5006 RefQualifierLoc = ConsumeToken();
5007 EndLoc = RefQualifierLoc;
5010 // C++11 [expr.prim.general]p3:
5011 // If a declaration declares a member function or member function
5012 // template of a class X, the expression this is a prvalue of type
5013 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5014 // and the end of the function-definition, member-declarator, or
5016 // FIXME: currently, "static" case isn't handled correctly.
5017 bool IsCXX11MemberFunction =
5018 getLangOpts().CPlusPlus11 &&
5019 (D.getContext() == Declarator::MemberContext
5020 ? !D.getDeclSpec().isFriendSpecified()
5021 : D.getContext() == Declarator::FileContext &&
5022 D.getCXXScopeSpec().isValid() &&
5023 Actions.CurContext->isRecord());
5024 Sema::CXXThisScopeRAII ThisScope(Actions,
5025 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5026 DS.getTypeQualifiers() |
5027 (D.getDeclSpec().isConstexprSpecified() &&
5028 !getLangOpts().CPlusPlus1y
5029 ? Qualifiers::Const : 0),
5030 IsCXX11MemberFunction);
5032 // Parse exception-specification[opt].
5033 ESpecType = tryParseExceptionSpecification(ESpecRange,
5035 DynamicExceptionRanges,
5037 if (ESpecType != EST_None)
5038 EndLoc = ESpecRange.getEnd();
5040 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5041 // after the exception-specification.
5042 MaybeParseCXX11Attributes(FnAttrs);
5044 // Parse trailing-return-type[opt].
5045 LocalEndLoc = EndLoc;
5046 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5047 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5048 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5049 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5050 LocalEndLoc = Tok.getLocation();
5052 TrailingReturnType = ParseTrailingReturnType(Range);
5053 EndLoc = Range.getEnd();
5058 // Remember that we parsed a function type, and remember the attributes.
5059 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5062 ParamInfo.data(), ParamInfo.size(),
5063 EllipsisLoc, RParenLoc,
5064 DS.getTypeQualifiers(),
5065 RefQualifierIsLValueRef,
5066 RefQualifierLoc, ConstQualifierLoc,
5067 VolatileQualifierLoc,
5068 /*MutableLoc=*/SourceLocation(),
5069 ESpecType, ESpecRange.getBegin(),
5070 DynamicExceptions.data(),
5071 DynamicExceptionRanges.data(),
5072 DynamicExceptions.size(),
5073 NoexceptExpr.isUsable() ?
5074 NoexceptExpr.get() : 0,
5075 StartLoc, LocalEndLoc, D,
5076 TrailingReturnType),
5079 Actions.ActOnEndFunctionDeclarator();
5082 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5083 /// identifier list form for a K&R-style function: void foo(a,b,c)
5085 /// Note that identifier-lists are only allowed for normal declarators, not for
5086 /// abstract-declarators.
5087 bool Parser::isFunctionDeclaratorIdentifierList() {
5088 return !getLangOpts().CPlusPlus
5089 && Tok.is(tok::identifier)
5090 && !TryAltiVecVectorToken()
5091 // K&R identifier lists can't have typedefs as identifiers, per C99
5093 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5094 // Identifier lists follow a really simple grammar: the identifiers can
5095 // be followed *only* by a ", identifier" or ")". However, K&R
5096 // identifier lists are really rare in the brave new modern world, and
5097 // it is very common for someone to typo a type in a non-K&R style
5098 // list. If we are presented with something like: "void foo(intptr x,
5099 // float y)", we don't want to start parsing the function declarator as
5100 // though it is a K&R style declarator just because intptr is an
5103 // To handle this, we check to see if the token after the first
5104 // identifier is a "," or ")". Only then do we parse it as an
5106 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5109 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5110 /// we found a K&R-style identifier list instead of a typed parameter list.
5112 /// After returning, ParamInfo will hold the parsed parameters.
5114 /// identifier-list: [C99 6.7.5]
5116 /// identifier-list ',' identifier
5118 void Parser::ParseFunctionDeclaratorIdentifierList(
5120 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
5121 // If there was no identifier specified for the declarator, either we are in
5122 // an abstract-declarator, or we are in a parameter declarator which was found
5123 // to be abstract. In abstract-declarators, identifier lists are not valid:
5125 if (!D.getIdentifier())
5126 Diag(Tok, diag::ext_ident_list_in_param);
5128 // Maintain an efficient lookup of params we have seen so far.
5129 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5132 // If this isn't an identifier, report the error and skip until ')'.
5133 if (Tok.isNot(tok::identifier)) {
5134 Diag(Tok, diag::err_expected_ident);
5135 SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
5136 // Forget we parsed anything.
5141 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5143 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5144 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5145 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5147 // Verify that the argument identifier has not already been mentioned.
5148 if (!ParamsSoFar.insert(ParmII)) {
5149 Diag(Tok, diag::err_param_redefinition) << ParmII;
5151 // Remember this identifier in ParamInfo.
5152 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5157 // Eat the identifier.
5160 // The list continues if we see a comma.
5161 if (Tok.isNot(tok::comma))
5167 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5168 /// after the opening parenthesis. This function will not parse a K&R-style
5169 /// identifier list.
5171 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5172 /// caller parsed those arguments immediately after the open paren - they should
5173 /// be considered to be part of the first parameter.
5175 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5176 /// be the location of the ellipsis, if any was parsed.
5178 /// parameter-type-list: [C99 6.7.5]
5180 /// parameter-list ',' '...'
5181 /// [C++] parameter-list '...'
5183 /// parameter-list: [C99 6.7.5]
5184 /// parameter-declaration
5185 /// parameter-list ',' parameter-declaration
5187 /// parameter-declaration: [C99 6.7.5]
5188 /// declaration-specifiers declarator
5189 /// [C++] declaration-specifiers declarator '=' assignment-expression
5190 /// [C++11] initializer-clause
5191 /// [GNU] declaration-specifiers declarator attributes
5192 /// declaration-specifiers abstract-declarator[opt]
5193 /// [C++] declaration-specifiers abstract-declarator[opt]
5194 /// '=' assignment-expression
5195 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5196 /// [C++11] attribute-specifier-seq parameter-declaration
5198 void Parser::ParseParameterDeclarationClause(
5200 ParsedAttributes &FirstArgAttrs,
5201 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
5202 SourceLocation &EllipsisLoc) {
5205 if (Tok.is(tok::ellipsis)) {
5206 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5207 // before deciding this was a parameter-declaration-clause.
5208 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
5212 // Parse the declaration-specifiers.
5213 // Just use the ParsingDeclaration "scope" of the declarator.
5214 DeclSpec DS(AttrFactory);
5216 // Parse any C++11 attributes.
5217 MaybeParseCXX11Attributes(DS.getAttributes());
5219 // Skip any Microsoft attributes before a param.
5220 MaybeParseMicrosoftAttributes(DS.getAttributes());
5222 SourceLocation DSStart = Tok.getLocation();
5224 // If the caller parsed attributes for the first argument, add them now.
5225 // Take them so that we only apply the attributes to the first parameter.
5226 // FIXME: If we can leave the attributes in the token stream somehow, we can
5227 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5229 DS.takeAttributesFrom(FirstArgAttrs);
5231 ParseDeclarationSpecifiers(DS);
5233 // Parse the declarator. This is "PrototypeContext", because we must
5234 // accept either 'declarator' or 'abstract-declarator' here.
5235 Declarator ParmDecl(DS, Declarator::PrototypeContext);
5236 ParseDeclarator(ParmDecl);
5238 // Parse GNU attributes, if present.
5239 MaybeParseGNUAttributes(ParmDecl);
5241 // Remember this parsed parameter in ParamInfo.
5242 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
5244 // DefArgToks is used when the parsing of default arguments needs
5246 CachedTokens *DefArgToks = 0;
5248 // If no parameter was specified, verify that *something* was specified,
5249 // otherwise we have a missing type and identifier.
5250 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
5251 ParmDecl.getNumTypeObjects() == 0) {
5252 // Completely missing, emit error.
5253 Diag(DSStart, diag::err_missing_param);
5255 // Otherwise, we have something. Add it and let semantic analysis try
5256 // to grok it and add the result to the ParamInfo we are building.
5258 // Inform the actions module about the parameter declarator, so it gets
5259 // added to the current scope.
5260 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
5262 // Parse the default argument, if any. We parse the default
5263 // arguments in all dialects; the semantic analysis in
5264 // ActOnParamDefaultArgument will reject the default argument in
5266 if (Tok.is(tok::equal)) {
5267 SourceLocation EqualLoc = Tok.getLocation();
5269 // Parse the default argument
5270 if (D.getContext() == Declarator::MemberContext) {
5271 // If we're inside a class definition, cache the tokens
5272 // corresponding to the default argument. We'll actually parse
5273 // them when we see the end of the class definition.
5274 // FIXME: Can we use a smart pointer for Toks?
5275 DefArgToks = new CachedTokens;
5277 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
5278 /*StopAtSemi=*/true,
5279 /*ConsumeFinalToken=*/false)) {
5282 Actions.ActOnParamDefaultArgumentError(Param);
5284 // Mark the end of the default argument so that we know when to
5285 // stop when we parse it later on.
5287 DefArgEnd.startToken();
5288 DefArgEnd.setKind(tok::cxx_defaultarg_end);
5289 DefArgEnd.setLocation(Tok.getLocation());
5290 DefArgToks->push_back(DefArgEnd);
5291 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5292 (*DefArgToks)[1].getLocation());
5298 // The argument isn't actually potentially evaluated unless it is
5300 EnterExpressionEvaluationContext Eval(Actions,
5301 Sema::PotentiallyEvaluatedIfUsed,
5304 ExprResult DefArgResult;
5305 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5306 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5307 DefArgResult = ParseBraceInitializer();
5309 DefArgResult = ParseAssignmentExpression();
5310 if (DefArgResult.isInvalid()) {
5311 Actions.ActOnParamDefaultArgumentError(Param);
5312 SkipUntil(tok::comma, tok::r_paren, true, true);
5314 // Inform the actions module about the default argument
5315 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5316 DefArgResult.take());
5321 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5322 ParmDecl.getIdentifierLoc(), Param,
5326 // If the next token is a comma, consume it and keep reading arguments.
5327 if (Tok.isNot(tok::comma)) {
5328 if (Tok.is(tok::ellipsis)) {
5329 EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
5331 if (!getLangOpts().CPlusPlus) {
5332 // We have ellipsis without a preceding ',', which is ill-formed
5333 // in C. Complain and provide the fix.
5334 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5335 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5342 // Consume the comma.
5348 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5349 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5350 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5351 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5352 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5353 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5354 /// attribute-specifier-seq[opt]
5355 void Parser::ParseBracketDeclarator(Declarator &D) {
5356 if (CheckProhibitedCXX11Attribute())
5359 BalancedDelimiterTracker T(*this, tok::l_square);
5362 // C array syntax has many features, but by-far the most common is [] and [4].
5363 // This code does a fast path to handle some of the most obvious cases.
5364 if (Tok.getKind() == tok::r_square) {
5366 ParsedAttributes attrs(AttrFactory);
5367 MaybeParseCXX11Attributes(attrs);
5369 // Remember that we parsed the empty array type.
5370 ExprResult NumElements;
5371 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
5372 T.getOpenLocation(),
5373 T.getCloseLocation()),
5374 attrs, T.getCloseLocation());
5376 } else if (Tok.getKind() == tok::numeric_constant &&
5377 GetLookAheadToken(1).is(tok::r_square)) {
5378 // [4] is very common. Parse the numeric constant expression.
5379 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5383 ParsedAttributes attrs(AttrFactory);
5384 MaybeParseCXX11Attributes(attrs);
5386 // Remember that we parsed a array type, and remember its features.
5387 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5389 T.getOpenLocation(),
5390 T.getCloseLocation()),
5391 attrs, T.getCloseLocation());
5395 // If valid, this location is the position where we read the 'static' keyword.
5396 SourceLocation StaticLoc;
5397 if (Tok.is(tok::kw_static))
5398 StaticLoc = ConsumeToken();
5400 // If there is a type-qualifier-list, read it now.
5401 // Type qualifiers in an array subscript are a C99 feature.
5402 DeclSpec DS(AttrFactory);
5403 ParseTypeQualifierListOpt(DS, false /*no attributes*/);
5405 // If we haven't already read 'static', check to see if there is one after the
5406 // type-qualifier-list.
5407 if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
5408 StaticLoc = ConsumeToken();
5410 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5411 bool isStar = false;
5412 ExprResult NumElements;
5414 // Handle the case where we have '[*]' as the array size. However, a leading
5415 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5416 // the token after the star is a ']'. Since stars in arrays are
5417 // infrequent, use of lookahead is not costly here.
5418 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5419 ConsumeToken(); // Eat the '*'.
5421 if (StaticLoc.isValid()) {
5422 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5423 StaticLoc = SourceLocation(); // Drop the static.
5426 } else if (Tok.isNot(tok::r_square)) {
5427 // Note, in C89, this production uses the constant-expr production instead
5428 // of assignment-expr. The only difference is that assignment-expr allows
5429 // things like '=' and '*='. Sema rejects these in C89 mode because they
5430 // are not i-c-e's, so we don't need to distinguish between the two here.
5432 // Parse the constant-expression or assignment-expression now (depending
5434 if (getLangOpts().CPlusPlus) {
5435 NumElements = ParseConstantExpression();
5437 EnterExpressionEvaluationContext Unevaluated(Actions,
5438 Sema::ConstantEvaluated);
5439 NumElements = ParseAssignmentExpression();
5443 // If there was an error parsing the assignment-expression, recover.
5444 if (NumElements.isInvalid()) {
5445 D.setInvalidType(true);
5446 // If the expression was invalid, skip it.
5447 SkipUntil(tok::r_square);
5453 ParsedAttributes attrs(AttrFactory);
5454 MaybeParseCXX11Attributes(attrs);
5456 // Remember that we parsed a array type, and remember its features.
5457 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
5458 StaticLoc.isValid(), isStar,
5459 NumElements.release(),
5460 T.getOpenLocation(),
5461 T.getCloseLocation()),
5462 attrs, T.getCloseLocation());
5465 /// [GNU] typeof-specifier:
5466 /// typeof ( expressions )
5467 /// typeof ( type-name )
5468 /// [GNU/C++] typeof unary-expression
5470 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
5471 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
5473 SourceLocation StartLoc = ConsumeToken();
5475 const bool hasParens = Tok.is(tok::l_paren);
5477 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
5478 Sema::ReuseLambdaContextDecl);
5482 SourceRange CastRange;
5483 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
5486 DS.setTypeofParensRange(CastRange);
5488 if (CastRange.getEnd().isInvalid())
5489 // FIXME: Not accurate, the range gets one token more than it should.
5490 DS.SetRangeEnd(Tok.getLocation());
5492 DS.SetRangeEnd(CastRange.getEnd());
5496 DS.SetTypeSpecError();
5500 const char *PrevSpec = 0;
5502 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5503 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
5505 Diag(StartLoc, DiagID) << PrevSpec;
5509 // If we get here, the operand to the typeof was an expresion.
5510 if (Operand.isInvalid()) {
5511 DS.SetTypeSpecError();
5515 // We might need to transform the operand if it is potentially evaluated.
5516 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
5517 if (Operand.isInvalid()) {
5518 DS.SetTypeSpecError();
5522 const char *PrevSpec = 0;
5524 // Check for duplicate type specifiers (e.g. "int typeof(int)").
5525 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
5526 DiagID, Operand.get()))
5527 Diag(StartLoc, DiagID) << PrevSpec;
5530 /// [C11] atomic-specifier:
5531 /// _Atomic ( type-name )
5533 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
5534 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
5535 "Not an atomic specifier");
5537 SourceLocation StartLoc = ConsumeToken();
5538 BalancedDelimiterTracker T(*this, tok::l_paren);
5539 if (T.consumeOpen())
5542 TypeResult Result = ParseTypeName();
5543 if (Result.isInvalid()) {
5544 SkipUntil(tok::r_paren);
5551 if (T.getCloseLocation().isInvalid())
5554 DS.setTypeofParensRange(T.getRange());
5555 DS.SetRangeEnd(T.getCloseLocation());
5557 const char *PrevSpec = 0;
5559 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
5560 DiagID, Result.release()))
5561 Diag(StartLoc, DiagID) << PrevSpec;
5565 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
5566 /// from TryAltiVecVectorToken.
5567 bool Parser::TryAltiVecVectorTokenOutOfLine() {
5568 Token Next = NextToken();
5569 switch (Next.getKind()) {
5570 default: return false;
5573 case tok::kw_signed:
5574 case tok::kw_unsigned:
5579 case tok::kw_double:
5581 case tok::kw___pixel:
5582 Tok.setKind(tok::kw___vector);
5584 case tok::identifier:
5585 if (Next.getIdentifierInfo() == Ident_pixel) {
5586 Tok.setKind(tok::kw___vector);
5593 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
5594 const char *&PrevSpec, unsigned &DiagID,
5596 if (Tok.getIdentifierInfo() == Ident_vector) {
5597 Token Next = NextToken();
5598 switch (Next.getKind()) {
5601 case tok::kw_signed:
5602 case tok::kw_unsigned:
5607 case tok::kw_double:
5609 case tok::kw___pixel:
5610 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5612 case tok::identifier:
5613 if (Next.getIdentifierInfo() == Ident_pixel) {
5614 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
5621 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
5622 DS.isTypeAltiVecVector()) {
5623 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);