1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
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/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/Attributes.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringSwitch.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
35 // C99 6.7: Declarations.
36 //===----------------------------------------------------------------------===//
39 /// type-name: [C99 6.7.6]
40 /// specifier-qualifier-list abstract-declarator[opt]
42 /// Called type-id in C++.
43 TypeResult Parser::ParseTypeName(SourceRange *Range,
44 Declarator::TheContext Context,
47 ParsedAttributes *Attrs) {
48 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49 if (DSC == DSC_normal)
50 DSC = DSC_type_specifier;
52 // Parse the common declaration-specifiers piece.
53 DeclSpec DS(AttrFactory);
55 DS.addAttributes(Attrs->getList());
56 ParseSpecifierQualifierList(DS, AS, DSC);
58 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
60 // Parse the abstract-declarator, if present.
61 Declarator DeclaratorInfo(DS, Context);
62 ParseDeclarator(DeclaratorInfo);
64 *Range = DeclaratorInfo.getSourceRange();
66 if (DeclaratorInfo.isInvalidType())
69 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
72 /// isAttributeLateParsed - Return true if the attribute has arguments that
73 /// require late parsing.
74 static bool isAttributeLateParsed(const IdentifierInfo &II) {
75 #define CLANG_ATTR_LATE_PARSED_LIST
76 return llvm::StringSwitch<bool>(II.getName())
77 #include "clang/Parse/AttrParserStringSwitches.inc"
79 #undef CLANG_ATTR_LATE_PARSED_LIST
82 /// ParseGNUAttributes - Parse a non-empty attributes list.
86 /// attributes attribute
89 /// '__attribute__' '(' '(' attribute-list ')' ')'
91 /// [GNU] attribute-list:
93 /// attribute_list ',' attrib
98 /// attrib-name '(' identifier ')'
99 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
100 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
102 /// [GNU] attrib-name:
108 /// Whether an attribute takes an 'identifier' is determined by the
109 /// attrib-name. GCC's behavior here is not worth imitating:
111 /// * In C mode, if the attribute argument list starts with an identifier
112 /// followed by a ',' or an ')', and the identifier doesn't resolve to
113 /// a type, it is parsed as an identifier. If the attribute actually
114 /// wanted an expression, it's out of luck (but it turns out that no
115 /// attributes work that way, because C constant expressions are very
117 /// * In C++ mode, if the attribute argument list starts with an identifier,
118 /// and the attribute *wants* an identifier, it is parsed as an identifier.
119 /// At block scope, any additional tokens between the identifier and the
120 /// ',' or ')' are ignored, otherwise they produce a parse error.
122 /// We follow the C++ model, but don't allow junk after the identifier.
123 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
124 SourceLocation *endLoc,
125 LateParsedAttrList *LateAttrs,
127 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
129 while (Tok.is(tok::kw___attribute)) {
131 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
133 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
136 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
137 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
140 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
142 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
143 if (TryConsumeToken(tok::comma))
146 // Expect an identifier or declaration specifier (const, int, etc.)
147 if (Tok.isAnnotation())
149 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
153 SourceLocation AttrNameLoc = ConsumeToken();
155 if (Tok.isNot(tok::l_paren)) {
156 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
157 AttributeList::AS_GNU);
161 // Handle "parameterized" attributes
162 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
163 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
164 SourceLocation(), AttributeList::AS_GNU, D);
168 // Handle attributes with arguments that require late parsing.
169 LateParsedAttribute *LA =
170 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
171 LateAttrs->push_back(LA);
173 // Attributes in a class are parsed at the end of the class, along
174 // with other late-parsed declarations.
175 if (!ClassStack.empty() && !LateAttrs->parseSoon())
176 getCurrentClass().LateParsedDeclarations.push_back(LA);
178 // consume everything up to and including the matching right parens
179 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
183 Eof.setLocation(Tok.getLocation());
184 LA->Toks.push_back(Eof);
187 if (ExpectAndConsume(tok::r_paren))
188 SkipUntil(tok::r_paren, StopAtSemi);
189 SourceLocation Loc = Tok.getLocation();
190 if (ExpectAndConsume(tok::r_paren))
191 SkipUntil(tok::r_paren, StopAtSemi);
197 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
198 static StringRef normalizeAttrName(StringRef Name) {
199 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
200 Name = Name.drop_front(2).drop_back(2);
204 /// \brief Determine whether the given attribute has an identifier argument.
205 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
206 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
207 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
208 #include "clang/Parse/AttrParserStringSwitches.inc"
210 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
213 /// \brief Determine whether the given attribute parses a type argument.
214 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
215 #define CLANG_ATTR_TYPE_ARG_LIST
216 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
217 #include "clang/Parse/AttrParserStringSwitches.inc"
219 #undef CLANG_ATTR_TYPE_ARG_LIST
222 /// \brief Determine whether the given attribute requires parsing its arguments
223 /// in an unevaluated context or not.
224 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
225 #define CLANG_ATTR_ARG_CONTEXT_LIST
226 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
227 #include "clang/Parse/AttrParserStringSwitches.inc"
229 #undef CLANG_ATTR_ARG_CONTEXT_LIST
232 IdentifierLoc *Parser::ParseIdentifierLoc() {
233 assert(Tok.is(tok::identifier) && "expected an identifier");
234 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
236 Tok.getIdentifierInfo());
241 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
242 SourceLocation AttrNameLoc,
243 ParsedAttributes &Attrs,
244 SourceLocation *EndLoc,
245 IdentifierInfo *ScopeName,
246 SourceLocation ScopeLoc,
247 AttributeList::Syntax Syntax) {
248 BalancedDelimiterTracker Parens(*this, tok::l_paren);
249 Parens.consumeOpen();
252 if (Tok.isNot(tok::r_paren))
255 if (Parens.consumeClose())
262 Attrs.addNewTypeAttr(&AttrName,
263 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
264 ScopeName, ScopeLoc, T.get(), Syntax);
266 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
267 ScopeName, ScopeLoc, nullptr, 0, Syntax);
270 unsigned Parser::ParseAttributeArgsCommon(
271 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
272 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
273 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
274 // Ignore the left paren location for now.
278 if (Tok.is(tok::identifier)) {
279 // If this attribute wants an 'identifier' argument, make it so.
280 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
281 AttributeList::Kind AttrKind =
282 AttributeList::getKind(AttrName, ScopeName, Syntax);
284 // If we don't know how to parse this attribute, but this is the only
285 // token in this argument, assume it's meant to be an identifier.
286 if (AttrKind == AttributeList::UnknownAttribute ||
287 AttrKind == AttributeList::IgnoredAttribute) {
288 const Token &Next = NextToken();
289 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
293 ArgExprs.push_back(ParseIdentifierLoc());
296 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
298 if (!ArgExprs.empty())
301 // Parse the non-empty comma-separated list of expressions.
303 std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated;
304 if (attributeParsedArgsUnevaluated(*AttrName))
306 new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated));
309 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
310 if (ArgExpr.isInvalid()) {
311 SkipUntil(tok::r_paren, StopAtSemi);
314 ArgExprs.push_back(ArgExpr.get());
315 // Eat the comma, move to the next argument
316 } while (TryConsumeToken(tok::comma));
319 SourceLocation RParen = Tok.getLocation();
320 if (!ExpectAndConsume(tok::r_paren)) {
321 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
322 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
323 ArgExprs.data(), ArgExprs.size(), Syntax);
329 return static_cast<unsigned>(ArgExprs.size());
332 /// Parse the arguments to a parameterized GNU attribute or
333 /// a C++11 attribute in "gnu" namespace.
334 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
335 SourceLocation AttrNameLoc,
336 ParsedAttributes &Attrs,
337 SourceLocation *EndLoc,
338 IdentifierInfo *ScopeName,
339 SourceLocation ScopeLoc,
340 AttributeList::Syntax Syntax,
343 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
345 AttributeList::Kind AttrKind =
346 AttributeList::getKind(AttrName, ScopeName, Syntax);
348 if (AttrKind == AttributeList::AT_Availability) {
349 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
352 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
353 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
354 ScopeName, ScopeLoc, Syntax);
356 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
357 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
358 ScopeName, ScopeLoc, Syntax);
360 } else if (attributeIsTypeArgAttr(*AttrName)) {
361 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
366 // These may refer to the function arguments, but need to be parsed early to
367 // participate in determining whether it's a redeclaration.
368 std::unique_ptr<ParseScope> PrototypeScope;
369 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
370 D && D->isFunctionDeclarator()) {
371 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
372 PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope |
373 Scope::FunctionDeclarationScope |
375 for (unsigned i = 0; i != FTI.NumParams; ++i) {
376 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
377 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
381 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
385 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
386 SourceLocation AttrNameLoc,
387 ParsedAttributes &Attrs) {
388 // If the attribute isn't known, we will not attempt to parse any
390 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
391 getTargetInfo(), getLangOpts())) {
392 // Eat the left paren, then skip to the ending right paren.
394 SkipUntil(tok::r_paren);
398 SourceLocation OpenParenLoc = Tok.getLocation();
400 if (AttrName->getName() == "property") {
401 // The property declspec is more complex in that it can take one or two
402 // assignment expressions as a parameter, but the lhs of the assignment
403 // must be named get or put.
405 BalancedDelimiterTracker T(*this, tok::l_paren);
406 T.expectAndConsume(diag::err_expected_lparen_after,
407 AttrName->getNameStart(), tok::r_paren);
412 AK_Get = 1 // indices into AccessorNames
414 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
415 bool HasInvalidAccessor = false;
417 // Parse the accessor specifications.
419 // Stop if this doesn't look like an accessor spec.
420 if (!Tok.is(tok::identifier)) {
421 // If the user wrote a completely empty list, use a special diagnostic.
422 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
423 AccessorNames[AK_Put] == nullptr &&
424 AccessorNames[AK_Get] == nullptr) {
425 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
429 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
434 SourceLocation KindLoc = Tok.getLocation();
435 StringRef KindStr = Tok.getIdentifierInfo()->getName();
436 if (KindStr == "get") {
438 } else if (KindStr == "put") {
441 // Recover from the common mistake of using 'set' instead of 'put'.
442 } else if (KindStr == "set") {
443 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
444 << FixItHint::CreateReplacement(KindLoc, "put");
447 // Handle the mistake of forgetting the accessor kind by skipping
449 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
450 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
452 HasInvalidAccessor = true;
453 goto next_property_accessor;
455 // Otherwise, complain about the unknown accessor kind.
457 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
458 HasInvalidAccessor = true;
461 // Try to keep parsing unless it doesn't look like an accessor spec.
462 if (!NextToken().is(tok::equal))
466 // Consume the identifier.
470 if (!TryConsumeToken(tok::equal)) {
471 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
476 // Expect the method name.
477 if (!Tok.is(tok::identifier)) {
478 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
482 if (Kind == AK_Invalid) {
483 // Just drop invalid accessors.
484 } else if (AccessorNames[Kind] != nullptr) {
485 // Complain about the repeated accessor, ignore it, and keep parsing.
486 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
488 AccessorNames[Kind] = Tok.getIdentifierInfo();
492 next_property_accessor:
493 // Keep processing accessors until we run out.
494 if (TryConsumeToken(tok::comma))
497 // If we run into the ')', stop without consuming it.
498 if (Tok.is(tok::r_paren))
501 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
505 // Only add the property attribute if it was well-formed.
506 if (!HasInvalidAccessor)
507 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
508 AccessorNames[AK_Get], AccessorNames[AK_Put],
509 AttributeList::AS_Declspec);
511 return !HasInvalidAccessor;
515 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
516 SourceLocation(), AttributeList::AS_Declspec);
518 // If this attribute's args were parsed, and it was expected to have
519 // arguments but none were provided, emit a diagnostic.
520 const AttributeList *Attr = Attrs.getList();
521 if (Attr && Attr->getMaxArgs() && !NumArgs) {
522 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
528 /// [MS] decl-specifier:
529 /// __declspec ( extended-decl-modifier-seq )
531 /// [MS] extended-decl-modifier-seq:
532 /// extended-decl-modifier[opt]
533 /// extended-decl-modifier extended-decl-modifier-seq
534 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
535 SourceLocation *End) {
536 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
537 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
539 while (Tok.is(tok::kw___declspec)) {
541 BalancedDelimiterTracker T(*this, tok::l_paren);
542 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
546 // An empty declspec is perfectly legal and should not warn. Additionally,
547 // you can specify multiple attributes per declspec.
548 while (Tok.isNot(tok::r_paren)) {
549 // Attribute not present.
550 if (TryConsumeToken(tok::comma))
553 // We expect either a well-known identifier or a generic string. Anything
554 // else is a malformed declspec.
555 bool IsString = Tok.getKind() == tok::string_literal;
556 if (!IsString && Tok.getKind() != tok::identifier &&
557 Tok.getKind() != tok::kw_restrict) {
558 Diag(Tok, diag::err_ms_declspec_type);
563 IdentifierInfo *AttrName;
564 SourceLocation AttrNameLoc;
566 SmallString<8> StrBuffer;
567 bool Invalid = false;
568 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
573 AttrName = PP.getIdentifierInfo(Str);
574 AttrNameLoc = ConsumeStringToken();
576 AttrName = Tok.getIdentifierInfo();
577 AttrNameLoc = ConsumeToken();
580 bool AttrHandled = false;
582 // Parse attribute arguments.
583 if (Tok.is(tok::l_paren))
584 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
585 else if (AttrName->getName() == "property")
586 // The property attribute must have an argument list.
587 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
588 << AttrName->getName();
591 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
592 AttributeList::AS_Declspec);
596 *End = T.getCloseLocation();
600 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
601 // Treat these like attributes
603 switch (Tok.getKind()) {
604 case tok::kw___fastcall:
605 case tok::kw___stdcall:
606 case tok::kw___thiscall:
607 case tok::kw___cdecl:
608 case tok::kw___vectorcall:
609 case tok::kw___ptr64:
611 case tok::kw___ptr32:
612 case tok::kw___unaligned:
614 case tok::kw___uptr: {
615 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
616 SourceLocation AttrNameLoc = ConsumeToken();
617 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
618 AttributeList::AS_Keyword);
627 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
628 SourceLocation StartLoc = Tok.getLocation();
629 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
631 if (EndLoc.isValid()) {
632 SourceRange Range(StartLoc, EndLoc);
633 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
637 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
638 SourceLocation EndLoc;
641 switch (Tok.getKind()) {
643 case tok::kw_volatile:
644 case tok::kw___fastcall:
645 case tok::kw___stdcall:
646 case tok::kw___thiscall:
647 case tok::kw___cdecl:
648 case tok::kw___vectorcall:
649 case tok::kw___ptr32:
650 case tok::kw___ptr64:
652 case tok::kw___unaligned:
655 EndLoc = ConsumeToken();
663 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
664 // Treat these like attributes
665 while (Tok.is(tok::kw___pascal)) {
666 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
667 SourceLocation AttrNameLoc = ConsumeToken();
668 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
669 AttributeList::AS_Keyword);
673 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
674 // Treat these like attributes
675 while (Tok.is(tok::kw___kernel)) {
676 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
677 SourceLocation AttrNameLoc = ConsumeToken();
678 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
679 AttributeList::AS_Keyword);
683 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
684 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
685 SourceLocation AttrNameLoc = Tok.getLocation();
686 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
687 AttributeList::AS_Keyword);
690 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
691 // Treat these like attributes, even though they're type specifiers.
693 switch (Tok.getKind()) {
694 case tok::kw__Nonnull:
695 case tok::kw__Nullable:
696 case tok::kw__Null_unspecified: {
697 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
698 SourceLocation AttrNameLoc = ConsumeToken();
699 if (!getLangOpts().ObjC1)
700 Diag(AttrNameLoc, diag::ext_nullability)
702 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
703 AttributeList::AS_Keyword);
712 static bool VersionNumberSeparator(const char Separator) {
713 return (Separator == '.' || Separator == '_');
716 /// \brief Parse a version number.
720 /// simple-integer ',' simple-integer
721 /// simple-integer ',' simple-integer ',' simple-integer
722 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
723 Range = Tok.getLocation();
725 if (!Tok.is(tok::numeric_constant)) {
726 Diag(Tok, diag::err_expected_version);
727 SkipUntil(tok::comma, tok::r_paren,
728 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
729 return VersionTuple();
732 // Parse the major (and possibly minor and subminor) versions, which
733 // are stored in the numeric constant. We utilize a quirk of the
734 // lexer, which is that it handles something like 1.2.3 as a single
735 // numeric constant, rather than two separate tokens.
736 SmallString<512> Buffer;
737 Buffer.resize(Tok.getLength()+1);
738 const char *ThisTokBegin = &Buffer[0];
740 // Get the spelling of the token, which eliminates trigraphs, etc.
741 bool Invalid = false;
742 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
744 return VersionTuple();
746 // Parse the major version.
747 unsigned AfterMajor = 0;
749 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
750 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
754 if (AfterMajor == 0) {
755 Diag(Tok, diag::err_expected_version);
756 SkipUntil(tok::comma, tok::r_paren,
757 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
758 return VersionTuple();
761 if (AfterMajor == ActualLength) {
764 // We only had a single version component.
766 Diag(Tok, diag::err_zero_version);
767 return VersionTuple();
770 return VersionTuple(Major);
773 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
774 if (!VersionNumberSeparator(AfterMajorSeparator)
775 || (AfterMajor + 1 == ActualLength)) {
776 Diag(Tok, diag::err_expected_version);
777 SkipUntil(tok::comma, tok::r_paren,
778 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
779 return VersionTuple();
782 // Parse the minor version.
783 unsigned AfterMinor = AfterMajor + 1;
785 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
786 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
790 if (AfterMinor == ActualLength) {
793 // We had major.minor.
794 if (Major == 0 && Minor == 0) {
795 Diag(Tok, diag::err_zero_version);
796 return VersionTuple();
799 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
802 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
803 // If what follows is not a '.' or '_', we have a problem.
804 if (!VersionNumberSeparator(AfterMinorSeparator)) {
805 Diag(Tok, diag::err_expected_version);
806 SkipUntil(tok::comma, tok::r_paren,
807 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
808 return VersionTuple();
811 // Warn if separators, be it '.' or '_', do not match.
812 if (AfterMajorSeparator != AfterMinorSeparator)
813 Diag(Tok, diag::warn_expected_consistent_version_separator);
815 // Parse the subminor version.
816 unsigned AfterSubminor = AfterMinor + 1;
817 unsigned Subminor = 0;
818 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
819 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
823 if (AfterSubminor != ActualLength) {
824 Diag(Tok, diag::err_expected_version);
825 SkipUntil(tok::comma, tok::r_paren,
826 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
827 return VersionTuple();
830 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
833 /// \brief Parse the contents of the "availability" attribute.
835 /// availability-attribute:
836 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
841 /// version-arg-list:
843 /// version-arg ',' version-arg-list
846 /// 'introduced' '=' version
847 /// 'deprecated' '=' version
848 /// 'obsoleted' = version
851 /// 'message' '=' <string>
852 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
853 SourceLocation AvailabilityLoc,
854 ParsedAttributes &attrs,
855 SourceLocation *endLoc,
856 IdentifierInfo *ScopeName,
857 SourceLocation ScopeLoc,
858 AttributeList::Syntax Syntax) {
859 enum { Introduced, Deprecated, Obsoleted, Unknown };
860 AvailabilityChange Changes[Unknown];
861 ExprResult MessageExpr;
864 BalancedDelimiterTracker T(*this, tok::l_paren);
865 if (T.consumeOpen()) {
866 Diag(Tok, diag::err_expected) << tok::l_paren;
870 // Parse the platform name,
871 if (Tok.isNot(tok::identifier)) {
872 Diag(Tok, diag::err_availability_expected_platform);
873 SkipUntil(tok::r_paren, StopAtSemi);
876 IdentifierLoc *Platform = ParseIdentifierLoc();
878 // Parse the ',' following the platform name.
879 if (ExpectAndConsume(tok::comma)) {
880 SkipUntil(tok::r_paren, StopAtSemi);
884 // If we haven't grabbed the pointers for the identifiers
885 // "introduced", "deprecated", and "obsoleted", do so now.
886 if (!Ident_introduced) {
887 Ident_introduced = PP.getIdentifierInfo("introduced");
888 Ident_deprecated = PP.getIdentifierInfo("deprecated");
889 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
890 Ident_unavailable = PP.getIdentifierInfo("unavailable");
891 Ident_message = PP.getIdentifierInfo("message");
894 // Parse the set of introductions/deprecations/removals.
895 SourceLocation UnavailableLoc;
897 if (Tok.isNot(tok::identifier)) {
898 Diag(Tok, diag::err_availability_expected_change);
899 SkipUntil(tok::r_paren, StopAtSemi);
902 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
903 SourceLocation KeywordLoc = ConsumeToken();
905 if (Keyword == Ident_unavailable) {
906 if (UnavailableLoc.isValid()) {
907 Diag(KeywordLoc, diag::err_availability_redundant)
908 << Keyword << SourceRange(UnavailableLoc);
910 UnavailableLoc = KeywordLoc;
914 if (Tok.isNot(tok::equal)) {
915 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
916 SkipUntil(tok::r_paren, StopAtSemi);
920 if (Keyword == Ident_message) {
921 if (Tok.isNot(tok::string_literal)) {
922 Diag(Tok, diag::err_expected_string_literal)
923 << /*Source='availability attribute'*/2;
924 SkipUntil(tok::r_paren, StopAtSemi);
927 MessageExpr = ParseStringLiteralExpression();
928 // Also reject wide string literals.
929 if (StringLiteral *MessageStringLiteral =
930 cast_or_null<StringLiteral>(MessageExpr.get())) {
931 if (MessageStringLiteral->getCharByteWidth() != 1) {
932 Diag(MessageStringLiteral->getSourceRange().getBegin(),
933 diag::err_expected_string_literal)
934 << /*Source='availability attribute'*/ 2;
935 SkipUntil(tok::r_paren, StopAtSemi);
942 // Special handling of 'NA' only when applied to introduced or
944 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
945 Tok.is(tok::identifier)) {
946 IdentifierInfo *NA = Tok.getIdentifierInfo();
947 if (NA->getName() == "NA") {
949 if (Keyword == Ident_introduced)
950 UnavailableLoc = KeywordLoc;
955 SourceRange VersionRange;
956 VersionTuple Version = ParseVersionTuple(VersionRange);
958 if (Version.empty()) {
959 SkipUntil(tok::r_paren, StopAtSemi);
964 if (Keyword == Ident_introduced)
966 else if (Keyword == Ident_deprecated)
968 else if (Keyword == Ident_obsoleted)
973 if (Index < Unknown) {
974 if (!Changes[Index].KeywordLoc.isInvalid()) {
975 Diag(KeywordLoc, diag::err_availability_redundant)
977 << SourceRange(Changes[Index].KeywordLoc,
978 Changes[Index].VersionRange.getEnd());
981 Changes[Index].KeywordLoc = KeywordLoc;
982 Changes[Index].Version = Version;
983 Changes[Index].VersionRange = VersionRange;
985 Diag(KeywordLoc, diag::err_availability_unknown_change)
986 << Keyword << VersionRange;
989 } while (TryConsumeToken(tok::comma));
992 if (T.consumeClose())
996 *endLoc = T.getCloseLocation();
998 // The 'unavailable' availability cannot be combined with any other
999 // availability changes. Make sure that hasn't happened.
1000 if (UnavailableLoc.isValid()) {
1001 bool Complained = false;
1002 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1003 if (Changes[Index].KeywordLoc.isValid()) {
1005 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1006 << SourceRange(Changes[Index].KeywordLoc,
1007 Changes[Index].VersionRange.getEnd());
1011 // Clear out the availability.
1012 Changes[Index] = AvailabilityChange();
1017 // Record this attribute
1018 attrs.addNew(&Availability,
1019 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1020 ScopeName, ScopeLoc,
1022 Changes[Introduced],
1023 Changes[Deprecated],
1025 UnavailableLoc, MessageExpr.get(),
1029 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1030 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1034 /// opt-class_method:
1035 /// Identifier: | <empty>
1037 /// opt-instance_method:
1038 /// Identifier | <empty>
1040 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1041 SourceLocation ObjCBridgeRelatedLoc,
1042 ParsedAttributes &attrs,
1043 SourceLocation *endLoc,
1044 IdentifierInfo *ScopeName,
1045 SourceLocation ScopeLoc,
1046 AttributeList::Syntax Syntax) {
1048 BalancedDelimiterTracker T(*this, tok::l_paren);
1049 if (T.consumeOpen()) {
1050 Diag(Tok, diag::err_expected) << tok::l_paren;
1054 // Parse the related class name.
1055 if (Tok.isNot(tok::identifier)) {
1056 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1057 SkipUntil(tok::r_paren, StopAtSemi);
1060 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1061 if (ExpectAndConsume(tok::comma)) {
1062 SkipUntil(tok::r_paren, StopAtSemi);
1066 // Parse optional class method name.
1067 IdentifierLoc *ClassMethod = nullptr;
1068 if (Tok.is(tok::identifier)) {
1069 ClassMethod = ParseIdentifierLoc();
1070 if (!TryConsumeToken(tok::colon)) {
1071 Diag(Tok, diag::err_objcbridge_related_selector_name);
1072 SkipUntil(tok::r_paren, StopAtSemi);
1076 if (!TryConsumeToken(tok::comma)) {
1077 if (Tok.is(tok::colon))
1078 Diag(Tok, diag::err_objcbridge_related_selector_name);
1080 Diag(Tok, diag::err_expected) << tok::comma;
1081 SkipUntil(tok::r_paren, StopAtSemi);
1085 // Parse optional instance method name.
1086 IdentifierLoc *InstanceMethod = nullptr;
1087 if (Tok.is(tok::identifier))
1088 InstanceMethod = ParseIdentifierLoc();
1089 else if (Tok.isNot(tok::r_paren)) {
1090 Diag(Tok, diag::err_expected) << tok::r_paren;
1091 SkipUntil(tok::r_paren, StopAtSemi);
1096 if (T.consumeClose())
1100 *endLoc = T.getCloseLocation();
1102 // Record this attribute
1103 attrs.addNew(&ObjCBridgeRelated,
1104 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1105 ScopeName, ScopeLoc,
1112 // Late Parsed Attributes:
1113 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1115 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1117 void Parser::LateParsedClass::ParseLexedAttributes() {
1118 Self->ParseLexedAttributes(*Class);
1121 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1122 Self->ParseLexedAttribute(*this, true, false);
1125 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1126 /// scope appropriately.
1127 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1128 // Deal with templates
1129 // FIXME: Test cases to make sure this does the right thing for templates.
1130 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1131 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1133 if (HasTemplateScope)
1134 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1136 // Set or update the scope flags.
1137 bool AlreadyHasClassScope = Class.TopLevelClass;
1138 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1139 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1140 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1142 // Enter the scope of nested classes
1143 if (!AlreadyHasClassScope)
1144 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1145 Class.TagOrTemplate);
1146 if (!Class.LateParsedDeclarations.empty()) {
1147 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1148 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1152 if (!AlreadyHasClassScope)
1153 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1154 Class.TagOrTemplate);
1157 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1158 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1159 bool EnterScope, bool OnDefinition) {
1160 assert(LAs.parseSoon() &&
1161 "Attribute list should be marked for immediate parsing.");
1162 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1165 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1171 /// \brief Finish parsing an attribute for which parsing was delayed.
1172 /// This will be called at the end of parsing a class declaration
1173 /// for each LateParsedAttribute. We consume the saved tokens and
1174 /// create an attribute with the arguments filled in. We add this
1175 /// to the Attribute list for the decl.
1176 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1177 bool EnterScope, bool OnDefinition) {
1178 // Create a fake EOF so that attribute parsing won't go off the end of the
1181 AttrEnd.startToken();
1182 AttrEnd.setKind(tok::eof);
1183 AttrEnd.setLocation(Tok.getLocation());
1184 AttrEnd.setEofData(LA.Toks.data());
1185 LA.Toks.push_back(AttrEnd);
1187 // Append the current token at the end of the new token stream so that it
1188 // doesn't get lost.
1189 LA.Toks.push_back(Tok);
1190 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1191 // Consume the previously pushed token.
1192 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1194 ParsedAttributes Attrs(AttrFactory);
1195 SourceLocation endLoc;
1197 if (LA.Decls.size() > 0) {
1198 Decl *D = LA.Decls[0];
1199 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1200 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1202 // Allow 'this' within late-parsed attributes.
1203 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1204 ND && ND->isCXXInstanceMember());
1206 if (LA.Decls.size() == 1) {
1207 // If the Decl is templatized, add template parameters to scope.
1208 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1209 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1210 if (HasTemplateScope)
1211 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1213 // If the Decl is on a function, add function parameters to the scope.
1214 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1215 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1217 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1219 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1220 nullptr, SourceLocation(), AttributeList::AS_GNU,
1224 Actions.ActOnExitFunctionContext();
1225 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1227 if (HasTemplateScope) {
1231 // If there are multiple decls, then the decl cannot be within the
1233 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1234 nullptr, SourceLocation(), AttributeList::AS_GNU,
1238 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1241 const AttributeList *AL = Attrs.getList();
1242 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1244 Diag(Tok, diag::warn_attribute_on_function_definition)
1247 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1248 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1250 // Due to a parsing error, we either went over the cached tokens or
1251 // there are still cached tokens left, so we skip the leftover tokens.
1252 while (Tok.isNot(tok::eof))
1255 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1259 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1260 SourceLocation AttrNameLoc,
1261 ParsedAttributes &Attrs,
1262 SourceLocation *EndLoc,
1263 IdentifierInfo *ScopeName,
1264 SourceLocation ScopeLoc,
1265 AttributeList::Syntax Syntax) {
1266 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1268 BalancedDelimiterTracker T(*this, tok::l_paren);
1271 if (Tok.isNot(tok::identifier)) {
1272 Diag(Tok, diag::err_expected) << tok::identifier;
1276 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1278 if (ExpectAndConsume(tok::comma)) {
1283 SourceRange MatchingCTypeRange;
1284 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1285 if (MatchingCType.isInvalid()) {
1290 bool LayoutCompatible = false;
1291 bool MustBeNull = false;
1292 while (TryConsumeToken(tok::comma)) {
1293 if (Tok.isNot(tok::identifier)) {
1294 Diag(Tok, diag::err_expected) << tok::identifier;
1298 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1299 if (Flag->isStr("layout_compatible"))
1300 LayoutCompatible = true;
1301 else if (Flag->isStr("must_be_null"))
1304 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1308 ConsumeToken(); // consume flag
1311 if (!T.consumeClose()) {
1312 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1313 ArgumentKind, MatchingCType.get(),
1314 LayoutCompatible, MustBeNull, Syntax);
1318 *EndLoc = T.getCloseLocation();
1321 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1322 /// of a C++11 attribute-specifier in a location where an attribute is not
1323 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1326 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1327 /// this doesn't appear to actually be an attribute-specifier, and the caller
1328 /// should try to parse it.
1329 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1330 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1332 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1333 case CAK_NotAttributeSpecifier:
1334 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1337 case CAK_InvalidAttributeSpecifier:
1338 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1341 case CAK_AttributeSpecifier:
1342 // Parse and discard the attributes.
1343 SourceLocation BeginLoc = ConsumeBracket();
1345 SkipUntil(tok::r_square);
1346 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1347 SourceLocation EndLoc = ConsumeBracket();
1348 Diag(BeginLoc, diag::err_attributes_not_allowed)
1349 << SourceRange(BeginLoc, EndLoc);
1352 llvm_unreachable("All cases handled above.");
1355 /// \brief We have found the opening square brackets of a C++11
1356 /// attribute-specifier in a location where an attribute is not permitted, but
1357 /// we know where the attributes ought to be written. Parse them anyway, and
1358 /// provide a fixit moving them to the right place.
1359 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1360 SourceLocation CorrectLocation) {
1361 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1362 Tok.is(tok::kw_alignas));
1364 // Consume the attributes.
1365 SourceLocation Loc = Tok.getLocation();
1366 ParseCXX11Attributes(Attrs);
1367 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1369 Diag(Loc, diag::err_attributes_not_allowed)
1370 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1371 << FixItHint::CreateRemoval(AttrRange);
1374 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1375 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1379 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1380 AttributeList *AttrList = attrs.getList();
1382 if (AttrList->isCXX11Attribute()) {
1383 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1384 << AttrList->getName();
1385 AttrList->setInvalid();
1387 AttrList = AttrList->getNext();
1391 // As an exception to the rule, __declspec(align(...)) before the
1392 // class-key affects the type instead of the variable.
1393 void Parser::handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
1395 Sema::TagUseKind TUK) {
1396 if (TUK == Sema::TUK_Reference)
1399 ParsedAttributes &PA = DS.getAttributes();
1400 AttributeList *AL = PA.getList();
1401 AttributeList *Prev = nullptr;
1403 AttributeList *Next = AL->getNext();
1405 // We only consider attributes using the appropriate '__declspec' spelling,
1406 // this behavior doesn't extend to any other spellings.
1407 if (AL->getKind() == AttributeList::AT_Aligned &&
1408 AL->isDeclspecAttribute()) {
1409 // Stitch the attribute into the tag's attribute list.
1410 AL->setNext(nullptr);
1413 // Remove the attribute from the variable's attribute list.
1415 // Set the last variable attribute's next attribute to be the attribute
1416 // after the current one.
1417 Prev->setNext(Next);
1419 // Removing the head of the list requires us to reset the head to the
1431 /// ParseDeclaration - Parse a full 'declaration', which consists of
1432 /// declaration-specifiers, some number of declarators, and a semicolon.
1433 /// 'Context' should be a Declarator::TheContext value. This returns the
1434 /// location of the semicolon in DeclEnd.
1436 /// declaration: [C99 6.7]
1437 /// block-declaration ->
1438 /// simple-declaration
1440 /// [C++] template-declaration
1441 /// [C++] namespace-definition
1442 /// [C++] using-directive
1443 /// [C++] using-declaration
1444 /// [C++11/C11] static_assert-declaration
1445 /// others... [FIXME]
1447 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
1448 SourceLocation &DeclEnd,
1449 ParsedAttributesWithRange &attrs) {
1450 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1451 // Must temporarily exit the objective-c container scope for
1452 // parsing c none objective-c decls.
1453 ObjCDeclContextSwitch ObjCDC(*this);
1455 Decl *SingleDecl = nullptr;
1456 Decl *OwnedType = nullptr;
1457 switch (Tok.getKind()) {
1458 case tok::kw_template:
1459 case tok::kw_export:
1460 ProhibitAttributes(attrs);
1461 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1463 case tok::kw_inline:
1464 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1465 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1466 ProhibitAttributes(attrs);
1467 SourceLocation InlineLoc = ConsumeToken();
1468 return ParseNamespace(Context, DeclEnd, InlineLoc);
1470 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1472 case tok::kw_namespace:
1473 ProhibitAttributes(attrs);
1474 return ParseNamespace(Context, DeclEnd);
1476 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1477 DeclEnd, attrs, &OwnedType);
1479 case tok::kw_static_assert:
1480 case tok::kw__Static_assert:
1481 ProhibitAttributes(attrs);
1482 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1485 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1488 // This routine returns a DeclGroup, if the thing we parsed only contains a
1489 // single decl, convert it now. Alias declarations can also declare a type;
1490 // include that too if it is present.
1491 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1494 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1495 /// declaration-specifiers init-declarator-list[opt] ';'
1496 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1497 /// init-declarator-list ';'
1498 ///[C90/C++]init-declarator-list ';' [TODO]
1499 /// [OMP] threadprivate-directive [TODO]
1501 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1502 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1504 /// If RequireSemi is false, this does not check for a ';' at the end of the
1505 /// declaration. If it is true, it checks for and eats it.
1507 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1508 /// of a simple-declaration. If we find that we are, we also parse the
1509 /// for-range-initializer, and place it here.
1510 Parser::DeclGroupPtrTy
1511 Parser::ParseSimpleDeclaration(unsigned Context,
1512 SourceLocation &DeclEnd,
1513 ParsedAttributesWithRange &Attrs,
1514 bool RequireSemi, ForRangeInit *FRI) {
1515 // Parse the common declaration-specifiers piece.
1516 ParsingDeclSpec DS(*this);
1518 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1519 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1521 // If we had a free-standing type definition with a missing semicolon, we
1522 // may get this far before the problem becomes obvious.
1523 if (DS.hasTagDefinition() &&
1524 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1525 return DeclGroupPtrTy();
1527 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1528 // declaration-specifiers init-declarator-list[opt] ';'
1529 if (Tok.is(tok::semi)) {
1530 ProhibitAttributes(Attrs);
1531 DeclEnd = Tok.getLocation();
1532 if (RequireSemi) ConsumeToken();
1533 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1535 DS.complete(TheDecl);
1536 return Actions.ConvertDeclToDeclGroup(TheDecl);
1539 DS.takeAttributesFrom(Attrs);
1540 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1543 /// Returns true if this might be the start of a declarator, or a common typo
1544 /// for a declarator.
1545 bool Parser::MightBeDeclarator(unsigned Context) {
1546 switch (Tok.getKind()) {
1547 case tok::annot_cxxscope:
1548 case tok::annot_template_id:
1550 case tok::code_completion:
1551 case tok::coloncolon:
1553 case tok::kw___attribute:
1554 case tok::kw_operator:
1561 return getLangOpts().CPlusPlus;
1563 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1564 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1565 NextToken().is(tok::l_square);
1567 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1568 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1570 case tok::identifier:
1571 switch (NextToken().getKind()) {
1572 case tok::code_completion:
1573 case tok::coloncolon:
1576 case tok::equalequal: // Might be a typo for '='.
1577 case tok::kw_alignas:
1579 case tok::kw___attribute:
1591 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1592 // and in block scope it's probably a label. Inside a class definition,
1593 // this is a bit-field.
1594 return Context == Declarator::MemberContext ||
1595 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1597 case tok::identifier: // Possible virt-specifier.
1598 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1609 /// Skip until we reach something which seems like a sensible place to pick
1610 /// up parsing after a malformed declaration. This will sometimes stop sooner
1611 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1612 void Parser::SkipMalformedDecl() {
1614 switch (Tok.getKind()) {
1616 // Skip until matching }, then stop. We've probably skipped over
1617 // a malformed class or function definition or similar.
1619 SkipUntil(tok::r_brace);
1620 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1621 // This declaration isn't over yet. Keep skipping.
1624 TryConsumeToken(tok::semi);
1629 SkipUntil(tok::r_square);
1634 SkipUntil(tok::r_paren);
1644 case tok::kw_inline:
1645 // 'inline namespace' at the start of a line is almost certainly
1646 // a good place to pick back up parsing, except in an Objective-C
1647 // @interface context.
1648 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1649 (!ParsingInObjCContainer || CurParsedObjCImpl))
1653 case tok::kw_namespace:
1654 // 'namespace' at the start of a line is almost certainly a good
1655 // place to pick back up parsing, except in an Objective-C
1656 // @interface context.
1657 if (Tok.isAtStartOfLine() &&
1658 (!ParsingInObjCContainer || CurParsedObjCImpl))
1663 // @end is very much like } in Objective-C contexts.
1664 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1665 ParsingInObjCContainer)
1671 // - and + probably start new method declarations in Objective-C contexts.
1672 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1677 case tok::annot_module_begin:
1678 case tok::annot_module_end:
1679 case tok::annot_module_include:
1690 /// ParseDeclGroup - Having concluded that this is either a function
1691 /// definition or a group of object declarations, actually parse the
1693 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1695 SourceLocation *DeclEnd,
1696 ForRangeInit *FRI) {
1697 // Parse the first declarator.
1698 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1701 // Bail out if the first declarator didn't seem well-formed.
1702 if (!D.hasName() && !D.mayOmitIdentifier()) {
1703 SkipMalformedDecl();
1704 return DeclGroupPtrTy();
1707 // Save late-parsed attributes for now; they need to be parsed in the
1708 // appropriate function scope after the function Decl has been constructed.
1709 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1710 LateParsedAttrList LateParsedAttrs(true);
1711 if (D.isFunctionDeclarator()) {
1712 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1714 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1715 // attribute. If we find the keyword here, tell the user to put it
1716 // at the start instead.
1717 if (Tok.is(tok::kw__Noreturn)) {
1718 SourceLocation Loc = ConsumeToken();
1719 const char *PrevSpec;
1722 // We can offer a fixit if it's valid to mark this function as _Noreturn
1723 // and we don't have any other declarators in this declaration.
1724 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1725 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1726 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1728 Diag(Loc, diag::err_c11_noreturn_misplaced)
1729 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1730 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1735 // Check to see if we have a function *definition* which must have a body.
1736 if (D.isFunctionDeclarator() &&
1737 // Look at the next token to make sure that this isn't a function
1738 // declaration. We have to check this because __attribute__ might be the
1739 // start of a function definition in GCC-extended K&R C.
1740 !isDeclarationAfterDeclarator()) {
1742 // Function definitions are only allowed at file scope and in C++ classes.
1743 // The C++ inline method definition case is handled elsewhere, so we only
1744 // need to handle the file scope definition case.
1745 if (Context == Declarator::FileContext) {
1746 if (isStartOfFunctionDefinition(D)) {
1747 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1748 Diag(Tok, diag::err_function_declared_typedef);
1750 // Recover by treating the 'typedef' as spurious.
1751 DS.ClearStorageClassSpecs();
1755 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1756 return Actions.ConvertDeclToDeclGroup(TheDecl);
1759 if (isDeclarationSpecifier()) {
1760 // If there is an invalid declaration specifier right after the
1761 // function prototype, then we must be in a missing semicolon case
1762 // where this isn't actually a body. Just fall through into the code
1763 // that handles it as a prototype, and let the top-level code handle
1764 // the erroneous declspec where it would otherwise expect a comma or
1767 Diag(Tok, diag::err_expected_fn_body);
1768 SkipUntil(tok::semi);
1769 return DeclGroupPtrTy();
1772 if (Tok.is(tok::l_brace)) {
1773 Diag(Tok, diag::err_function_definition_not_allowed);
1774 SkipMalformedDecl();
1775 return DeclGroupPtrTy();
1780 if (ParseAsmAttributesAfterDeclarator(D))
1781 return DeclGroupPtrTy();
1783 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1784 // must parse and analyze the for-range-initializer before the declaration is
1787 // Handle the Objective-C for-in loop variable similarly, although we
1788 // don't need to parse the container in advance.
1789 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1790 bool IsForRangeLoop = false;
1791 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1792 IsForRangeLoop = true;
1793 if (Tok.is(tok::l_brace))
1794 FRI->RangeExpr = ParseBraceInitializer();
1796 FRI->RangeExpr = ParseExpression();
1799 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1801 Actions.ActOnCXXForRangeDecl(ThisDecl);
1802 Actions.FinalizeDeclaration(ThisDecl);
1803 D.complete(ThisDecl);
1804 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1807 SmallVector<Decl *, 8> DeclsInGroup;
1808 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1809 D, ParsedTemplateInfo(), FRI);
1810 if (LateParsedAttrs.size() > 0)
1811 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1812 D.complete(FirstDecl);
1814 DeclsInGroup.push_back(FirstDecl);
1816 bool ExpectSemi = Context != Declarator::ForContext;
1818 // If we don't have a comma, it is either the end of the list (a ';') or an
1820 SourceLocation CommaLoc;
1821 while (TryConsumeToken(tok::comma, CommaLoc)) {
1822 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1823 // This comma was followed by a line-break and something which can't be
1824 // the start of a declarator. The comma was probably a typo for a
1826 Diag(CommaLoc, diag::err_expected_semi_declaration)
1827 << FixItHint::CreateReplacement(CommaLoc, ";");
1832 // Parse the next declarator.
1834 D.setCommaLoc(CommaLoc);
1836 // Accept attributes in an init-declarator. In the first declarator in a
1837 // declaration, these would be part of the declspec. In subsequent
1838 // declarators, they become part of the declarator itself, so that they
1839 // don't apply to declarators after *this* one. Examples:
1840 // short __attribute__((common)) var; -> declspec
1841 // short var __attribute__((common)); -> declarator
1842 // short x, __attribute__((common)) var; -> declarator
1843 MaybeParseGNUAttributes(D);
1845 // MSVC parses but ignores qualifiers after the comma as an extension.
1846 if (getLangOpts().MicrosoftExt)
1847 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
1850 if (!D.isInvalidType()) {
1851 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1852 D.complete(ThisDecl);
1854 DeclsInGroup.push_back(ThisDecl);
1859 *DeclEnd = Tok.getLocation();
1862 ExpectAndConsumeSemi(Context == Declarator::FileContext
1863 ? diag::err_invalid_token_after_toplevel_declarator
1864 : diag::err_expected_semi_declaration)) {
1865 // Okay, there was no semicolon and one was expected. If we see a
1866 // declaration specifier, just assume it was missing and continue parsing.
1867 // Otherwise things are very confused and we skip to recover.
1868 if (!isDeclarationSpecifier()) {
1869 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1870 TryConsumeToken(tok::semi);
1874 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1877 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1878 /// declarator. Returns true on an error.
1879 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1880 // If a simple-asm-expr is present, parse it.
1881 if (Tok.is(tok::kw_asm)) {
1883 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1884 if (AsmLabel.isInvalid()) {
1885 SkipUntil(tok::semi, StopBeforeMatch);
1889 D.setAsmLabel(AsmLabel.get());
1893 MaybeParseGNUAttributes(D);
1897 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1898 /// declarator'. This method parses the remainder of the declaration
1899 /// (including any attributes or initializer, among other things) and
1900 /// finalizes the declaration.
1902 /// init-declarator: [C99 6.7]
1904 /// declarator '=' initializer
1905 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1906 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1907 /// [C++] declarator initializer[opt]
1909 /// [C++] initializer:
1910 /// [C++] '=' initializer-clause
1911 /// [C++] '(' expression-list ')'
1912 /// [C++0x] '=' 'default' [TODO]
1913 /// [C++0x] '=' 'delete'
1914 /// [C++0x] braced-init-list
1916 /// According to the standard grammar, =default and =delete are function
1917 /// definitions, but that definitely doesn't fit with the parser here.
1919 Decl *Parser::ParseDeclarationAfterDeclarator(
1920 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
1921 if (ParseAsmAttributesAfterDeclarator(D))
1924 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1927 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
1928 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
1929 // Inform the current actions module that we just parsed this declarator.
1930 Decl *ThisDecl = nullptr;
1931 switch (TemplateInfo.Kind) {
1932 case ParsedTemplateInfo::NonTemplate:
1933 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1936 case ParsedTemplateInfo::Template:
1937 case ParsedTemplateInfo::ExplicitSpecialization: {
1938 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1939 *TemplateInfo.TemplateParams,
1941 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1942 // Re-direct this decl to refer to the templated decl so that we can
1944 ThisDecl = VT->getTemplatedDecl();
1947 case ParsedTemplateInfo::ExplicitInstantiation: {
1948 if (Tok.is(tok::semi)) {
1949 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1950 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1951 if (ThisRes.isInvalid()) {
1952 SkipUntil(tok::semi, StopBeforeMatch);
1955 ThisDecl = ThisRes.get();
1957 // FIXME: This check should be for a variable template instantiation only.
1959 // Check that this is a valid instantiation
1960 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1961 // If the declarator-id is not a template-id, issue a diagnostic and
1962 // recover by ignoring the 'template' keyword.
1963 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1964 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1965 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1967 SourceLocation LAngleLoc =
1968 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1969 Diag(D.getIdentifierLoc(),
1970 diag::err_explicit_instantiation_with_definition)
1971 << SourceRange(TemplateInfo.TemplateLoc)
1972 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1974 // Recover as if it were an explicit specialization.
1975 TemplateParameterLists FakedParamLists;
1976 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1977 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1981 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1988 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1990 // Parse declarator '=' initializer.
1991 // If a '==' or '+=' is found, suggest a fixit to '='.
1992 if (isTokenEqualOrEqualTypo()) {
1993 SourceLocation EqualLoc = ConsumeToken();
1995 if (Tok.is(tok::kw_delete)) {
1996 if (D.isFunctionDeclarator())
1997 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2000 Diag(ConsumeToken(), diag::err_deleted_non_function);
2001 } else if (Tok.is(tok::kw_default)) {
2002 if (D.isFunctionDeclarator())
2003 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2006 Diag(ConsumeToken(), diag::err_default_special_members);
2008 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2010 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2013 if (Tok.is(tok::code_completion)) {
2014 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2015 Actions.FinalizeDeclaration(ThisDecl);
2020 ExprResult Init(ParseInitializer());
2022 // If this is the only decl in (possibly) range based for statement,
2023 // our best guess is that the user meant ':' instead of '='.
2024 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2025 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2026 << FixItHint::CreateReplacement(EqualLoc, ":");
2027 // We are trying to stop parser from looking for ';' in this for
2028 // statement, therefore preventing spurious errors to be issued.
2029 FRI->ColonLoc = EqualLoc;
2031 FRI->RangeExpr = Init;
2034 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2035 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2039 if (Init.isInvalid()) {
2040 SmallVector<tok::TokenKind, 2> StopTokens;
2041 StopTokens.push_back(tok::comma);
2042 if (D.getContext() == Declarator::ForContext)
2043 StopTokens.push_back(tok::r_paren);
2044 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2045 Actions.ActOnInitializerError(ThisDecl);
2047 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2048 /*DirectInit=*/false, TypeContainsAuto);
2050 } else if (Tok.is(tok::l_paren)) {
2051 // Parse C++ direct initializer: '(' expression-list ')'
2052 BalancedDelimiterTracker T(*this, tok::l_paren);
2056 CommaLocsTy CommaLocs;
2058 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2060 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2063 if (ParseExpressionList(Exprs, CommaLocs, [&] {
2064 Actions.CodeCompleteConstructor(getCurScope(),
2065 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
2066 ThisDecl->getLocation(), Exprs);
2068 Actions.ActOnInitializerError(ThisDecl);
2069 SkipUntil(tok::r_paren, StopAtSemi);
2071 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2072 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2079 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2080 "Unexpected number of commas!");
2082 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2083 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2087 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2088 T.getCloseLocation(),
2090 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2091 /*DirectInit=*/true, TypeContainsAuto);
2093 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2094 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2095 // Parse C++0x braced-init-list.
2096 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2098 if (D.getCXXScopeSpec().isSet()) {
2100 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2103 ExprResult Init(ParseBraceInitializer());
2105 if (D.getCXXScopeSpec().isSet()) {
2106 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2110 if (Init.isInvalid()) {
2111 Actions.ActOnInitializerError(ThisDecl);
2113 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2114 /*DirectInit=*/true, TypeContainsAuto);
2117 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
2120 Actions.FinalizeDeclaration(ThisDecl);
2125 /// ParseSpecifierQualifierList
2126 /// specifier-qualifier-list:
2127 /// type-specifier specifier-qualifier-list[opt]
2128 /// type-qualifier specifier-qualifier-list[opt]
2129 /// [GNU] attributes specifier-qualifier-list[opt]
2131 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2132 DeclSpecContext DSC) {
2133 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2134 /// parse declaration-specifiers and complain about extra stuff.
2135 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2136 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2138 // Validate declspec for type-name.
2139 unsigned Specs = DS.getParsedSpecifiers();
2140 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2141 Diag(Tok, diag::err_expected_type);
2142 DS.SetTypeSpecError();
2143 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2144 Diag(Tok, diag::err_typename_requires_specqual);
2145 if (!DS.hasTypeSpecifier())
2146 DS.SetTypeSpecError();
2149 // Issue diagnostic and remove storage class if present.
2150 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2151 if (DS.getStorageClassSpecLoc().isValid())
2152 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2154 Diag(DS.getThreadStorageClassSpecLoc(),
2155 diag::err_typename_invalid_storageclass);
2156 DS.ClearStorageClassSpecs();
2159 // Issue diagnostic and remove function specifier if present.
2160 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2161 if (DS.isInlineSpecified())
2162 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2163 if (DS.isVirtualSpecified())
2164 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2165 if (DS.isExplicitSpecified())
2166 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2167 DS.ClearFunctionSpecs();
2170 // Issue diagnostic and remove constexpr specfier if present.
2171 if (DS.isConstexprSpecified() && DSC != DSC_condition) {
2172 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2173 DS.ClearConstexprSpec();
2177 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2178 /// specified token is valid after the identifier in a declarator which
2179 /// immediately follows the declspec. For example, these things are valid:
2181 /// int x [ 4]; // direct-declarator
2182 /// int x ( int y); // direct-declarator
2183 /// int(int x ) // direct-declarator
2184 /// int x ; // simple-declaration
2185 /// int x = 17; // init-declarator-list
2186 /// int x , y; // init-declarator-list
2187 /// int x __asm__ ("foo"); // init-declarator-list
2188 /// int x : 4; // struct-declarator
2189 /// int x { 5}; // C++'0x unified initializers
2191 /// This is not, because 'x' does not immediately follow the declspec (though
2192 /// ')' happens to be valid anyway).
2195 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2196 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2197 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2201 /// ParseImplicitInt - This method is called when we have an non-typename
2202 /// identifier in a declspec (which normally terminates the decl spec) when
2203 /// the declspec has no type specifier. In this case, the declspec is either
2204 /// malformed or is "implicit int" (in K&R and C89).
2206 /// This method handles diagnosing this prettily and returns false if the
2207 /// declspec is done being processed. If it recovers and thinks there may be
2208 /// other pieces of declspec after it, it returns true.
2210 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2211 const ParsedTemplateInfo &TemplateInfo,
2212 AccessSpecifier AS, DeclSpecContext DSC,
2213 ParsedAttributesWithRange &Attrs) {
2214 assert(Tok.is(tok::identifier) && "should have identifier");
2216 SourceLocation Loc = Tok.getLocation();
2217 // If we see an identifier that is not a type name, we normally would
2218 // parse it as the identifer being declared. However, when a typename
2219 // is typo'd or the definition is not included, this will incorrectly
2220 // parse the typename as the identifier name and fall over misparsing
2221 // later parts of the diagnostic.
2223 // As such, we try to do some look-ahead in cases where this would
2224 // otherwise be an "implicit-int" case to see if this is invalid. For
2225 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2226 // an identifier with implicit int, we'd get a parse error because the
2227 // next token is obviously invalid for a type. Parse these as a case
2228 // with an invalid type specifier.
2229 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2231 // Since we know that this either implicit int (which is rare) or an
2232 // error, do lookahead to try to do better recovery. This never applies
2233 // within a type specifier. Outside of C++, we allow this even if the
2234 // language doesn't "officially" support implicit int -- we support
2235 // implicit int as an extension in C99 and C11.
2236 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2237 isValidAfterIdentifierInDeclarator(NextToken())) {
2238 // If this token is valid for implicit int, e.g. "static x = 4", then
2239 // we just avoid eating the identifier, so it will be parsed as the
2240 // identifier in the declarator.
2244 if (getLangOpts().CPlusPlus &&
2245 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2246 // Don't require a type specifier if we have the 'auto' storage class
2247 // specifier in C++98 -- we'll promote it to a type specifier.
2249 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2253 // Otherwise, if we don't consume this token, we are going to emit an
2254 // error anyway. Try to recover from various common problems. Check
2255 // to see if this was a reference to a tag name without a tag specified.
2256 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2258 // C++ doesn't need this, and isTagName doesn't take SS.
2259 if (SS == nullptr) {
2260 const char *TagName = nullptr, *FixitTagName = nullptr;
2261 tok::TokenKind TagKind = tok::unknown;
2263 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2265 case DeclSpec::TST_enum:
2266 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2267 case DeclSpec::TST_union:
2268 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2269 case DeclSpec::TST_struct:
2270 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2271 case DeclSpec::TST_interface:
2272 TagName="__interface"; FixitTagName = "__interface ";
2273 TagKind=tok::kw___interface;break;
2274 case DeclSpec::TST_class:
2275 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2279 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2280 LookupResult R(Actions, TokenName, SourceLocation(),
2281 Sema::LookupOrdinaryName);
2283 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2284 << TokenName << TagName << getLangOpts().CPlusPlus
2285 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2287 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2288 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2290 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2291 << TokenName << TagName;
2294 // Parse this as a tag as if the missing tag were present.
2295 if (TagKind == tok::kw_enum)
2296 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2298 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2299 /*EnteringContext*/ false, DSC_normal, Attrs);
2304 // Determine whether this identifier could plausibly be the name of something
2305 // being declared (with a missing type).
2306 if (!isTypeSpecifier(DSC) &&
2307 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2308 // Look ahead to the next token to try to figure out what this declaration
2309 // was supposed to be.
2310 switch (NextToken().getKind()) {
2311 case tok::l_paren: {
2312 // static x(4); // 'x' is not a type
2313 // x(int n); // 'x' is not a type
2314 // x (*p)[]; // 'x' is a type
2316 // Since we're in an error case, we can afford to perform a tentative
2317 // parse to determine which case we're in.
2318 TentativeParsingAction PA(*this);
2320 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2323 if (TPR != TPResult::False) {
2324 // The identifier is followed by a parenthesized declarator.
2325 // It's supposed to be a type.
2329 // If we're in a context where we could be declaring a constructor,
2330 // check whether this is a constructor declaration with a bogus name.
2331 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2332 IdentifierInfo *II = Tok.getIdentifierInfo();
2333 if (Actions.isCurrentClassNameTypo(II, SS)) {
2334 Diag(Loc, diag::err_constructor_bad_name)
2335 << Tok.getIdentifierInfo() << II
2336 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2337 Tok.setIdentifierInfo(II);
2348 // This looks like a variable or function declaration. The type is
2349 // probably missing. We're done parsing decl-specifiers.
2351 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2355 // This is probably supposed to be a type. This includes cases like:
2357 // struct S { unsinged : 4; };
2362 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2363 // and attempt to recover.
2365 IdentifierInfo *II = Tok.getIdentifierInfo();
2366 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2367 getLangOpts().CPlusPlus &&
2368 NextToken().is(tok::less));
2370 // The action has suggested that the type T could be used. Set that as
2371 // the type in the declaration specifiers, consume the would-be type
2372 // name token, and we're done.
2373 const char *PrevSpec;
2375 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2376 Actions.getASTContext().getPrintingPolicy());
2377 DS.SetRangeEnd(Tok.getLocation());
2379 // There may be other declaration specifiers after this.
2381 } else if (II != Tok.getIdentifierInfo()) {
2382 // If no type was suggested, the correction is to a keyword
2383 Tok.setKind(II->getTokenID());
2384 // There may be other declaration specifiers after this.
2388 // Otherwise, the action had no suggestion for us. Mark this as an error.
2389 DS.SetTypeSpecError();
2390 DS.SetRangeEnd(Tok.getLocation());
2393 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2394 // avoid rippling error messages on subsequent uses of the same type,
2395 // could be useful if #include was forgotten.
2399 /// \brief Determine the declaration specifier context from the declarator
2402 /// \param Context the declarator context, which is one of the
2403 /// Declarator::TheContext enumerator values.
2404 Parser::DeclSpecContext
2405 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2406 if (Context == Declarator::MemberContext)
2408 if (Context == Declarator::FileContext)
2409 return DSC_top_level;
2410 if (Context == Declarator::TemplateTypeArgContext)
2411 return DSC_template_type_arg;
2412 if (Context == Declarator::TrailingReturnContext)
2413 return DSC_trailing;
2414 if (Context == Declarator::AliasDeclContext ||
2415 Context == Declarator::AliasTemplateContext)
2416 return DSC_alias_declaration;
2420 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2422 /// FIXME: Simply returns an alignof() expression if the argument is a
2423 /// type. Ideally, the type should be propagated directly into Sema.
2426 /// [C11] constant-expression
2427 /// [C++0x] type-id ...[opt]
2428 /// [C++0x] assignment-expression ...[opt]
2429 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2430 SourceLocation &EllipsisLoc) {
2432 if (isTypeIdInParens()) {
2433 SourceLocation TypeLoc = Tok.getLocation();
2434 ParsedType Ty = ParseTypeName().get();
2435 SourceRange TypeRange(Start, Tok.getLocation());
2436 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2437 Ty.getAsOpaquePtr(), TypeRange);
2439 ER = ParseConstantExpression();
2441 if (getLangOpts().CPlusPlus11)
2442 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2447 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2448 /// attribute to Attrs.
2450 /// alignment-specifier:
2451 /// [C11] '_Alignas' '(' type-id ')'
2452 /// [C11] '_Alignas' '(' constant-expression ')'
2453 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2454 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2455 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2456 SourceLocation *EndLoc) {
2457 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2458 "Not an alignment-specifier!");
2460 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2461 SourceLocation KWLoc = ConsumeToken();
2463 BalancedDelimiterTracker T(*this, tok::l_paren);
2464 if (T.expectAndConsume())
2467 SourceLocation EllipsisLoc;
2468 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2469 if (ArgExpr.isInvalid()) {
2476 *EndLoc = T.getCloseLocation();
2478 ArgsVector ArgExprs;
2479 ArgExprs.push_back(ArgExpr.get());
2480 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2481 AttributeList::AS_Keyword, EllipsisLoc);
2484 /// Determine whether we're looking at something that might be a declarator
2485 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2486 /// diagnose a missing semicolon after a prior tag definition in the decl
2489 /// \return \c true if an error occurred and this can't be any kind of
2492 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2493 DeclSpecContext DSContext,
2494 LateParsedAttrList *LateAttrs) {
2495 assert(DS.hasTagDefinition() && "shouldn't call this");
2497 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2499 if (getLangOpts().CPlusPlus &&
2500 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2501 tok::annot_template_id) &&
2502 TryAnnotateCXXScopeToken(EnteringContext)) {
2503 SkipMalformedDecl();
2507 bool HasScope = Tok.is(tok::annot_cxxscope);
2508 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2509 Token AfterScope = HasScope ? NextToken() : Tok;
2511 // Determine whether the following tokens could possibly be a
2513 bool MightBeDeclarator = true;
2514 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2515 // A declarator-id can't start with 'typename'.
2516 MightBeDeclarator = false;
2517 } else if (AfterScope.is(tok::annot_template_id)) {
2518 // If we have a type expressed as a template-id, this cannot be a
2519 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2520 TemplateIdAnnotation *Annot =
2521 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2522 if (Annot->Kind == TNK_Type_template)
2523 MightBeDeclarator = false;
2524 } else if (AfterScope.is(tok::identifier)) {
2525 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2527 // These tokens cannot come after the declarator-id in a
2528 // simple-declaration, and are likely to come after a type-specifier.
2529 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2530 tok::annot_cxxscope, tok::coloncolon)) {
2531 // Missing a semicolon.
2532 MightBeDeclarator = false;
2533 } else if (HasScope) {
2534 // If the declarator-id has a scope specifier, it must redeclare a
2535 // previously-declared entity. If that's a type (and this is not a
2536 // typedef), that's an error.
2538 Actions.RestoreNestedNameSpecifierAnnotation(
2539 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2540 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2541 Sema::NameClassification Classification = Actions.ClassifyName(
2542 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2543 /*IsAddressOfOperand*/false);
2544 switch (Classification.getKind()) {
2545 case Sema::NC_Error:
2546 SkipMalformedDecl();
2549 case Sema::NC_Keyword:
2550 case Sema::NC_NestedNameSpecifier:
2551 llvm_unreachable("typo correction and nested name specifiers not "
2555 case Sema::NC_TypeTemplate:
2556 // Not a previously-declared non-type entity.
2557 MightBeDeclarator = false;
2560 case Sema::NC_Unknown:
2561 case Sema::NC_Expression:
2562 case Sema::NC_VarTemplate:
2563 case Sema::NC_FunctionTemplate:
2564 // Might be a redeclaration of a prior entity.
2570 if (MightBeDeclarator)
2573 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2574 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2575 diag::err_expected_after)
2576 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2578 // Try to recover from the typo, by dropping the tag definition and parsing
2579 // the problematic tokens as a type.
2581 // FIXME: Split the DeclSpec into pieces for the standalone
2582 // declaration and pieces for the following declaration, instead
2583 // of assuming that all the other pieces attach to new declaration,
2584 // and call ParsedFreeStandingDeclSpec as appropriate.
2585 DS.ClearTypeSpecType();
2586 ParsedTemplateInfo NotATemplate;
2587 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2591 /// ParseDeclarationSpecifiers
2592 /// declaration-specifiers: [C99 6.7]
2593 /// storage-class-specifier declaration-specifiers[opt]
2594 /// type-specifier declaration-specifiers[opt]
2595 /// [C99] function-specifier declaration-specifiers[opt]
2596 /// [C11] alignment-specifier declaration-specifiers[opt]
2597 /// [GNU] attributes declaration-specifiers[opt]
2598 /// [Clang] '__module_private__' declaration-specifiers[opt]
2599 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2601 /// storage-class-specifier: [C99 6.7.1]
2608 /// [C++11] 'thread_local'
2609 /// [C11] '_Thread_local'
2610 /// [GNU] '__thread'
2611 /// function-specifier: [C99 6.7.4]
2614 /// [C++] 'explicit'
2615 /// [OpenCL] '__kernel'
2616 /// 'friend': [C++ dcl.friend]
2617 /// 'constexpr': [C++0x dcl.constexpr]
2618 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2619 const ParsedTemplateInfo &TemplateInfo,
2621 DeclSpecContext DSContext,
2622 LateParsedAttrList *LateAttrs) {
2623 if (DS.getSourceRange().isInvalid()) {
2624 // Start the range at the current token but make the end of the range
2625 // invalid. This will make the entire range invalid unless we successfully
2627 DS.SetRangeStart(Tok.getLocation());
2628 DS.SetRangeEnd(SourceLocation());
2631 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2632 bool AttrsLastTime = false;
2633 ParsedAttributesWithRange attrs(AttrFactory);
2634 // We use Sema's policy to get bool macros right.
2635 const PrintingPolicy &Policy = Actions.getPrintingPolicy();
2637 bool isInvalid = false;
2638 bool isStorageClass = false;
2639 const char *PrevSpec = nullptr;
2640 unsigned DiagID = 0;
2642 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2643 // implementation for VS2013 uses _Atomic as an identifier for one of the
2644 // classes in <atomic>.
2646 // A typedef declaration containing _Atomic<...> is among the places where
2647 // the class is used. If we are currently parsing such a declaration, treat
2648 // the token as an identifier.
2649 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2650 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2651 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2652 Tok.setKind(tok::identifier);
2654 SourceLocation Loc = Tok.getLocation();
2656 switch (Tok.getKind()) {
2660 ProhibitAttributes(attrs);
2662 // Reject C++11 attributes that appertain to decl specifiers as
2663 // we don't support any C++11 attributes that appertain to decl
2664 // specifiers. This also conforms to what g++ 4.8 is doing.
2665 ProhibitCXX11Attributes(attrs);
2667 DS.takeAttributesFrom(attrs);
2670 // If this is not a declaration specifier token, we're done reading decl
2671 // specifiers. First verify that DeclSpec's are consistent.
2672 DS.Finish(Actions, Policy);
2676 case tok::kw_alignas:
2677 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2678 goto DoneWithDeclSpec;
2680 ProhibitAttributes(attrs);
2681 // FIXME: It would be good to recover by accepting the attributes,
2682 // but attempting to do that now would cause serious
2683 // madness in terms of diagnostics.
2685 attrs.Range = SourceRange();
2687 ParseCXX11Attributes(attrs);
2688 AttrsLastTime = true;
2691 case tok::code_completion: {
2692 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2693 if (DS.hasTypeSpecifier()) {
2694 bool AllowNonIdentifiers
2695 = (getCurScope()->getFlags() & (Scope::ControlScope |
2697 Scope::TemplateParamScope |
2698 Scope::FunctionPrototypeScope |
2699 Scope::AtCatchScope)) == 0;
2700 bool AllowNestedNameSpecifiers
2701 = DSContext == DSC_top_level ||
2702 (DSContext == DSC_class && DS.isFriendSpecified());
2704 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2705 AllowNonIdentifiers,
2706 AllowNestedNameSpecifiers);
2707 return cutOffParsing();
2710 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2711 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2712 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2713 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2714 : Sema::PCC_Template;
2715 else if (DSContext == DSC_class)
2716 CCC = Sema::PCC_Class;
2717 else if (CurParsedObjCImpl)
2718 CCC = Sema::PCC_ObjCImplementation;
2720 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2721 return cutOffParsing();
2724 case tok::coloncolon: // ::foo::bar
2725 // C++ scope specifier. Annotate and loop, or bail out on error.
2726 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2727 if (!DS.hasTypeSpecifier())
2728 DS.SetTypeSpecError();
2729 goto DoneWithDeclSpec;
2731 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2732 goto DoneWithDeclSpec;
2735 case tok::annot_cxxscope: {
2736 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2737 goto DoneWithDeclSpec;
2740 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2741 Tok.getAnnotationRange(),
2744 // We are looking for a qualified typename.
2745 Token Next = NextToken();
2746 if (Next.is(tok::annot_template_id) &&
2747 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2748 ->Kind == TNK_Type_template) {
2749 // We have a qualified template-id, e.g., N::A<int>
2751 // C++ [class.qual]p2:
2752 // In a lookup in which the constructor is an acceptable lookup
2753 // result and the nested-name-specifier nominates a class C:
2755 // - if the name specified after the
2756 // nested-name-specifier, when looked up in C, is the
2757 // injected-class-name of C (Clause 9), or
2759 // - if the name specified after the nested-name-specifier
2760 // is the same as the identifier or the
2761 // simple-template-id's template-name in the last
2762 // component of the nested-name-specifier,
2764 // the name is instead considered to name the constructor of
2767 // Thus, if the template-name is actually the constructor
2768 // name, then the code is ill-formed; this interpretation is
2769 // reinforced by the NAD status of core issue 635.
2770 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2771 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2773 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2774 if (isConstructorDeclarator(/*Unqualified*/false)) {
2775 // The user meant this to be an out-of-line constructor
2776 // definition, but template arguments are not allowed
2777 // there. Just allow this as a constructor; we'll
2778 // complain about it later.
2779 goto DoneWithDeclSpec;
2782 // The user meant this to name a type, but it actually names
2783 // a constructor with some extraneous template
2784 // arguments. Complain, then parse it as a type as the user
2786 Diag(TemplateId->TemplateNameLoc,
2787 diag::err_out_of_line_template_id_type_names_constructor)
2788 << TemplateId->Name << 0 /* template name */;
2791 DS.getTypeSpecScope() = SS;
2792 ConsumeToken(); // The C++ scope.
2793 assert(Tok.is(tok::annot_template_id) &&
2794 "ParseOptionalCXXScopeSpecifier not working");
2795 AnnotateTemplateIdTokenAsType();
2799 if (Next.is(tok::annot_typename)) {
2800 DS.getTypeSpecScope() = SS;
2801 ConsumeToken(); // The C++ scope.
2802 if (Tok.getAnnotationValue()) {
2803 ParsedType T = getTypeAnnotation(Tok);
2804 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2805 Tok.getAnnotationEndLoc(),
2806 PrevSpec, DiagID, T, Policy);
2811 DS.SetTypeSpecError();
2812 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2813 ConsumeToken(); // The typename
2816 if (Next.isNot(tok::identifier))
2817 goto DoneWithDeclSpec;
2819 // If we're in a context where the identifier could be a class name,
2820 // check whether this is a constructor declaration.
2821 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2822 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2824 if (isConstructorDeclarator(/*Unqualified*/false))
2825 goto DoneWithDeclSpec;
2827 // As noted in C++ [class.qual]p2 (cited above), when the name
2828 // of the class is qualified in a context where it could name
2829 // a constructor, its a constructor name. However, we've
2830 // looked at the declarator, and the user probably meant this
2831 // to be a type. Complain that it isn't supposed to be treated
2832 // as a type, then proceed to parse it as a type.
2833 Diag(Next.getLocation(),
2834 diag::err_out_of_line_template_id_type_names_constructor)
2835 << Next.getIdentifierInfo() << 1 /* type */;
2838 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2841 false, false, ParsedType(),
2842 /*IsCtorOrDtorName=*/false,
2843 /*NonTrivialSourceInfo=*/true);
2845 // If the referenced identifier is not a type, then this declspec is
2846 // erroneous: We already checked about that it has no type specifier, and
2847 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2850 ConsumeToken(); // Eat the scope spec so the identifier is current.
2851 ParsedAttributesWithRange Attrs(AttrFactory);
2852 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2853 if (!Attrs.empty()) {
2854 AttrsLastTime = true;
2855 attrs.takeAllFrom(Attrs);
2859 goto DoneWithDeclSpec;
2862 DS.getTypeSpecScope() = SS;
2863 ConsumeToken(); // The C++ scope.
2865 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2866 DiagID, TypeRep, Policy);
2870 DS.SetRangeEnd(Tok.getLocation());
2871 ConsumeToken(); // The typename.
2876 case tok::annot_typename: {
2877 // If we've previously seen a tag definition, we were almost surely
2878 // missing a semicolon after it.
2879 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2880 goto DoneWithDeclSpec;
2882 if (Tok.getAnnotationValue()) {
2883 ParsedType T = getTypeAnnotation(Tok);
2884 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2887 DS.SetTypeSpecError();
2892 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2893 ConsumeToken(); // The typename
2898 case tok::kw___is_signed:
2899 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2900 // typically treats it as a trait. If we see __is_signed as it appears
2901 // in libstdc++, e.g.,
2903 // static const bool __is_signed;
2905 // then treat __is_signed as an identifier rather than as a keyword.
2906 if (DS.getTypeSpecType() == TST_bool &&
2907 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2908 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2909 TryKeywordIdentFallback(true);
2911 // We're done with the declaration-specifiers.
2912 goto DoneWithDeclSpec;
2915 case tok::kw___super:
2916 case tok::kw_decltype:
2917 case tok::identifier: {
2918 // This identifier can only be a typedef name if we haven't already seen
2919 // a type-specifier. Without this check we misparse:
2920 // typedef int X; struct Y { short X; }; as 'short int'.
2921 if (DS.hasTypeSpecifier())
2922 goto DoneWithDeclSpec;
2924 // In C++, check to see if this is a scope specifier like foo::bar::, if
2925 // so handle it as such. This is important for ctor parsing.
2926 if (getLangOpts().CPlusPlus) {
2927 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2928 DS.SetTypeSpecError();
2929 goto DoneWithDeclSpec;
2931 if (!Tok.is(tok::identifier))
2935 // Check for need to substitute AltiVec keyword tokens.
2936 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2939 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2940 // allow the use of a typedef name as a type specifier.
2941 if (DS.isTypeAltiVecVector())
2942 goto DoneWithDeclSpec;
2944 if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
2945 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
2947 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2948 DiagID, TypeRep, Policy);
2952 DS.SetRangeEnd(Loc);
2957 ParsedType TypeRep =
2958 Actions.getTypeName(*Tok.getIdentifierInfo(),
2959 Tok.getLocation(), getCurScope());
2961 // MSVC: If we weren't able to parse a default template argument, and it's
2962 // just a simple identifier, create a DependentNameType. This will allow
2963 // us to defer the name lookup to template instantiation time, as long we
2964 // forge a NestedNameSpecifier for the current context.
2965 if (!TypeRep && DSContext == DSC_template_type_arg &&
2966 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) {
2967 TypeRep = Actions.ActOnDelayedDefaultTemplateArg(
2968 *Tok.getIdentifierInfo(), Tok.getLocation());
2971 // If this is not a typedef name, don't parse it as part of the declspec,
2972 // it must be an implicit int or an error.
2974 ParsedAttributesWithRange Attrs(AttrFactory);
2975 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
2976 if (!Attrs.empty()) {
2977 AttrsLastTime = true;
2978 attrs.takeAllFrom(Attrs);
2982 goto DoneWithDeclSpec;
2985 // If we're in a context where the identifier could be a class name,
2986 // check whether this is a constructor declaration.
2987 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2988 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2989 isConstructorDeclarator(/*Unqualified*/true))
2990 goto DoneWithDeclSpec;
2992 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2993 DiagID, TypeRep, Policy);
2997 DS.SetRangeEnd(Tok.getLocation());
2998 ConsumeToken(); // The identifier
3000 // Objective-C supports type arguments and protocol references
3001 // following an Objective-C object or object pointer
3002 // type. Handle either one of them.
3003 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3004 SourceLocation NewEndLoc;
3005 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3006 Loc, TypeRep, /*consumeLastToken=*/true,
3008 if (NewTypeRep.isUsable()) {
3009 DS.UpdateTypeRep(NewTypeRep.get());
3010 DS.SetRangeEnd(NewEndLoc);
3014 // Need to support trailing type qualifiers (e.g. "id<p> const").
3015 // If a type specifier follows, it will be diagnosed elsewhere.
3020 case tok::annot_template_id: {
3021 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3022 if (TemplateId->Kind != TNK_Type_template) {
3023 // This template-id does not refer to a type name, so we're
3024 // done with the type-specifiers.
3025 goto DoneWithDeclSpec;
3028 // If we're in a context where the template-id could be a
3029 // constructor name or specialization, check whether this is a
3030 // constructor declaration.
3031 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3032 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3033 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3034 goto DoneWithDeclSpec;
3036 // Turn the template-id annotation token into a type annotation
3037 // token, then try again to parse it as a type-specifier.
3038 AnnotateTemplateIdTokenAsType();
3042 // GNU attributes support.
3043 case tok::kw___attribute:
3044 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3047 // Microsoft declspec support.
3048 case tok::kw___declspec:
3049 ParseMicrosoftDeclSpecs(DS.getAttributes());
3052 // Microsoft single token adornments.
3053 case tok::kw___forceinline: {
3054 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3055 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3056 SourceLocation AttrNameLoc = Tok.getLocation();
3057 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3058 nullptr, 0, AttributeList::AS_Keyword);
3062 case tok::kw___sptr:
3063 case tok::kw___uptr:
3064 case tok::kw___ptr64:
3065 case tok::kw___ptr32:
3067 case tok::kw___cdecl:
3068 case tok::kw___stdcall:
3069 case tok::kw___fastcall:
3070 case tok::kw___thiscall:
3071 case tok::kw___vectorcall:
3072 case tok::kw___unaligned:
3073 ParseMicrosoftTypeAttributes(DS.getAttributes());
3076 // Borland single token adornments.
3077 case tok::kw___pascal:
3078 ParseBorlandTypeAttributes(DS.getAttributes());
3081 // OpenCL single token adornments.
3082 case tok::kw___kernel:
3083 ParseOpenCLAttributes(DS.getAttributes());
3086 // Nullability type specifiers.
3087 case tok::kw__Nonnull:
3088 case tok::kw__Nullable:
3089 case tok::kw__Null_unspecified:
3090 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3093 // Objective-C 'kindof' types.
3094 case tok::kw___kindof:
3095 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3096 nullptr, 0, AttributeList::AS_Keyword);
3097 (void)ConsumeToken();
3100 // storage-class-specifier
3101 case tok::kw_typedef:
3102 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3103 PrevSpec, DiagID, Policy);
3104 isStorageClass = true;
3106 case tok::kw_extern:
3107 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3108 Diag(Tok, diag::ext_thread_before) << "extern";
3109 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3110 PrevSpec, DiagID, Policy);
3111 isStorageClass = true;
3113 case tok::kw___private_extern__:
3114 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3115 Loc, PrevSpec, DiagID, Policy);
3116 isStorageClass = true;
3118 case tok::kw_static:
3119 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3120 Diag(Tok, diag::ext_thread_before) << "static";
3121 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3122 PrevSpec, DiagID, Policy);
3123 isStorageClass = true;
3126 if (getLangOpts().CPlusPlus11) {
3127 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3128 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3129 PrevSpec, DiagID, Policy);
3131 Diag(Tok, diag::ext_auto_storage_class)
3132 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3134 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3137 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3138 PrevSpec, DiagID, Policy);
3139 isStorageClass = true;
3141 case tok::kw___auto_type:
3142 Diag(Tok, diag::ext_auto_type);
3143 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3146 case tok::kw_register:
3147 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3148 PrevSpec, DiagID, Policy);
3149 isStorageClass = true;
3151 case tok::kw_mutable:
3152 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3153 PrevSpec, DiagID, Policy);
3154 isStorageClass = true;
3156 case tok::kw___thread:
3157 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3159 isStorageClass = true;
3161 case tok::kw_thread_local:
3162 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3165 case tok::kw__Thread_local:
3166 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3167 Loc, PrevSpec, DiagID);
3168 isStorageClass = true;
3171 // function-specifier
3172 case tok::kw_inline:
3173 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3175 case tok::kw_virtual:
3176 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3178 case tok::kw_explicit:
3179 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3181 case tok::kw__Noreturn:
3182 if (!getLangOpts().C11)
3183 Diag(Loc, diag::ext_c11_noreturn);
3184 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3187 // alignment-specifier
3188 case tok::kw__Alignas:
3189 if (!getLangOpts().C11)
3190 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3191 ParseAlignmentSpecifier(DS.getAttributes());
3195 case tok::kw_friend:
3196 if (DSContext == DSC_class)
3197 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3199 PrevSpec = ""; // not actually used by the diagnostic
3200 DiagID = diag::err_friend_invalid_in_context;
3206 case tok::kw___module_private__:
3207 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3211 case tok::kw_constexpr:
3212 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3216 case tok::kw_concept:
3217 isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3222 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3226 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3227 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3230 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3233 case tok::kw___int64:
3234 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3237 case tok::kw_signed:
3238 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3241 case tok::kw_unsigned:
3242 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3245 case tok::kw__Complex:
3246 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3249 case tok::kw__Imaginary:
3250 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3254 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3258 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3262 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3265 case tok::kw___int128:
3266 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3270 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3274 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3277 case tok::kw_double:
3278 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3281 case tok::kw_wchar_t:
3282 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3285 case tok::kw_char16_t:
3286 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3289 case tok::kw_char32_t:
3290 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3295 if (Tok.is(tok::kw_bool) &&
3296 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3297 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3298 PrevSpec = ""; // Not used by the diagnostic.
3299 DiagID = diag::err_bool_redeclaration;
3300 // For better error recovery.
3301 Tok.setKind(tok::identifier);
3304 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3308 case tok::kw__Decimal32:
3309 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3312 case tok::kw__Decimal64:
3313 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3316 case tok::kw__Decimal128:
3317 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3320 case tok::kw___vector:
3321 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3323 case tok::kw___pixel:
3324 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3326 case tok::kw___bool:
3327 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3330 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3331 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3332 // support the "pipe" word as identifier.
3333 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3334 goto DoneWithDeclSpec;
3336 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3338 case tok::kw___unknown_anytype:
3339 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3340 PrevSpec, DiagID, Policy);
3345 case tok::kw_struct:
3346 case tok::kw___interface:
3347 case tok::kw_union: {
3348 tok::TokenKind Kind = Tok.getKind();
3351 // These are attributes following class specifiers.
3352 // To produce better diagnostic, we parse them when
3353 // parsing class specifier.
3354 ParsedAttributesWithRange Attributes(AttrFactory);
3355 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3356 EnteringContext, DSContext, Attributes);
3358 // If there are attributes following class specifier,
3359 // take them over and handle them here.
3360 if (!Attributes.empty()) {
3361 AttrsLastTime = true;
3362 attrs.takeAllFrom(Attributes);
3370 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3375 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3378 case tok::kw_volatile:
3379 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3382 case tok::kw_restrict:
3383 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3387 // C++ typename-specifier:
3388 case tok::kw_typename:
3389 if (TryAnnotateTypeOrScopeToken()) {
3390 DS.SetTypeSpecError();
3391 goto DoneWithDeclSpec;
3393 if (!Tok.is(tok::kw_typename))
3397 // GNU typeof support.
3398 case tok::kw_typeof:
3399 ParseTypeofSpecifier(DS);
3402 case tok::annot_decltype:
3403 ParseDecltypeSpecifier(DS);
3406 case tok::kw___underlying_type:
3407 ParseUnderlyingTypeSpecifier(DS);
3410 case tok::kw__Atomic:
3412 // If the _Atomic keyword is immediately followed by a left parenthesis,
3413 // it is interpreted as a type specifier (with a type name), not as a
3415 if (NextToken().is(tok::l_paren)) {
3416 ParseAtomicSpecifier(DS);
3419 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3423 // OpenCL qualifiers:
3424 case tok::kw___generic:
3425 // generic address space is introduced only in OpenCL v2.0
3426 // see OpenCL C Spec v2.0 s6.5.5
3427 if (Actions.getLangOpts().OpenCLVersion < 200) {
3428 DiagID = diag::err_opencl_unknown_type_specifier;
3429 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3433 case tok::kw___private:
3434 case tok::kw___global:
3435 case tok::kw___local:
3436 case tok::kw___constant:
3437 case tok::kw___read_only:
3438 case tok::kw___write_only:
3439 case tok::kw___read_write:
3440 ParseOpenCLQualifiers(DS.getAttributes());
3444 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3445 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3446 // but we support it.
3447 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3448 goto DoneWithDeclSpec;
3450 SourceLocation StartLoc = Tok.getLocation();
3451 SourceLocation EndLoc;
3452 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3453 if (Type.isUsable()) {
3454 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3455 PrevSpec, DiagID, Type.get(),
3456 Actions.getASTContext().getPrintingPolicy()))
3457 Diag(StartLoc, DiagID) << PrevSpec;
3459 DS.SetRangeEnd(EndLoc);
3461 DS.SetTypeSpecError();
3464 // Need to support trailing type qualifiers (e.g. "id<p> const").
3465 // If a type specifier follows, it will be diagnosed elsewhere.
3468 // If the specifier wasn't legal, issue a diagnostic.
3470 assert(PrevSpec && "Method did not return previous specifier!");
3473 if (DiagID == diag::ext_duplicate_declspec)
3475 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3476 else if (DiagID == diag::err_opencl_unknown_type_specifier)
3477 Diag(Tok, DiagID) << PrevSpec << isStorageClass;
3479 Diag(Tok, DiagID) << PrevSpec;
3482 DS.SetRangeEnd(Tok.getLocation());
3483 if (DiagID != diag::err_bool_redeclaration)
3486 AttrsLastTime = false;
3490 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3493 /// struct-declaration:
3494 /// specifier-qualifier-list struct-declarator-list
3495 /// [GNU] __extension__ struct-declaration
3496 /// [GNU] specifier-qualifier-list
3497 /// struct-declarator-list:
3498 /// struct-declarator
3499 /// struct-declarator-list ',' struct-declarator
3500 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3501 /// struct-declarator:
3503 /// [GNU] declarator attributes[opt]
3504 /// declarator[opt] ':' constant-expression
3505 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3507 void Parser::ParseStructDeclaration(
3508 ParsingDeclSpec &DS,
3509 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3511 if (Tok.is(tok::kw___extension__)) {
3512 // __extension__ silences extension warnings in the subexpression.
3513 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3515 return ParseStructDeclaration(DS, FieldsCallback);
3518 // Parse the common specifier-qualifiers-list piece.
3519 ParseSpecifierQualifierList(DS);
3521 // If there are no declarators, this is a free-standing declaration
3522 // specifier. Let the actions module cope with it.
3523 if (Tok.is(tok::semi)) {
3524 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3526 DS.complete(TheDecl);
3530 // Read struct-declarators until we find the semicolon.
3531 bool FirstDeclarator = true;
3532 SourceLocation CommaLoc;
3534 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3535 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3537 // Attributes are only allowed here on successive declarators.
3538 if (!FirstDeclarator)
3539 MaybeParseGNUAttributes(DeclaratorInfo.D);
3541 /// struct-declarator: declarator
3542 /// struct-declarator: declarator[opt] ':' constant-expression
3543 if (Tok.isNot(tok::colon)) {
3544 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3545 ColonProtectionRAIIObject X(*this);
3546 ParseDeclarator(DeclaratorInfo.D);
3548 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3550 if (TryConsumeToken(tok::colon)) {
3551 ExprResult Res(ParseConstantExpression());
3552 if (Res.isInvalid())
3553 SkipUntil(tok::semi, StopBeforeMatch);
3555 DeclaratorInfo.BitfieldSize = Res.get();
3558 // If attributes exist after the declarator, parse them.
3559 MaybeParseGNUAttributes(DeclaratorInfo.D);
3561 // We're done with this declarator; invoke the callback.
3562 FieldsCallback(DeclaratorInfo);
3564 // If we don't have a comma, it is either the end of the list (a ';')
3565 // or an error, bail out.
3566 if (!TryConsumeToken(tok::comma, CommaLoc))
3569 FirstDeclarator = false;
3573 /// ParseStructUnionBody
3574 /// struct-contents:
3575 /// struct-declaration-list
3577 /// [GNU] "struct-declaration-list" without terminatoring ';'
3578 /// struct-declaration-list:
3579 /// struct-declaration
3580 /// struct-declaration-list struct-declaration
3581 /// [OBC] '@' 'defs' '(' class-name ')'
3583 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3584 unsigned TagType, Decl *TagDecl) {
3585 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3586 "parsing struct/union body");
3587 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3589 BalancedDelimiterTracker T(*this, tok::l_brace);
3590 if (T.consumeOpen())
3593 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3594 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3596 SmallVector<Decl *, 32> FieldDecls;
3598 // While we still have something to read, read the declarations in the struct.
3599 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3600 Tok.isNot(tok::eof)) {
3601 // Each iteration of this loop reads one struct-declaration.
3603 // Check for extraneous top-level semicolon.
3604 if (Tok.is(tok::semi)) {
3605 ConsumeExtraSemi(InsideStruct, TagType);
3609 // Parse _Static_assert declaration.
3610 if (Tok.is(tok::kw__Static_assert)) {
3611 SourceLocation DeclEnd;
3612 ParseStaticAssertDeclaration(DeclEnd);
3616 if (Tok.is(tok::annot_pragma_pack)) {
3621 if (Tok.is(tok::annot_pragma_align)) {
3622 HandlePragmaAlign();
3626 if (Tok.is(tok::annot_pragma_openmp)) {
3627 // Result can be ignored, because it must be always empty.
3628 auto Res = ParseOpenMPDeclarativeDirective();
3630 // Silence possible warnings.
3634 if (!Tok.is(tok::at)) {
3635 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3636 // Install the declarator into the current TagDecl.
3638 Actions.ActOnField(getCurScope(), TagDecl,
3639 FD.D.getDeclSpec().getSourceRange().getBegin(),
3640 FD.D, FD.BitfieldSize);
3641 FieldDecls.push_back(Field);
3645 // Parse all the comma separated declarators.
3646 ParsingDeclSpec DS(*this);
3647 ParseStructDeclaration(DS, CFieldCallback);
3648 } else { // Handle @defs
3650 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3651 Diag(Tok, diag::err_unexpected_at);
3652 SkipUntil(tok::semi);
3656 ExpectAndConsume(tok::l_paren);
3657 if (!Tok.is(tok::identifier)) {
3658 Diag(Tok, diag::err_expected) << tok::identifier;
3659 SkipUntil(tok::semi);
3662 SmallVector<Decl *, 16> Fields;
3663 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3664 Tok.getIdentifierInfo(), Fields);
3665 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3667 ExpectAndConsume(tok::r_paren);
3670 if (TryConsumeToken(tok::semi))
3673 if (Tok.is(tok::r_brace)) {
3674 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3678 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3679 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3680 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3681 // If we stopped at a ';', eat it.
3682 TryConsumeToken(tok::semi);
3687 ParsedAttributes attrs(AttrFactory);
3688 // If attributes exist after struct contents, parse them.
3689 MaybeParseGNUAttributes(attrs);
3691 Actions.ActOnFields(getCurScope(),
3692 RecordLoc, TagDecl, FieldDecls,
3693 T.getOpenLocation(), T.getCloseLocation(),
3696 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3697 T.getCloseLocation());
3700 /// ParseEnumSpecifier
3701 /// enum-specifier: [C99 6.7.2.2]
3702 /// 'enum' identifier[opt] '{' enumerator-list '}'
3703 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3704 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3705 /// '}' attributes[opt]
3706 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3708 /// 'enum' identifier
3709 /// [GNU] 'enum' attributes[opt] identifier
3711 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3712 /// [C++11] enum-head '{' enumerator-list ',' '}'
3714 /// enum-head: [C++11]
3715 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3716 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3717 /// identifier enum-base[opt]
3719 /// enum-key: [C++11]
3724 /// enum-base: [C++11]
3725 /// ':' type-specifier-seq
3727 /// [C++] elaborated-type-specifier:
3728 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3730 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3731 const ParsedTemplateInfo &TemplateInfo,
3732 AccessSpecifier AS, DeclSpecContext DSC) {
3733 // Parse the tag portion of this.
3734 if (Tok.is(tok::code_completion)) {
3735 // Code completion for an enum name.
3736 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3737 return cutOffParsing();
3740 // If attributes exist after tag, parse them.
3741 ParsedAttributesWithRange attrs(AttrFactory);
3742 MaybeParseGNUAttributes(attrs);
3743 MaybeParseCXX11Attributes(attrs);
3744 MaybeParseMicrosoftDeclSpecs(attrs);
3746 SourceLocation ScopedEnumKWLoc;
3747 bool IsScopedUsingClassTag = false;
3749 // In C++11, recognize 'enum class' and 'enum struct'.
3750 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
3751 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3752 : diag::ext_scoped_enum);
3753 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3754 ScopedEnumKWLoc = ConsumeToken();
3756 // Attributes are not allowed between these keywords. Diagnose,
3757 // but then just treat them like they appeared in the right place.
3758 ProhibitAttributes(attrs);
3760 // They are allowed afterwards, though.
3761 MaybeParseGNUAttributes(attrs);
3762 MaybeParseCXX11Attributes(attrs);
3763 MaybeParseMicrosoftDeclSpecs(attrs);
3766 // C++11 [temp.explicit]p12:
3767 // The usual access controls do not apply to names used to specify
3768 // explicit instantiations.
3769 // We extend this to also cover explicit specializations. Note that
3770 // we don't suppress if this turns out to be an elaborated type
3772 bool shouldDelayDiagsInTag =
3773 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3774 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3775 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3777 // Enum definitions should not be parsed in a trailing-return-type.
3778 bool AllowDeclaration = DSC != DSC_trailing;
3780 bool AllowFixedUnderlyingType = AllowDeclaration &&
3781 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3782 getLangOpts().ObjC2);
3784 CXXScopeSpec &SS = DS.getTypeSpecScope();
3785 if (getLangOpts().CPlusPlus) {
3786 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3787 // if a fixed underlying type is allowed.
3788 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3791 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(),
3792 /*EnteringContext=*/true))
3795 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
3796 Diag(Tok, diag::err_expected) << tok::identifier;
3797 if (Tok.isNot(tok::l_brace)) {
3798 // Has no name and is not a definition.
3799 // Skip the rest of this declarator, up until the comma or semicolon.
3800 SkipUntil(tok::comma, StopAtSemi);
3808 // Must have either 'enum name' or 'enum {...}'.
3809 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3810 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3811 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
3813 // Skip the rest of this declarator, up until the comma or semicolon.
3814 SkipUntil(tok::comma, StopAtSemi);
3818 // If an identifier is present, consume and remember it.
3819 IdentifierInfo *Name = nullptr;
3820 SourceLocation NameLoc;
3821 if (Tok.is(tok::identifier)) {
3822 Name = Tok.getIdentifierInfo();
3823 NameLoc = ConsumeToken();
3826 if (!Name && ScopedEnumKWLoc.isValid()) {
3827 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3828 // declaration of a scoped enumeration.
3829 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3830 ScopedEnumKWLoc = SourceLocation();
3831 IsScopedUsingClassTag = false;
3834 // Okay, end the suppression area. We'll decide whether to emit the
3835 // diagnostics in a second.
3836 if (shouldDelayDiagsInTag)
3837 diagsFromTag.done();
3839 TypeResult BaseType;
3841 // Parse the fixed underlying type.
3842 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3843 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3844 bool PossibleBitfield = false;
3845 if (CanBeBitfield) {
3846 // If we're in class scope, this can either be an enum declaration with
3847 // an underlying type, or a declaration of a bitfield member. We try to
3848 // use a simple disambiguation scheme first to catch the common cases
3849 // (integer literal, sizeof); if it's still ambiguous, we then consider
3850 // anything that's a simple-type-specifier followed by '(' as an
3851 // expression. This suffices because function types are not valid
3852 // underlying types anyway.
3853 EnterExpressionEvaluationContext Unevaluated(Actions,
3854 Sema::ConstantEvaluated);
3855 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3856 // If the next token starts an expression, we know we're parsing a
3857 // bit-field. This is the common case.
3858 if (TPR == TPResult::True)
3859 PossibleBitfield = true;
3860 // If the next token starts a type-specifier-seq, it may be either a
3861 // a fixed underlying type or the start of a function-style cast in C++;
3862 // lookahead one more token to see if it's obvious that we have a
3863 // fixed underlying type.
3864 else if (TPR == TPResult::False &&
3865 GetLookAheadToken(2).getKind() == tok::semi) {
3869 // We have the start of a type-specifier-seq, so we have to perform
3870 // tentative parsing to determine whether we have an expression or a
3872 TentativeParsingAction TPA(*this);
3877 // If we see a type specifier followed by an open-brace, we have an
3878 // ambiguity between an underlying type and a C++11 braced
3879 // function-style cast. Resolve this by always treating it as an
3881 // FIXME: The standard is not entirely clear on how to disambiguate in
3883 if ((getLangOpts().CPlusPlus &&
3884 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
3885 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3886 // We'll parse this as a bitfield later.
3887 PossibleBitfield = true;
3890 // We have a type-specifier-seq.
3899 if (!PossibleBitfield) {
3901 BaseType = ParseTypeName(&Range);
3903 if (getLangOpts().CPlusPlus11) {
3904 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3905 } else if (!getLangOpts().ObjC2) {
3906 if (getLangOpts().CPlusPlus)
3907 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3909 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3914 // There are four options here. If we have 'friend enum foo;' then this is a
3915 // friend declaration, and cannot have an accompanying definition. If we have
3916 // 'enum foo;', then this is a forward declaration. If we have
3917 // 'enum foo {...' then this is a definition. Otherwise we have something
3918 // like 'enum foo xyz', a reference.
3920 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3921 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3922 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3924 Sema::TagUseKind TUK;
3925 if (!AllowDeclaration) {
3926 TUK = Sema::TUK_Reference;
3927 } else if (Tok.is(tok::l_brace)) {
3928 if (DS.isFriendSpecified()) {
3929 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3930 << SourceRange(DS.getFriendSpecLoc());
3932 SkipUntil(tok::r_brace, StopAtSemi);
3933 TUK = Sema::TUK_Friend;
3935 TUK = Sema::TUK_Definition;
3937 } else if (!isTypeSpecifier(DSC) &&
3938 (Tok.is(tok::semi) ||
3939 (Tok.isAtStartOfLine() &&
3940 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3941 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3942 if (Tok.isNot(tok::semi)) {
3943 // A semicolon was missing after this declaration. Diagnose and recover.
3944 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
3946 Tok.setKind(tok::semi);
3949 TUK = Sema::TUK_Reference;
3952 // If this is an elaborated type specifier, and we delayed
3953 // diagnostics before, just merge them into the current pool.
3954 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3955 diagsFromTag.redelay();
3958 MultiTemplateParamsArg TParams;
3959 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3960 TUK != Sema::TUK_Reference) {
3961 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3962 // Skip the rest of this declarator, up until the comma or semicolon.
3963 Diag(Tok, diag::err_enum_template);
3964 SkipUntil(tok::comma, StopAtSemi);
3968 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3969 // Enumerations can't be explicitly instantiated.
3970 DS.SetTypeSpecError();
3971 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3975 assert(TemplateInfo.TemplateParams && "no template parameters");
3976 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3977 TemplateInfo.TemplateParams->size());
3980 if (TUK == Sema::TUK_Reference)
3981 ProhibitAttributes(attrs);
3983 if (!Name && TUK != Sema::TUK_Definition) {
3984 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3986 // Skip the rest of this declarator, up until the comma or semicolon.
3987 SkipUntil(tok::comma, StopAtSemi);
3991 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
3993 Sema::SkipBodyInfo SkipBody;
3994 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
3995 NextToken().is(tok::identifier))
3996 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
3997 NextToken().getIdentifierInfo(),
3998 NextToken().getLocation());
4001 bool IsDependent = false;
4002 const char *PrevSpec = nullptr;
4004 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
4005 StartLoc, SS, Name, NameLoc, attrs.getList(),
4006 AS, DS.getModulePrivateSpecLoc(), TParams,
4007 Owned, IsDependent, ScopedEnumKWLoc,
4008 IsScopedUsingClassTag, BaseType,
4009 DSC == DSC_type_specifier, &SkipBody);
4011 if (SkipBody.ShouldSkip) {
4012 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4014 BalancedDelimiterTracker T(*this, tok::l_brace);
4018 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4019 NameLoc.isValid() ? NameLoc : StartLoc,
4020 PrevSpec, DiagID, TagDecl, Owned,
4021 Actions.getASTContext().getPrintingPolicy()))
4022 Diag(StartLoc, DiagID) << PrevSpec;
4027 // This enum has a dependent nested-name-specifier. Handle it as a
4030 DS.SetTypeSpecError();
4031 Diag(Tok, diag::err_expected_type_name_after_typename);
4035 TypeResult Type = Actions.ActOnDependentTag(
4036 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4037 if (Type.isInvalid()) {
4038 DS.SetTypeSpecError();
4042 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4043 NameLoc.isValid() ? NameLoc : StartLoc,
4044 PrevSpec, DiagID, Type.get(),
4045 Actions.getASTContext().getPrintingPolicy()))
4046 Diag(StartLoc, DiagID) << PrevSpec;
4052 // The action failed to produce an enumeration tag. If this is a
4053 // definition, consume the entire definition.
4054 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4056 SkipUntil(tok::r_brace, StopAtSemi);
4059 DS.SetTypeSpecError();
4063 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
4064 ParseEnumBody(StartLoc, TagDecl);
4066 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4067 NameLoc.isValid() ? NameLoc : StartLoc,
4068 PrevSpec, DiagID, TagDecl, Owned,
4069 Actions.getASTContext().getPrintingPolicy()))
4070 Diag(StartLoc, DiagID) << PrevSpec;
4073 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4074 /// enumerator-list:
4076 /// enumerator-list ',' enumerator
4078 /// enumeration-constant attributes[opt]
4079 /// enumeration-constant attributes[opt] '=' constant-expression
4080 /// enumeration-constant:
4083 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4084 // Enter the scope of the enum body and start the definition.
4085 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4086 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4088 BalancedDelimiterTracker T(*this, tok::l_brace);
4091 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4092 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4093 Diag(Tok, diag::error_empty_enum);
4095 SmallVector<Decl *, 32> EnumConstantDecls;
4096 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4098 Decl *LastEnumConstDecl = nullptr;
4100 // Parse the enumerator-list.
4101 while (Tok.isNot(tok::r_brace)) {
4102 // Parse enumerator. If failed, try skipping till the start of the next
4103 // enumerator definition.
4104 if (Tok.isNot(tok::identifier)) {
4105 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4106 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4107 TryConsumeToken(tok::comma))
4111 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4112 SourceLocation IdentLoc = ConsumeToken();
4114 // If attributes exist after the enumerator, parse them.
4115 ParsedAttributesWithRange attrs(AttrFactory);
4116 MaybeParseGNUAttributes(attrs);
4117 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4118 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4119 if (!getLangOpts().CPlusPlus1z)
4120 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4121 << 1 /*enumerator*/;
4122 ParseCXX11Attributes(attrs);
4125 SourceLocation EqualLoc;
4126 ExprResult AssignedVal;
4127 EnumAvailabilityDiags.emplace_back(*this);
4129 if (TryConsumeToken(tok::equal, EqualLoc)) {
4130 AssignedVal = ParseConstantExpression();
4131 if (AssignedVal.isInvalid())
4132 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4135 // Install the enumerator constant into EnumDecl.
4136 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4139 attrs.getList(), EqualLoc,
4141 EnumAvailabilityDiags.back().done();
4143 EnumConstantDecls.push_back(EnumConstDecl);
4144 LastEnumConstDecl = EnumConstDecl;
4146 if (Tok.is(tok::identifier)) {
4147 // We're missing a comma between enumerators.
4148 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
4149 Diag(Loc, diag::err_enumerator_list_missing_comma)
4150 << FixItHint::CreateInsertion(Loc, ", ");
4154 // Emumerator definition must be finished, only comma or r_brace are
4156 SourceLocation CommaLoc;
4157 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4158 if (EqualLoc.isValid())
4159 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4162 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4163 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4164 if (TryConsumeToken(tok::comma, CommaLoc))
4171 // If comma is followed by r_brace, emit appropriate warning.
4172 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4173 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4174 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4175 diag::ext_enumerator_list_comma_cxx :
4176 diag::ext_enumerator_list_comma_c)
4177 << FixItHint::CreateRemoval(CommaLoc);
4178 else if (getLangOpts().CPlusPlus11)
4179 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4180 << FixItHint::CreateRemoval(CommaLoc);
4188 // If attributes exist after the identifier list, parse them.
4189 ParsedAttributes attrs(AttrFactory);
4190 MaybeParseGNUAttributes(attrs);
4192 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
4193 EnumDecl, EnumConstantDecls,
4197 // Now handle enum constant availability diagnostics.
4198 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4199 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4200 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4201 EnumAvailabilityDiags[i].redelay();
4202 PD.complete(EnumConstantDecls[i]);
4206 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
4207 T.getCloseLocation());
4209 // The next token must be valid after an enum definition. If not, a ';'
4210 // was probably forgotten.
4211 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4212 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4213 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4214 // Push this token back into the preprocessor and change our current token
4215 // to ';' so that the rest of the code recovers as though there were an
4216 // ';' after the definition.
4218 Tok.setKind(tok::semi);
4222 /// isTypeSpecifierQualifier - Return true if the current token could be the
4223 /// start of a type-qualifier-list.
4224 bool Parser::isTypeQualifier() const {
4225 switch (Tok.getKind()) {
4226 default: return false;
4229 case tok::kw_volatile:
4230 case tok::kw_restrict:
4231 case tok::kw___private:
4232 case tok::kw___local:
4233 case tok::kw___global:
4234 case tok::kw___constant:
4235 case tok::kw___generic:
4236 case tok::kw___read_only:
4237 case tok::kw___read_write:
4238 case tok::kw___write_only:
4243 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4244 /// is definitely a type-specifier. Return false if it isn't part of a type
4245 /// specifier or if we're not sure.
4246 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4247 switch (Tok.getKind()) {
4248 default: return false;
4252 case tok::kw___int64:
4253 case tok::kw___int128:
4254 case tok::kw_signed:
4255 case tok::kw_unsigned:
4256 case tok::kw__Complex:
4257 case tok::kw__Imaginary:
4260 case tok::kw_wchar_t:
4261 case tok::kw_char16_t:
4262 case tok::kw_char32_t:
4266 case tok::kw_double:
4269 case tok::kw__Decimal32:
4270 case tok::kw__Decimal64:
4271 case tok::kw__Decimal128:
4272 case tok::kw___vector:
4274 // struct-or-union-specifier (C99) or class-specifier (C++)
4276 case tok::kw_struct:
4277 case tok::kw___interface:
4283 case tok::annot_typename:
4288 /// isTypeSpecifierQualifier - Return true if the current token could be the
4289 /// start of a specifier-qualifier-list.
4290 bool Parser::isTypeSpecifierQualifier() {
4291 switch (Tok.getKind()) {
4292 default: return false;
4294 case tok::identifier: // foo::bar
4295 if (TryAltiVecVectorToken())
4298 case tok::kw_typename: // typename T::type
4299 // Annotate typenames and C++ scope specifiers. If we get one, just
4300 // recurse to handle whatever we get.
4301 if (TryAnnotateTypeOrScopeToken())
4303 if (Tok.is(tok::identifier))
4305 return isTypeSpecifierQualifier();
4307 case tok::coloncolon: // ::foo::bar
4308 if (NextToken().is(tok::kw_new) || // ::new
4309 NextToken().is(tok::kw_delete)) // ::delete
4312 if (TryAnnotateTypeOrScopeToken())
4314 return isTypeSpecifierQualifier();
4316 // GNU attributes support.
4317 case tok::kw___attribute:
4318 // GNU typeof support.
4319 case tok::kw_typeof:
4324 case tok::kw___int64:
4325 case tok::kw___int128:
4326 case tok::kw_signed:
4327 case tok::kw_unsigned:
4328 case tok::kw__Complex:
4329 case tok::kw__Imaginary:
4332 case tok::kw_wchar_t:
4333 case tok::kw_char16_t:
4334 case tok::kw_char32_t:
4338 case tok::kw_double:
4341 case tok::kw__Decimal32:
4342 case tok::kw__Decimal64:
4343 case tok::kw__Decimal128:
4344 case tok::kw___vector:
4346 // struct-or-union-specifier (C99) or class-specifier (C++)
4348 case tok::kw_struct:
4349 case tok::kw___interface:
4356 case tok::kw_volatile:
4357 case tok::kw_restrict:
4359 // Debugger support.
4360 case tok::kw___unknown_anytype:
4363 case tok::annot_typename:
4366 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4368 return getLangOpts().ObjC1;
4370 case tok::kw___cdecl:
4371 case tok::kw___stdcall:
4372 case tok::kw___fastcall:
4373 case tok::kw___thiscall:
4374 case tok::kw___vectorcall:
4376 case tok::kw___ptr64:
4377 case tok::kw___ptr32:
4378 case tok::kw___pascal:
4379 case tok::kw___unaligned:
4381 case tok::kw__Nonnull:
4382 case tok::kw__Nullable:
4383 case tok::kw__Null_unspecified:
4385 case tok::kw___kindof:
4387 case tok::kw___private:
4388 case tok::kw___local:
4389 case tok::kw___global:
4390 case tok::kw___constant:
4391 case tok::kw___generic:
4392 case tok::kw___read_only:
4393 case tok::kw___read_write:
4394 case tok::kw___write_only:
4399 case tok::kw__Atomic:
4404 /// isDeclarationSpecifier() - Return true if the current token is part of a
4405 /// declaration specifier.
4407 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4408 /// this check is to disambiguate between an expression and a declaration.
4409 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4410 switch (Tok.getKind()) {
4411 default: return false;
4414 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4416 case tok::identifier: // foo::bar
4417 // Unfortunate hack to support "Class.factoryMethod" notation.
4418 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4420 if (TryAltiVecVectorToken())
4423 case tok::kw_decltype: // decltype(T())::type
4424 case tok::kw_typename: // typename T::type
4425 // Annotate typenames and C++ scope specifiers. If we get one, just
4426 // recurse to handle whatever we get.
4427 if (TryAnnotateTypeOrScopeToken())
4429 if (Tok.is(tok::identifier))
4432 // If we're in Objective-C and we have an Objective-C class type followed
4433 // by an identifier and then either ':' or ']', in a place where an
4434 // expression is permitted, then this is probably a class message send
4435 // missing the initial '['. In this case, we won't consider this to be
4436 // the start of a declaration.
4437 if (DisambiguatingWithExpression &&
4438 isStartOfObjCClassMessageMissingOpenBracket())
4441 return isDeclarationSpecifier();
4443 case tok::coloncolon: // ::foo::bar
4444 if (NextToken().is(tok::kw_new) || // ::new
4445 NextToken().is(tok::kw_delete)) // ::delete
4448 // Annotate typenames and C++ scope specifiers. If we get one, just
4449 // recurse to handle whatever we get.
4450 if (TryAnnotateTypeOrScopeToken())
4452 return isDeclarationSpecifier();
4454 // storage-class-specifier
4455 case tok::kw_typedef:
4456 case tok::kw_extern:
4457 case tok::kw___private_extern__:
4458 case tok::kw_static:
4460 case tok::kw___auto_type:
4461 case tok::kw_register:
4462 case tok::kw___thread:
4463 case tok::kw_thread_local:
4464 case tok::kw__Thread_local:
4467 case tok::kw___module_private__:
4470 case tok::kw___unknown_anytype:
4475 case tok::kw___int64:
4476 case tok::kw___int128:
4477 case tok::kw_signed:
4478 case tok::kw_unsigned:
4479 case tok::kw__Complex:
4480 case tok::kw__Imaginary:
4483 case tok::kw_wchar_t:
4484 case tok::kw_char16_t:
4485 case tok::kw_char32_t:
4490 case tok::kw_double:
4493 case tok::kw__Decimal32:
4494 case tok::kw__Decimal64:
4495 case tok::kw__Decimal128:
4496 case tok::kw___vector:
4498 // struct-or-union-specifier (C99) or class-specifier (C++)
4500 case tok::kw_struct:
4502 case tok::kw___interface:
4508 case tok::kw_volatile:
4509 case tok::kw_restrict:
4511 // function-specifier
4512 case tok::kw_inline:
4513 case tok::kw_virtual:
4514 case tok::kw_explicit:
4515 case tok::kw__Noreturn:
4517 // alignment-specifier
4518 case tok::kw__Alignas:
4521 case tok::kw_friend:
4523 // static_assert-declaration
4524 case tok::kw__Static_assert:
4526 // GNU typeof support.
4527 case tok::kw_typeof:
4530 case tok::kw___attribute:
4532 // C++11 decltype and constexpr.
4533 case tok::annot_decltype:
4534 case tok::kw_constexpr:
4536 // C++ Concepts TS - concept
4537 case tok::kw_concept:
4540 case tok::kw__Atomic:
4543 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4545 return getLangOpts().ObjC1;
4548 case tok::annot_typename:
4549 return !DisambiguatingWithExpression ||
4550 !isStartOfObjCClassMessageMissingOpenBracket();
4552 case tok::kw___declspec:
4553 case tok::kw___cdecl:
4554 case tok::kw___stdcall:
4555 case tok::kw___fastcall:
4556 case tok::kw___thiscall:
4557 case tok::kw___vectorcall:
4559 case tok::kw___sptr:
4560 case tok::kw___uptr:
4561 case tok::kw___ptr64:
4562 case tok::kw___ptr32:
4563 case tok::kw___forceinline:
4564 case tok::kw___pascal:
4565 case tok::kw___unaligned:
4567 case tok::kw__Nonnull:
4568 case tok::kw__Nullable:
4569 case tok::kw__Null_unspecified:
4571 case tok::kw___kindof:
4573 case tok::kw___private:
4574 case tok::kw___local:
4575 case tok::kw___global:
4576 case tok::kw___constant:
4577 case tok::kw___generic:
4578 case tok::kw___read_only:
4579 case tok::kw___read_write:
4580 case tok::kw___write_only:
4586 bool Parser::isConstructorDeclarator(bool IsUnqualified) {
4587 TentativeParsingAction TPA(*this);
4589 // Parse the C++ scope specifier.
4591 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4592 /*EnteringContext=*/true)) {
4597 // Parse the constructor name.
4598 if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) {
4599 // We already know that we have a constructor name; just consume
4607 // Current class name must be followed by a left parenthesis.
4608 if (Tok.isNot(tok::l_paren)) {
4614 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4615 // that we have a constructor.
4616 if (Tok.is(tok::r_paren) ||
4617 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4622 // A C++11 attribute here signals that we have a constructor, and is an
4623 // attribute on the first constructor parameter.
4624 if (getLangOpts().CPlusPlus11 &&
4625 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4626 /*OuterMightBeMessageSend*/ true)) {
4631 // If we need to, enter the specified scope.
4632 DeclaratorScopeObj DeclScopeObj(*this, SS);
4633 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4634 DeclScopeObj.EnterDeclaratorScope();
4636 // Optionally skip Microsoft attributes.
4637 ParsedAttributes Attrs(AttrFactory);
4638 MaybeParseMicrosoftAttributes(Attrs);
4640 // Check whether the next token(s) are part of a declaration
4641 // specifier, in which case we have the start of a parameter and,
4642 // therefore, we know that this is a constructor.
4643 bool IsConstructor = false;
4644 if (isDeclarationSpecifier())
4645 IsConstructor = true;
4646 else if (Tok.is(tok::identifier) ||
4647 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4648 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4649 // This might be a parenthesized member name, but is more likely to
4650 // be a constructor declaration with an invalid argument type. Keep
4652 if (Tok.is(tok::annot_cxxscope))
4656 // If this is not a constructor, we must be parsing a declarator,
4657 // which must have one of the following syntactic forms (see the
4658 // grammar extract at the start of ParseDirectDeclarator):
4659 switch (Tok.getKind()) {
4664 // C(X [ [attribute]]);
4665 case tok::coloncolon:
4668 // Assume this isn't a constructor, rather than assuming it's a
4669 // constructor with an unnamed parameter of an ill-formed type.
4674 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) {
4675 // Assume these were meant to be constructors:
4676 // C(X) : (the name of a bit-field cannot be parenthesized).
4677 // C(X) try (this is otherwise ill-formed).
4678 IsConstructor = true;
4680 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) {
4681 // If we have a constructor name within the class definition,
4682 // assume these were meant to be constructors:
4685 // ... because otherwise we would be declaring a non-static data
4686 // member that is ill-formed because it's of the same type as its
4687 // surrounding class.
4689 // FIXME: We can actually do this whether or not the name is qualified,
4690 // because if it is qualified in this context it must be being used as
4691 // a constructor name. However, we do not implement that rule correctly
4692 // currently, so we're somewhat conservative here.
4693 IsConstructor = IsUnqualified;
4698 IsConstructor = true;
4704 return IsConstructor;
4707 /// ParseTypeQualifierListOpt
4708 /// type-qualifier-list: [C99 6.7.5]
4710 /// [vendor] attributes
4711 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4712 /// type-qualifier-list type-qualifier
4713 /// [vendor] type-qualifier-list attributes
4714 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4715 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4716 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4717 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4718 /// AttrRequirements bitmask values.
4719 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs,
4721 bool IdentifierRequired) {
4722 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4723 isCXX11AttributeSpecifier()) {
4724 ParsedAttributesWithRange attrs(AttrFactory);
4725 ParseCXX11Attributes(attrs);
4726 DS.takeAttributesFrom(attrs);
4729 SourceLocation EndLoc;
4732 bool isInvalid = false;
4733 const char *PrevSpec = nullptr;
4734 unsigned DiagID = 0;
4735 SourceLocation Loc = Tok.getLocation();
4737 switch (Tok.getKind()) {
4738 case tok::code_completion:
4739 Actions.CodeCompleteTypeQualifiers(DS);
4740 return cutOffParsing();
4743 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4746 case tok::kw_volatile:
4747 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4750 case tok::kw_restrict:
4751 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4754 case tok::kw__Atomic:
4756 goto DoneWithTypeQuals;
4757 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4761 // OpenCL qualifiers:
4762 case tok::kw___private:
4763 case tok::kw___global:
4764 case tok::kw___local:
4765 case tok::kw___constant:
4766 case tok::kw___generic:
4767 case tok::kw___read_only:
4768 case tok::kw___write_only:
4769 case tok::kw___read_write:
4770 ParseOpenCLQualifiers(DS.getAttributes());
4773 case tok::kw___uptr:
4774 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4775 // with the MS modifier keyword.
4776 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
4777 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4778 if (TryKeywordIdentFallback(false))
4781 case tok::kw___sptr:
4783 case tok::kw___ptr64:
4784 case tok::kw___ptr32:
4785 case tok::kw___cdecl:
4786 case tok::kw___stdcall:
4787 case tok::kw___fastcall:
4788 case tok::kw___thiscall:
4789 case tok::kw___vectorcall:
4790 case tok::kw___unaligned:
4791 if (AttrReqs & AR_DeclspecAttributesParsed) {
4792 ParseMicrosoftTypeAttributes(DS.getAttributes());
4795 goto DoneWithTypeQuals;
4796 case tok::kw___pascal:
4797 if (AttrReqs & AR_VendorAttributesParsed) {
4798 ParseBorlandTypeAttributes(DS.getAttributes());
4801 goto DoneWithTypeQuals;
4803 // Nullability type specifiers.
4804 case tok::kw__Nonnull:
4805 case tok::kw__Nullable:
4806 case tok::kw__Null_unspecified:
4807 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4810 // Objective-C 'kindof' types.
4811 case tok::kw___kindof:
4812 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4813 nullptr, 0, AttributeList::AS_Keyword);
4814 (void)ConsumeToken();
4817 case tok::kw___attribute:
4818 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
4819 // When GNU attributes are expressly forbidden, diagnose their usage.
4820 Diag(Tok, diag::err_attributes_not_allowed);
4822 // Parse the attributes even if they are rejected to ensure that error
4823 // recovery is graceful.
4824 if (AttrReqs & AR_GNUAttributesParsed ||
4825 AttrReqs & AR_GNUAttributesParsedAndRejected) {
4826 ParseGNUAttributes(DS.getAttributes());
4827 continue; // do *not* consume the next token!
4829 // otherwise, FALL THROUGH!
4832 // If this is not a type-qualifier token, we're done reading type
4833 // qualifiers. First verify that DeclSpec's are consistent.
4834 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
4835 if (EndLoc.isValid())
4836 DS.SetRangeEnd(EndLoc);
4840 // If the specifier combination wasn't legal, issue a diagnostic.
4842 assert(PrevSpec && "Method did not return previous specifier!");
4843 Diag(Tok, DiagID) << PrevSpec;
4845 EndLoc = ConsumeToken();
4849 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4851 void Parser::ParseDeclarator(Declarator &D) {
4852 /// This implements the 'declarator' production in the C grammar, then checks
4853 /// for well-formedness and issues diagnostics.
4854 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4857 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
4858 unsigned TheContext) {
4859 if (Kind == tok::star || Kind == tok::caret)
4862 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
4865 if (!Lang.CPlusPlus)
4868 if (Kind == tok::amp)
4871 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4872 // But we must not parse them in conversion-type-ids and new-type-ids, since
4873 // those can be legitimately followed by a && operator.
4874 // (The same thing can in theory happen after a trailing-return-type, but
4875 // since those are a C++11 feature, there is no rejects-valid issue there.)
4876 if (Kind == tok::ampamp)
4877 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
4878 TheContext != Declarator::CXXNewContext);
4883 // Indicates whether the given declarator is a pipe declarator.
4884 static bool isPipeDeclerator(const Declarator &D) {
4885 const unsigned NumTypes = D.getNumTypeObjects();
4887 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
4888 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
4894 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4895 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4896 /// isn't parsed at all, making this function effectively parse the C++
4897 /// ptr-operator production.
4899 /// If the grammar of this construct is extended, matching changes must also be
4900 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4901 /// isConstructorDeclarator.
4903 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4904 /// [C] pointer[opt] direct-declarator
4905 /// [C++] direct-declarator
4906 /// [C++] ptr-operator declarator
4908 /// pointer: [C99 6.7.5]
4909 /// '*' type-qualifier-list[opt]
4910 /// '*' type-qualifier-list[opt] pointer
4913 /// '*' cv-qualifier-seq[opt]
4916 /// [GNU] '&' restrict[opt] attributes[opt]
4917 /// [GNU?] '&&' restrict[opt] attributes[opt]
4918 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4919 void Parser::ParseDeclaratorInternal(Declarator &D,
4920 DirectDeclParseFunction DirectDeclParser) {
4921 if (Diags.hasAllExtensionsSilenced())
4924 // C++ member pointers start with a '::' or a nested-name.
4925 // Member pointers get special handling, since there's no place for the
4926 // scope spec in the generic path below.
4927 if (getLangOpts().CPlusPlus &&
4928 (Tok.is(tok::coloncolon) ||
4929 (Tok.is(tok::identifier) &&
4930 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
4931 Tok.is(tok::annot_cxxscope))) {
4932 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4933 D.getContext() == Declarator::MemberContext;
4935 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4937 if (SS.isNotEmpty()) {
4938 if (Tok.isNot(tok::star)) {
4939 // The scope spec really belongs to the direct-declarator.
4940 if (D.mayHaveIdentifier())
4941 D.getCXXScopeSpec() = SS;
4943 AnnotateScopeToken(SS, true);
4945 if (DirectDeclParser)
4946 (this->*DirectDeclParser)(D);
4950 SourceLocation Loc = ConsumeToken();
4952 DeclSpec DS(AttrFactory);
4953 ParseTypeQualifierListOpt(DS);
4954 D.ExtendWithDeclSpec(DS);
4956 // Recurse to parse whatever is left.
4957 ParseDeclaratorInternal(D, DirectDeclParser);
4959 // Sema will have to catch (syntactically invalid) pointers into global
4960 // scope. It has to catch pointers into namespace scope anyway.
4961 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4964 /* Don't replace range end. */SourceLocation());
4969 tok::TokenKind Kind = Tok.getKind();
4971 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
4972 DeclSpec &DS = D.getMutableDeclSpec();
4975 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
4976 DS.getAttributes(), SourceLocation());
4979 // Not a pointer, C++ reference, or block.
4980 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
4981 if (DirectDeclParser)
4982 (this->*DirectDeclParser)(D);
4986 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4987 // '&&' -> rvalue reference
4988 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4991 if (Kind == tok::star || Kind == tok::caret) {
4993 DeclSpec DS(AttrFactory);
4995 // GNU attributes are not allowed here in a new-type-id, but Declspec and
4996 // C++11 attributes are allowed.
4997 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
4998 ((D.getContext() != Declarator::CXXNewContext)
4999 ? AR_GNUAttributesParsed
5000 : AR_GNUAttributesParsedAndRejected);
5001 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5002 D.ExtendWithDeclSpec(DS);
5004 // Recursively parse the declarator.
5005 ParseDeclaratorInternal(D, DirectDeclParser);
5006 if (Kind == tok::star)
5007 // Remember that we parsed a pointer type, and remember the type-quals.
5008 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
5009 DS.getConstSpecLoc(),
5010 DS.getVolatileSpecLoc(),
5011 DS.getRestrictSpecLoc(),
5012 DS.getAtomicSpecLoc()),
5016 // Remember that we parsed a Block type, and remember the type-quals.
5017 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
5023 DeclSpec DS(AttrFactory);
5025 // Complain about rvalue references in C++03, but then go on and build
5027 if (Kind == tok::ampamp)
5028 Diag(Loc, getLangOpts().CPlusPlus11 ?
5029 diag::warn_cxx98_compat_rvalue_reference :
5030 diag::ext_rvalue_reference);
5032 // GNU-style and C++11 attributes are allowed here, as is restrict.
5033 ParseTypeQualifierListOpt(DS);
5034 D.ExtendWithDeclSpec(DS);
5036 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5037 // cv-qualifiers are introduced through the use of a typedef or of a
5038 // template type argument, in which case the cv-qualifiers are ignored.
5039 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5040 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5041 Diag(DS.getConstSpecLoc(),
5042 diag::err_invalid_reference_qualifier_application) << "const";
5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5044 Diag(DS.getVolatileSpecLoc(),
5045 diag::err_invalid_reference_qualifier_application) << "volatile";
5046 // 'restrict' is permitted as an extension.
5047 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5048 Diag(DS.getAtomicSpecLoc(),
5049 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5052 // Recursively parse the declarator.
5053 ParseDeclaratorInternal(D, DirectDeclParser);
5055 if (D.getNumTypeObjects() > 0) {
5056 // C++ [dcl.ref]p4: There shall be no references to references.
5057 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5058 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5059 if (const IdentifierInfo *II = D.getIdentifier())
5060 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5063 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5066 // Once we've complained about the reference-to-reference, we
5067 // can go ahead and build the (technically ill-formed)
5068 // declarator: reference collapsing will take care of it.
5072 // Remember that we parsed a reference type.
5073 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5080 // When correcting from misplaced brackets before the identifier, the location
5081 // is saved inside the declarator so that other diagnostic messages can use
5082 // them. This extracts and returns that location, or returns the provided
5083 // location if a stored location does not exist.
5084 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5085 SourceLocation Loc) {
5086 if (D.getName().StartLocation.isInvalid() &&
5087 D.getName().EndLocation.isValid())
5088 return D.getName().EndLocation;
5093 /// ParseDirectDeclarator
5094 /// direct-declarator: [C99 6.7.5]
5095 /// [C99] identifier
5096 /// '(' declarator ')'
5097 /// [GNU] '(' attributes declarator ')'
5098 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5099 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5100 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5101 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5102 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5103 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5104 /// attribute-specifier-seq[opt]
5105 /// direct-declarator '(' parameter-type-list ')'
5106 /// direct-declarator '(' identifier-list[opt] ')'
5107 /// [GNU] direct-declarator '(' parameter-forward-declarations
5108 /// parameter-type-list[opt] ')'
5109 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5110 /// cv-qualifier-seq[opt] exception-specification[opt]
5111 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5112 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5113 /// ref-qualifier[opt] exception-specification[opt]
5114 /// [C++] declarator-id
5115 /// [C++11] declarator-id attribute-specifier-seq[opt]
5117 /// declarator-id: [C++ 8]
5118 /// '...'[opt] id-expression
5119 /// '::'[opt] nested-name-specifier[opt] type-name
5121 /// id-expression: [C++ 5.1]
5125 /// unqualified-id: [C++ 5.1]
5127 /// operator-function-id
5128 /// conversion-function-id
5132 /// Note, any additional constructs added here may need corresponding changes
5133 /// in isConstructorDeclarator.
5134 void Parser::ParseDirectDeclarator(Declarator &D) {
5135 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5137 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5138 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5139 // this context it is a bitfield. Also in range-based for statement colon
5140 // may delimit for-range-declaration.
5141 ColonProtectionRAIIObject X(*this,
5142 D.getContext() == Declarator::MemberContext ||
5143 (D.getContext() == Declarator::ForContext &&
5144 getLangOpts().CPlusPlus11));
5146 // ParseDeclaratorInternal might already have parsed the scope.
5147 if (D.getCXXScopeSpec().isEmpty()) {
5148 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5149 D.getContext() == Declarator::MemberContext;
5150 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
5154 if (D.getCXXScopeSpec().isValid()) {
5155 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5156 D.getCXXScopeSpec()))
5157 // Change the declaration context for name lookup, until this function
5158 // is exited (and the declarator has been parsed).
5159 DeclScopeObj.EnterDeclaratorScope();
5162 // C++0x [dcl.fct]p14:
5163 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5164 // parameter-declaration-clause without a preceding comma. In this case,
5165 // the ellipsis is parsed as part of the abstract-declarator if the type
5166 // of the parameter either names a template parameter pack that has not
5167 // been expanded or contains auto; otherwise, it is parsed as part of the
5168 // parameter-declaration-clause.
5169 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5170 !((D.getContext() == Declarator::PrototypeContext ||
5171 D.getContext() == Declarator::LambdaExprParameterContext ||
5172 D.getContext() == Declarator::BlockLiteralContext) &&
5173 NextToken().is(tok::r_paren) &&
5174 !D.hasGroupingParens() &&
5175 !Actions.containsUnexpandedParameterPacks(D) &&
5176 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5177 SourceLocation EllipsisLoc = ConsumeToken();
5178 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5179 // The ellipsis was put in the wrong place. Recover, and explain to
5180 // the user what they should have done.
5182 if (EllipsisLoc.isValid())
5183 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5186 D.setEllipsisLoc(EllipsisLoc);
5188 // The ellipsis can't be followed by a parenthesized declarator. We
5189 // check for that in ParseParenDeclarator, after we have disambiguated
5190 // the l_paren token.
5193 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5195 // We found something that indicates the start of an unqualified-id.
5196 // Parse that unqualified-id.
5197 bool AllowConstructorName;
5198 if (D.getDeclSpec().hasTypeSpecifier())
5199 AllowConstructorName = false;
5200 else if (D.getCXXScopeSpec().isSet())
5201 AllowConstructorName =
5202 (D.getContext() == Declarator::FileContext ||
5203 D.getContext() == Declarator::MemberContext);
5205 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5207 SourceLocation TemplateKWLoc;
5208 bool HadScope = D.getCXXScopeSpec().isValid();
5209 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5210 /*EnteringContext=*/true,
5211 /*AllowDestructorName=*/true,
5212 AllowConstructorName,
5216 // Once we're past the identifier, if the scope was bad, mark the
5217 // whole declarator bad.
5218 D.getCXXScopeSpec().isInvalid()) {
5219 D.SetIdentifier(nullptr, Tok.getLocation());
5220 D.setInvalidType(true);
5222 // ParseUnqualifiedId might have parsed a scope specifier during error
5223 // recovery. If it did so, enter that scope.
5224 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5225 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5226 D.getCXXScopeSpec()))
5227 DeclScopeObj.EnterDeclaratorScope();
5229 // Parsed the unqualified-id; update range information and move along.
5230 if (D.getSourceRange().getBegin().isInvalid())
5231 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5232 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5234 goto PastIdentifier;
5237 if (D.getCXXScopeSpec().isNotEmpty()) {
5238 // We have a scope specifier but no following unqualified-id.
5239 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5240 diag::err_expected_unqualified_id)
5242 D.SetIdentifier(nullptr, Tok.getLocation());
5243 goto PastIdentifier;
5245 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5246 assert(!getLangOpts().CPlusPlus &&
5247 "There's a C++-specific check for tok::identifier above");
5248 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5249 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5250 D.SetRangeEnd(Tok.getLocation());
5252 goto PastIdentifier;
5253 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
5254 // A virt-specifier isn't treated as an identifier if it appears after a
5255 // trailing-return-type.
5256 if (D.getContext() != Declarator::TrailingReturnContext ||
5257 !isCXX11VirtSpecifier(Tok)) {
5258 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5259 << FixItHint::CreateRemoval(Tok.getLocation());
5260 D.SetIdentifier(nullptr, Tok.getLocation());
5262 goto PastIdentifier;
5266 if (Tok.is(tok::l_paren)) {
5267 // direct-declarator: '(' declarator ')'
5268 // direct-declarator: '(' attributes declarator ')'
5269 // Example: 'char (*X)' or 'int (*XX)(void)'
5270 ParseParenDeclarator(D);
5272 // If the declarator was parenthesized, we entered the declarator
5273 // scope when parsing the parenthesized declarator, then exited
5274 // the scope already. Re-enter the scope, if we need to.
5275 if (D.getCXXScopeSpec().isSet()) {
5276 // If there was an error parsing parenthesized declarator, declarator
5277 // scope may have been entered before. Don't do it again.
5278 if (!D.isInvalidType() &&
5279 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5280 D.getCXXScopeSpec()))
5281 // Change the declaration context for name lookup, until this function
5282 // is exited (and the declarator has been parsed).
5283 DeclScopeObj.EnterDeclaratorScope();
5285 } else if (D.mayOmitIdentifier()) {
5286 // This could be something simple like "int" (in which case the declarator
5287 // portion is empty), if an abstract-declarator is allowed.
5288 D.SetIdentifier(nullptr, Tok.getLocation());
5290 // The grammar for abstract-pack-declarator does not allow grouping parens.
5291 // FIXME: Revisit this once core issue 1488 is resolved.
5292 if (D.hasEllipsis() && D.hasGroupingParens())
5293 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5294 diag::ext_abstract_pack_declarator_parens);
5296 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5298 if (Tok.is(tok::l_square))
5299 return ParseMisplacedBracketDeclarator(D);
5300 if (D.getContext() == Declarator::MemberContext) {
5301 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5302 diag::err_expected_member_name_or_semi)
5303 << (D.getDeclSpec().isEmpty() ? SourceRange()
5304 : D.getDeclSpec().getSourceRange());
5305 } else if (getLangOpts().CPlusPlus) {
5306 if (Tok.isOneOf(tok::period, tok::arrow))
5307 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5309 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5310 if (Tok.isAtStartOfLine() && Loc.isValid())
5311 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5312 << getLangOpts().CPlusPlus;
5314 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5315 diag::err_expected_unqualified_id)
5316 << getLangOpts().CPlusPlus;
5319 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5320 diag::err_expected_either)
5321 << tok::identifier << tok::l_paren;
5323 D.SetIdentifier(nullptr, Tok.getLocation());
5324 D.setInvalidType(true);
5328 assert(D.isPastIdentifier() &&
5329 "Haven't past the location of the identifier yet?");
5331 // Don't parse attributes unless we have parsed an unparenthesized name.
5332 if (D.hasName() && !D.getNumTypeObjects())
5333 MaybeParseCXX11Attributes(D);
5336 if (Tok.is(tok::l_paren)) {
5337 // Enter function-declaration scope, limiting any declarators to the
5338 // function prototype scope, including parameter declarators.
5339 ParseScope PrototypeScope(this,
5340 Scope::FunctionPrototypeScope|Scope::DeclScope|
5341 (D.isFunctionDeclaratorAFunctionDeclaration()
5342 ? Scope::FunctionDeclarationScope : 0));
5344 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5345 // In such a case, check if we actually have a function declarator; if it
5346 // is not, the declarator has been fully parsed.
5347 bool IsAmbiguous = false;
5348 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5349 // The name of the declarator, if any, is tentatively declared within
5350 // a possible direct initializer.
5351 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5352 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5353 TentativelyDeclaredIdentifiers.pop_back();
5354 if (!IsFunctionDecl)
5357 ParsedAttributes attrs(AttrFactory);
5358 BalancedDelimiterTracker T(*this, tok::l_paren);
5360 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5361 PrototypeScope.Exit();
5362 } else if (Tok.is(tok::l_square)) {
5363 ParseBracketDeclarator(D);
5370 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5371 /// only called before the identifier, so these are most likely just grouping
5372 /// parens for precedence. If we find that these are actually function
5373 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5375 /// direct-declarator:
5376 /// '(' declarator ')'
5377 /// [GNU] '(' attributes declarator ')'
5378 /// direct-declarator '(' parameter-type-list ')'
5379 /// direct-declarator '(' identifier-list[opt] ')'
5380 /// [GNU] direct-declarator '(' parameter-forward-declarations
5381 /// parameter-type-list[opt] ')'
5383 void Parser::ParseParenDeclarator(Declarator &D) {
5384 BalancedDelimiterTracker T(*this, tok::l_paren);
5387 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5389 // Eat any attributes before we look at whether this is a grouping or function
5390 // declarator paren. If this is a grouping paren, the attribute applies to
5391 // the type being built up, for example:
5392 // int (__attribute__(()) *x)(long y)
5393 // If this ends up not being a grouping paren, the attribute applies to the
5394 // first argument, for example:
5395 // int (__attribute__(()) int x)
5396 // In either case, we need to eat any attributes to be able to determine what
5397 // sort of paren this is.
5399 ParsedAttributes attrs(AttrFactory);
5400 bool RequiresArg = false;
5401 if (Tok.is(tok::kw___attribute)) {
5402 ParseGNUAttributes(attrs);
5404 // We require that the argument list (if this is a non-grouping paren) be
5405 // present even if the attribute list was empty.
5409 // Eat any Microsoft extensions.
5410 ParseMicrosoftTypeAttributes(attrs);
5412 // Eat any Borland extensions.
5413 if (Tok.is(tok::kw___pascal))
5414 ParseBorlandTypeAttributes(attrs);
5416 // If we haven't past the identifier yet (or where the identifier would be
5417 // stored, if this is an abstract declarator), then this is probably just
5418 // grouping parens. However, if this could be an abstract-declarator, then
5419 // this could also be the start of function arguments (consider 'void()').
5422 if (!D.mayOmitIdentifier()) {
5423 // If this can't be an abstract-declarator, this *must* be a grouping
5424 // paren, because we haven't seen the identifier yet.
5426 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5427 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5428 NextToken().is(tok::r_paren)) || // C++ int(...)
5429 isDeclarationSpecifier() || // 'int(int)' is a function.
5430 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5431 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5432 // considered to be a type, not a K&R identifier-list.
5435 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5439 // If this is a grouping paren, handle:
5440 // direct-declarator: '(' declarator ')'
5441 // direct-declarator: '(' attributes declarator ')'
5443 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5444 D.setEllipsisLoc(SourceLocation());
5446 bool hadGroupingParens = D.hasGroupingParens();
5447 D.setGroupingParens(true);
5448 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5451 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5452 T.getCloseLocation()),
5453 attrs, T.getCloseLocation());
5455 D.setGroupingParens(hadGroupingParens);
5457 // An ellipsis cannot be placed outside parentheses.
5458 if (EllipsisLoc.isValid())
5459 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5464 // Okay, if this wasn't a grouping paren, it must be the start of a function
5465 // argument list. Recognize that this declarator will never have an
5466 // identifier (and remember where it would have been), then call into
5467 // ParseFunctionDeclarator to handle of argument list.
5468 D.SetIdentifier(nullptr, Tok.getLocation());
5470 // Enter function-declaration scope, limiting any declarators to the
5471 // function prototype scope, including parameter declarators.
5472 ParseScope PrototypeScope(this,
5473 Scope::FunctionPrototypeScope | Scope::DeclScope |
5474 (D.isFunctionDeclaratorAFunctionDeclaration()
5475 ? Scope::FunctionDeclarationScope : 0));
5476 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5477 PrototypeScope.Exit();
5480 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5481 /// declarator D up to a paren, which indicates that we are parsing function
5484 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5485 /// immediately after the open paren - they should be considered to be the
5486 /// first argument of a parameter.
5488 /// If RequiresArg is true, then the first argument of the function is required
5489 /// to be present and required to not be an identifier list.
5491 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5492 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5493 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5495 /// [C++11] exception-specification:
5496 /// dynamic-exception-specification
5497 /// noexcept-specification
5499 void Parser::ParseFunctionDeclarator(Declarator &D,
5500 ParsedAttributes &FirstArgAttrs,
5501 BalancedDelimiterTracker &Tracker,
5504 assert(getCurScope()->isFunctionPrototypeScope() &&
5505 "Should call from a Function scope");
5506 // lparen is already consumed!
5507 assert(D.isPastIdentifier() && "Should not call before identifier!");
5509 // This should be true when the function has typed arguments.
5510 // Otherwise, it is treated as a K&R-style function.
5511 bool HasProto = false;
5512 // Build up an array of information about the parsed arguments.
5513 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5514 // Remember where we see an ellipsis, if any.
5515 SourceLocation EllipsisLoc;
5517 DeclSpec DS(AttrFactory);
5518 bool RefQualifierIsLValueRef = true;
5519 SourceLocation RefQualifierLoc;
5520 SourceLocation ConstQualifierLoc;
5521 SourceLocation VolatileQualifierLoc;
5522 SourceLocation RestrictQualifierLoc;
5523 ExceptionSpecificationType ESpecType = EST_None;
5524 SourceRange ESpecRange;
5525 SmallVector<ParsedType, 2> DynamicExceptions;
5526 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5527 ExprResult NoexceptExpr;
5528 CachedTokens *ExceptionSpecTokens = nullptr;
5529 ParsedAttributes FnAttrs(AttrFactory);
5530 TypeResult TrailingReturnType;
5532 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5533 EndLoc is the end location for the function declarator.
5534 They differ for trailing return types. */
5535 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5536 SourceLocation LParenLoc, RParenLoc;
5537 LParenLoc = Tracker.getOpenLocation();
5538 StartLoc = LParenLoc;
5540 if (isFunctionDeclaratorIdentifierList()) {
5542 Diag(Tok, diag::err_argument_required_after_attribute);
5544 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5546 Tracker.consumeClose();
5547 RParenLoc = Tracker.getCloseLocation();
5548 LocalEndLoc = RParenLoc;
5551 if (Tok.isNot(tok::r_paren))
5552 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5554 else if (RequiresArg)
5555 Diag(Tok, diag::err_argument_required_after_attribute);
5557 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5559 // If we have the closing ')', eat it.
5560 Tracker.consumeClose();
5561 RParenLoc = Tracker.getCloseLocation();
5562 LocalEndLoc = RParenLoc;
5565 if (getLangOpts().CPlusPlus) {
5566 // FIXME: Accept these components in any order, and produce fixits to
5567 // correct the order if the user gets it wrong. Ideally we should deal
5568 // with the pure-specifier in the same way.
5570 // Parse cv-qualifier-seq[opt].
5571 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5572 /*AtomicAllowed*/ false);
5573 if (!DS.getSourceRange().getEnd().isInvalid()) {
5574 EndLoc = DS.getSourceRange().getEnd();
5575 ConstQualifierLoc = DS.getConstSpecLoc();
5576 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5577 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5580 // Parse ref-qualifier[opt].
5581 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5582 EndLoc = RefQualifierLoc;
5584 // C++11 [expr.prim.general]p3:
5585 // If a declaration declares a member function or member function
5586 // template of a class X, the expression this is a prvalue of type
5587 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5588 // and the end of the function-definition, member-declarator, or
5590 // FIXME: currently, "static" case isn't handled correctly.
5591 bool IsCXX11MemberFunction =
5592 getLangOpts().CPlusPlus11 &&
5593 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5594 (D.getContext() == Declarator::MemberContext
5595 ? !D.getDeclSpec().isFriendSpecified()
5596 : D.getContext() == Declarator::FileContext &&
5597 D.getCXXScopeSpec().isValid() &&
5598 Actions.CurContext->isRecord());
5599 Sema::CXXThisScopeRAII ThisScope(Actions,
5600 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5601 DS.getTypeQualifiers() |
5602 (D.getDeclSpec().isConstexprSpecified() &&
5603 !getLangOpts().CPlusPlus14
5604 ? Qualifiers::Const : 0),
5605 IsCXX11MemberFunction);
5607 // Parse exception-specification[opt].
5608 bool Delayed = D.isFirstDeclarationOfMember() &&
5609 D.isFunctionDeclaratorAFunctionDeclaration();
5610 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
5611 GetLookAheadToken(0).is(tok::kw_noexcept) &&
5612 GetLookAheadToken(1).is(tok::l_paren) &&
5613 GetLookAheadToken(2).is(tok::kw_noexcept) &&
5614 GetLookAheadToken(3).is(tok::l_paren) &&
5615 GetLookAheadToken(4).is(tok::identifier) &&
5616 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
5617 // HACK: We've got an exception-specification
5618 // noexcept(noexcept(swap(...)))
5620 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
5621 // on a 'swap' member function. This is a libstdc++ bug; the lookup
5622 // for 'swap' will only find the function we're currently declaring,
5623 // whereas it expects to find a non-member swap through ADL. Turn off
5624 // delayed parsing to give it a chance to find what it expects.
5627 ESpecType = tryParseExceptionSpecification(Delayed,
5630 DynamicExceptionRanges,
5632 ExceptionSpecTokens);
5633 if (ESpecType != EST_None)
5634 EndLoc = ESpecRange.getEnd();
5636 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5637 // after the exception-specification.
5638 MaybeParseCXX11Attributes(FnAttrs);
5640 // Parse trailing-return-type[opt].
5641 LocalEndLoc = EndLoc;
5642 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5643 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5644 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5645 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5646 LocalEndLoc = Tok.getLocation();
5648 TrailingReturnType = ParseTrailingReturnType(Range);
5649 EndLoc = Range.getEnd();
5654 // Remember that we parsed a function type, and remember the attributes.
5655 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5658 ParamInfo.data(), ParamInfo.size(),
5659 EllipsisLoc, RParenLoc,
5660 DS.getTypeQualifiers(),
5661 RefQualifierIsLValueRef,
5662 RefQualifierLoc, ConstQualifierLoc,
5663 VolatileQualifierLoc,
5664 RestrictQualifierLoc,
5665 /*MutableLoc=*/SourceLocation(),
5666 ESpecType, ESpecRange,
5667 DynamicExceptions.data(),
5668 DynamicExceptionRanges.data(),
5669 DynamicExceptions.size(),
5670 NoexceptExpr.isUsable() ?
5671 NoexceptExpr.get() : nullptr,
5672 ExceptionSpecTokens,
5673 StartLoc, LocalEndLoc, D,
5674 TrailingReturnType),
5678 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
5679 /// true if a ref-qualifier is found.
5680 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
5681 SourceLocation &RefQualifierLoc) {
5682 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
5683 Diag(Tok, getLangOpts().CPlusPlus11 ?
5684 diag::warn_cxx98_compat_ref_qualifier :
5685 diag::ext_ref_qualifier);
5687 RefQualifierIsLValueRef = Tok.is(tok::amp);
5688 RefQualifierLoc = ConsumeToken();
5694 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5695 /// identifier list form for a K&R-style function: void foo(a,b,c)
5697 /// Note that identifier-lists are only allowed for normal declarators, not for
5698 /// abstract-declarators.
5699 bool Parser::isFunctionDeclaratorIdentifierList() {
5700 return !getLangOpts().CPlusPlus
5701 && Tok.is(tok::identifier)
5702 && !TryAltiVecVectorToken()
5703 // K&R identifier lists can't have typedefs as identifiers, per C99
5705 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5706 // Identifier lists follow a really simple grammar: the identifiers can
5707 // be followed *only* by a ", identifier" or ")". However, K&R
5708 // identifier lists are really rare in the brave new modern world, and
5709 // it is very common for someone to typo a type in a non-K&R style
5710 // list. If we are presented with something like: "void foo(intptr x,
5711 // float y)", we don't want to start parsing the function declarator as
5712 // though it is a K&R style declarator just because intptr is an
5715 // To handle this, we check to see if the token after the first
5716 // identifier is a "," or ")". Only then do we parse it as an
5718 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5721 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5722 /// we found a K&R-style identifier list instead of a typed parameter list.
5724 /// After returning, ParamInfo will hold the parsed parameters.
5726 /// identifier-list: [C99 6.7.5]
5728 /// identifier-list ',' identifier
5730 void Parser::ParseFunctionDeclaratorIdentifierList(
5732 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5733 // If there was no identifier specified for the declarator, either we are in
5734 // an abstract-declarator, or we are in a parameter declarator which was found
5735 // to be abstract. In abstract-declarators, identifier lists are not valid:
5737 if (!D.getIdentifier())
5738 Diag(Tok, diag::ext_ident_list_in_param);
5740 // Maintain an efficient lookup of params we have seen so far.
5741 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5744 // If this isn't an identifier, report the error and skip until ')'.
5745 if (Tok.isNot(tok::identifier)) {
5746 Diag(Tok, diag::err_expected) << tok::identifier;
5747 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5748 // Forget we parsed anything.
5753 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5755 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5756 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5757 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5759 // Verify that the argument identifier has not already been mentioned.
5760 if (!ParamsSoFar.insert(ParmII).second) {
5761 Diag(Tok, diag::err_param_redefinition) << ParmII;
5763 // Remember this identifier in ParamInfo.
5764 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5769 // Eat the identifier.
5771 // The list continues if we see a comma.
5772 } while (TryConsumeToken(tok::comma));
5775 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5776 /// after the opening parenthesis. This function will not parse a K&R-style
5777 /// identifier list.
5779 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5780 /// caller parsed those arguments immediately after the open paren - they should
5781 /// be considered to be part of the first parameter.
5783 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5784 /// be the location of the ellipsis, if any was parsed.
5786 /// parameter-type-list: [C99 6.7.5]
5788 /// parameter-list ',' '...'
5789 /// [C++] parameter-list '...'
5791 /// parameter-list: [C99 6.7.5]
5792 /// parameter-declaration
5793 /// parameter-list ',' parameter-declaration
5795 /// parameter-declaration: [C99 6.7.5]
5796 /// declaration-specifiers declarator
5797 /// [C++] declaration-specifiers declarator '=' assignment-expression
5798 /// [C++11] initializer-clause
5799 /// [GNU] declaration-specifiers declarator attributes
5800 /// declaration-specifiers abstract-declarator[opt]
5801 /// [C++] declaration-specifiers abstract-declarator[opt]
5802 /// '=' assignment-expression
5803 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5804 /// [C++11] attribute-specifier-seq parameter-declaration
5806 void Parser::ParseParameterDeclarationClause(
5808 ParsedAttributes &FirstArgAttrs,
5809 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5810 SourceLocation &EllipsisLoc) {
5812 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5813 // before deciding this was a parameter-declaration-clause.
5814 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
5817 // Parse the declaration-specifiers.
5818 // Just use the ParsingDeclaration "scope" of the declarator.
5819 DeclSpec DS(AttrFactory);
5821 // Parse any C++11 attributes.
5822 MaybeParseCXX11Attributes(DS.getAttributes());
5824 // Skip any Microsoft attributes before a param.
5825 MaybeParseMicrosoftAttributes(DS.getAttributes());
5827 SourceLocation DSStart = Tok.getLocation();
5829 // If the caller parsed attributes for the first argument, add them now.
5830 // Take them so that we only apply the attributes to the first parameter.
5831 // FIXME: If we can leave the attributes in the token stream somehow, we can
5832 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5834 DS.takeAttributesFrom(FirstArgAttrs);
5836 ParseDeclarationSpecifiers(DS);
5839 // Parse the declarator. This is "PrototypeContext" or
5840 // "LambdaExprParameterContext", because we must accept either
5841 // 'declarator' or 'abstract-declarator' here.
5842 Declarator ParmDeclarator(DS,
5843 D.getContext() == Declarator::LambdaExprContext ?
5844 Declarator::LambdaExprParameterContext :
5845 Declarator::PrototypeContext);
5846 ParseDeclarator(ParmDeclarator);
5848 // Parse GNU attributes, if present.
5849 MaybeParseGNUAttributes(ParmDeclarator);
5851 // Remember this parsed parameter in ParamInfo.
5852 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
5854 // DefArgToks is used when the parsing of default arguments needs
5856 CachedTokens *DefArgToks = nullptr;
5858 // If no parameter was specified, verify that *something* was specified,
5859 // otherwise we have a missing type and identifier.
5860 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
5861 ParmDeclarator.getNumTypeObjects() == 0) {
5862 // Completely missing, emit error.
5863 Diag(DSStart, diag::err_missing_param);
5865 // Otherwise, we have something. Add it and let semantic analysis try
5866 // to grok it and add the result to the ParamInfo we are building.
5868 // Last chance to recover from a misplaced ellipsis in an attempted
5869 // parameter pack declaration.
5870 if (Tok.is(tok::ellipsis) &&
5871 (NextToken().isNot(tok::r_paren) ||
5872 (!ParmDeclarator.getEllipsisLoc().isValid() &&
5873 !Actions.isUnexpandedParameterPackPermitted())) &&
5874 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
5875 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
5877 // Inform the actions module about the parameter declarator, so it gets
5878 // added to the current scope.
5879 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
5880 // Parse the default argument, if any. We parse the default
5881 // arguments in all dialects; the semantic analysis in
5882 // ActOnParamDefaultArgument will reject the default argument in
5884 if (Tok.is(tok::equal)) {
5885 SourceLocation EqualLoc = Tok.getLocation();
5887 // Parse the default argument
5888 if (D.getContext() == Declarator::MemberContext) {
5889 // If we're inside a class definition, cache the tokens
5890 // corresponding to the default argument. We'll actually parse
5891 // them when we see the end of the class definition.
5892 // FIXME: Can we use a smart pointer for Toks?
5893 DefArgToks = new CachedTokens;
5895 SourceLocation ArgStartLoc = NextToken().getLocation();
5896 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
5898 DefArgToks = nullptr;
5899 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5901 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5908 // The argument isn't actually potentially evaluated unless it is
5910 EnterExpressionEvaluationContext Eval(Actions,
5911 Sema::PotentiallyEvaluatedIfUsed,
5914 ExprResult DefArgResult;
5915 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5916 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5917 DefArgResult = ParseBraceInitializer();
5919 DefArgResult = ParseAssignmentExpression();
5920 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
5921 if (DefArgResult.isInvalid()) {
5922 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5923 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
5925 // Inform the actions module about the default argument
5926 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5927 DefArgResult.get());
5932 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5933 ParmDeclarator.getIdentifierLoc(),
5934 Param, DefArgToks));
5937 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
5938 if (!getLangOpts().CPlusPlus) {
5939 // We have ellipsis without a preceding ',', which is ill-formed
5940 // in C. Complain and provide the fix.
5941 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5942 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5943 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
5944 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
5945 // It looks like this was supposed to be a parameter pack. Warn and
5946 // point out where the ellipsis should have gone.
5947 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
5948 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
5949 << ParmEllipsis.isValid() << ParmEllipsis;
5950 if (ParmEllipsis.isValid()) {
5952 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
5954 Diag(ParmDeclarator.getIdentifierLoc(),
5955 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
5956 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
5958 << !ParmDeclarator.hasName();
5960 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
5961 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5964 // We can't have any more parameters after an ellipsis.
5968 // If the next token is a comma, consume it and keep reading arguments.
5969 } while (TryConsumeToken(tok::comma));
5972 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5973 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5974 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5975 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5976 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5977 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5978 /// attribute-specifier-seq[opt]
5979 void Parser::ParseBracketDeclarator(Declarator &D) {
5980 if (CheckProhibitedCXX11Attribute())
5983 BalancedDelimiterTracker T(*this, tok::l_square);
5986 // C array syntax has many features, but by-far the most common is [] and [4].
5987 // This code does a fast path to handle some of the most obvious cases.
5988 if (Tok.getKind() == tok::r_square) {
5990 ParsedAttributes attrs(AttrFactory);
5991 MaybeParseCXX11Attributes(attrs);
5993 // Remember that we parsed the empty array type.
5994 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
5995 T.getOpenLocation(),
5996 T.getCloseLocation()),
5997 attrs, T.getCloseLocation());
5999 } else if (Tok.getKind() == tok::numeric_constant &&
6000 GetLookAheadToken(1).is(tok::r_square)) {
6001 // [4] is very common. Parse the numeric constant expression.
6002 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6006 ParsedAttributes attrs(AttrFactory);
6007 MaybeParseCXX11Attributes(attrs);
6009 // Remember that we parsed a array type, and remember its features.
6010 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
6012 T.getOpenLocation(),
6013 T.getCloseLocation()),
6014 attrs, T.getCloseLocation());
6018 // If valid, this location is the position where we read the 'static' keyword.
6019 SourceLocation StaticLoc;
6020 TryConsumeToken(tok::kw_static, StaticLoc);
6022 // If there is a type-qualifier-list, read it now.
6023 // Type qualifiers in an array subscript are a C99 feature.
6024 DeclSpec DS(AttrFactory);
6025 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6027 // If we haven't already read 'static', check to see if there is one after the
6028 // type-qualifier-list.
6029 if (!StaticLoc.isValid())
6030 TryConsumeToken(tok::kw_static, StaticLoc);
6032 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6033 bool isStar = false;
6034 ExprResult NumElements;
6036 // Handle the case where we have '[*]' as the array size. However, a leading
6037 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6038 // the token after the star is a ']'. Since stars in arrays are
6039 // infrequent, use of lookahead is not costly here.
6040 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6041 ConsumeToken(); // Eat the '*'.
6043 if (StaticLoc.isValid()) {
6044 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6045 StaticLoc = SourceLocation(); // Drop the static.
6048 } else if (Tok.isNot(tok::r_square)) {
6049 // Note, in C89, this production uses the constant-expr production instead
6050 // of assignment-expr. The only difference is that assignment-expr allows
6051 // things like '=' and '*='. Sema rejects these in C89 mode because they
6052 // are not i-c-e's, so we don't need to distinguish between the two here.
6054 // Parse the constant-expression or assignment-expression now (depending
6056 if (getLangOpts().CPlusPlus) {
6057 NumElements = ParseConstantExpression();
6059 EnterExpressionEvaluationContext Unevaluated(Actions,
6060 Sema::ConstantEvaluated);
6062 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6065 if (StaticLoc.isValid()) {
6066 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6067 StaticLoc = SourceLocation(); // Drop the static.
6071 // If there was an error parsing the assignment-expression, recover.
6072 if (NumElements.isInvalid()) {
6073 D.setInvalidType(true);
6074 // If the expression was invalid, skip it.
6075 SkipUntil(tok::r_square, StopAtSemi);
6081 ParsedAttributes attrs(AttrFactory);
6082 MaybeParseCXX11Attributes(attrs);
6084 // Remember that we parsed a array type, and remember its features.
6085 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6086 StaticLoc.isValid(), isStar,
6088 T.getOpenLocation(),
6089 T.getCloseLocation()),
6090 attrs, T.getCloseLocation());
6093 /// Diagnose brackets before an identifier.
6094 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6095 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6096 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6098 SourceLocation StartBracketLoc = Tok.getLocation();
6099 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6101 while (Tok.is(tok::l_square)) {
6102 ParseBracketDeclarator(TempDeclarator);
6105 // Stuff the location of the start of the brackets into the Declarator.
6106 // The diagnostics from ParseDirectDeclarator will make more sense if
6107 // they use this location instead.
6108 if (Tok.is(tok::semi))
6109 D.getName().EndLocation = StartBracketLoc;
6111 SourceLocation SuggestParenLoc = Tok.getLocation();
6113 // Now that the brackets are removed, try parsing the declarator again.
6114 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6116 // Something went wrong parsing the brackets, in which case,
6117 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6119 if (TempDeclarator.getNumTypeObjects() == 0)
6122 // Determine if parens will need to be suggested in the diagnostic.
6123 bool NeedParens = false;
6124 if (D.getNumTypeObjects() != 0) {
6125 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6126 case DeclaratorChunk::Pointer:
6127 case DeclaratorChunk::Reference:
6128 case DeclaratorChunk::BlockPointer:
6129 case DeclaratorChunk::MemberPointer:
6130 case DeclaratorChunk::Pipe:
6133 case DeclaratorChunk::Array:
6134 case DeclaratorChunk::Function:
6135 case DeclaratorChunk::Paren:
6141 // Create a DeclaratorChunk for the inserted parens.
6142 ParsedAttributes attrs(AttrFactory);
6143 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6144 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6148 // Adding back the bracket info to the end of the Declarator.
6149 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6150 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6151 ParsedAttributes attrs(AttrFactory);
6152 attrs.set(Chunk.Common.AttrList);
6153 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6156 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6157 // If parentheses are required, always suggest them.
6158 if (!D.getIdentifier() && !NeedParens)
6161 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6163 // Generate the move bracket error message.
6164 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6165 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6168 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6169 << getLangOpts().CPlusPlus
6170 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6171 << FixItHint::CreateInsertion(EndLoc, ")")
6172 << FixItHint::CreateInsertionFromRange(
6173 EndLoc, CharSourceRange(BracketRange, true))
6174 << FixItHint::CreateRemoval(BracketRange);
6176 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6177 << getLangOpts().CPlusPlus
6178 << FixItHint::CreateInsertionFromRange(
6179 EndLoc, CharSourceRange(BracketRange, true))
6180 << FixItHint::CreateRemoval(BracketRange);
6184 /// [GNU] typeof-specifier:
6185 /// typeof ( expressions )
6186 /// typeof ( type-name )
6187 /// [GNU/C++] typeof unary-expression
6189 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6190 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6192 SourceLocation StartLoc = ConsumeToken();
6194 const bool hasParens = Tok.is(tok::l_paren);
6196 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
6197 Sema::ReuseLambdaContextDecl);
6201 SourceRange CastRange;
6202 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6203 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6205 DS.setTypeofParensRange(CastRange);
6207 if (CastRange.getEnd().isInvalid())
6208 // FIXME: Not accurate, the range gets one token more than it should.
6209 DS.SetRangeEnd(Tok.getLocation());
6211 DS.SetRangeEnd(CastRange.getEnd());
6215 DS.SetTypeSpecError();
6219 const char *PrevSpec = nullptr;
6221 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6222 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6224 Actions.getASTContext().getPrintingPolicy()))
6225 Diag(StartLoc, DiagID) << PrevSpec;
6229 // If we get here, the operand to the typeof was an expresion.
6230 if (Operand.isInvalid()) {
6231 DS.SetTypeSpecError();
6235 // We might need to transform the operand if it is potentially evaluated.
6236 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6237 if (Operand.isInvalid()) {
6238 DS.SetTypeSpecError();
6242 const char *PrevSpec = nullptr;
6244 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6245 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6246 DiagID, Operand.get(),
6247 Actions.getASTContext().getPrintingPolicy()))
6248 Diag(StartLoc, DiagID) << PrevSpec;
6251 /// [C11] atomic-specifier:
6252 /// _Atomic ( type-name )
6254 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6255 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6256 "Not an atomic specifier");
6258 SourceLocation StartLoc = ConsumeToken();
6259 BalancedDelimiterTracker T(*this, tok::l_paren);
6260 if (T.consumeOpen())
6263 TypeResult Result = ParseTypeName();
6264 if (Result.isInvalid()) {
6265 SkipUntil(tok::r_paren, StopAtSemi);
6272 if (T.getCloseLocation().isInvalid())
6275 DS.setTypeofParensRange(T.getRange());
6276 DS.SetRangeEnd(T.getCloseLocation());
6278 const char *PrevSpec = nullptr;
6280 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6281 DiagID, Result.get(),
6282 Actions.getASTContext().getPrintingPolicy()))
6283 Diag(StartLoc, DiagID) << PrevSpec;
6286 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6287 /// from TryAltiVecVectorToken.
6288 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6289 Token Next = NextToken();
6290 switch (Next.getKind()) {
6291 default: return false;
6294 case tok::kw_signed:
6295 case tok::kw_unsigned:
6300 case tok::kw_double:
6302 case tok::kw___bool:
6303 case tok::kw___pixel:
6304 Tok.setKind(tok::kw___vector);
6306 case tok::identifier:
6307 if (Next.getIdentifierInfo() == Ident_pixel) {
6308 Tok.setKind(tok::kw___vector);
6311 if (Next.getIdentifierInfo() == Ident_bool) {
6312 Tok.setKind(tok::kw___vector);
6319 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6320 const char *&PrevSpec, unsigned &DiagID,
6322 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6323 if (Tok.getIdentifierInfo() == Ident_vector) {
6324 Token Next = NextToken();
6325 switch (Next.getKind()) {
6328 case tok::kw_signed:
6329 case tok::kw_unsigned:
6334 case tok::kw_double:
6336 case tok::kw___bool:
6337 case tok::kw___pixel:
6338 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6340 case tok::identifier:
6341 if (Next.getIdentifierInfo() == Ident_pixel) {
6342 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6345 if (Next.getIdentifierInfo() == Ident_bool) {
6346 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6353 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6354 DS.isTypeAltiVecVector()) {
6355 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6357 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6358 DS.isTypeAltiVecVector()) {
6359 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);