1 //===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/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 "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringSwitch.h"
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
33 // C99 6.7: Declarations.
34 //===----------------------------------------------------------------------===//
37 /// type-name: [C99 6.7.6]
38 /// specifier-qualifier-list abstract-declarator[opt]
40 /// Called type-id in C++.
41 TypeResult Parser::ParseTypeName(SourceRange *Range,
42 Declarator::TheContext Context,
45 ParsedAttributes *Attrs) {
46 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
47 if (DSC == DSC_normal)
48 DSC = DSC_type_specifier;
50 // Parse the common declaration-specifiers piece.
51 DeclSpec DS(AttrFactory);
53 DS.addAttributes(Attrs->getList());
54 ParseSpecifierQualifierList(DS, AS, DSC);
56 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58 // Parse the abstract-declarator, if present.
59 Declarator DeclaratorInfo(DS, Context);
60 ParseDeclarator(DeclaratorInfo);
62 *Range = DeclaratorInfo.getSourceRange();
64 if (DeclaratorInfo.isInvalidType())
67 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
71 /// isAttributeLateParsed - Return true if the attribute has arguments that
72 /// require late parsing.
73 static bool isAttributeLateParsed(const IdentifierInfo &II) {
74 #define CLANG_ATTR_LATE_PARSED_LIST
75 return llvm::StringSwitch<bool>(II.getName())
76 #include "clang/Parse/AttrParserStringSwitches.inc"
78 #undef CLANG_ATTR_LATE_PARSED_LIST
81 /// ParseGNUAttributes - Parse a non-empty attributes list.
85 /// attributes attribute
88 /// '__attribute__' '(' '(' attribute-list ')' ')'
90 /// [GNU] attribute-list:
92 /// attribute_list ',' attrib
97 /// attrib-name '(' identifier ')'
98 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
99 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
101 /// [GNU] attrib-name:
107 /// Whether an attribute takes an 'identifier' is determined by the
108 /// attrib-name. GCC's behavior here is not worth imitating:
110 /// * In C mode, if the attribute argument list starts with an identifier
111 /// followed by a ',' or an ')', and the identifier doesn't resolve to
112 /// a type, it is parsed as an identifier. If the attribute actually
113 /// wanted an expression, it's out of luck (but it turns out that no
114 /// attributes work that way, because C constant expressions are very
116 /// * In C++ mode, if the attribute argument list starts with an identifier,
117 /// and the attribute *wants* an identifier, it is parsed as an identifier.
118 /// At block scope, any additional tokens between the identifier and the
119 /// ',' or ')' are ignored, otherwise they produce a parse error.
121 /// We follow the C++ model, but don't allow junk after the identifier.
122 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
123 SourceLocation *endLoc,
124 LateParsedAttrList *LateAttrs,
126 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
128 while (Tok.is(tok::kw___attribute)) {
130 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
132 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
135 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
136 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
139 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
141 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
142 if (TryConsumeToken(tok::comma))
145 // Expect an identifier or declaration specifier (const, int, etc.)
146 if (Tok.isAnnotation())
148 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
152 SourceLocation AttrNameLoc = ConsumeToken();
154 if (Tok.isNot(tok::l_paren)) {
155 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
156 AttributeList::AS_GNU);
160 // Handle "parameterized" attributes
161 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
162 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
163 SourceLocation(), AttributeList::AS_GNU, D);
167 // Handle attributes with arguments that require late parsing.
168 LateParsedAttribute *LA =
169 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
170 LateAttrs->push_back(LA);
172 // Attributes in a class are parsed at the end of the class, along
173 // with other late-parsed declarations.
174 if (!ClassStack.empty() && !LateAttrs->parseSoon())
175 getCurrentClass().LateParsedDeclarations.push_back(LA);
177 // consume everything up to and including the matching right parens
178 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
182 Eof.setLocation(Tok.getLocation());
183 LA->Toks.push_back(Eof);
186 if (ExpectAndConsume(tok::r_paren))
187 SkipUntil(tok::r_paren, StopAtSemi);
188 SourceLocation Loc = Tok.getLocation();
189 if (ExpectAndConsume(tok::r_paren))
190 SkipUntil(tok::r_paren, StopAtSemi);
196 /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
197 static StringRef normalizeAttrName(StringRef Name) {
198 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
199 Name = Name.drop_front(2).drop_back(2);
203 /// \brief Determine whether the given attribute has an identifier argument.
204 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
205 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
206 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
207 #include "clang/Parse/AttrParserStringSwitches.inc"
209 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
212 /// \brief Determine whether the given attribute parses a type argument.
213 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
214 #define CLANG_ATTR_TYPE_ARG_LIST
215 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
216 #include "clang/Parse/AttrParserStringSwitches.inc"
218 #undef CLANG_ATTR_TYPE_ARG_LIST
221 /// \brief Determine whether the given attribute requires parsing its arguments
222 /// in an unevaluated context or not.
223 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
224 #define CLANG_ATTR_ARG_CONTEXT_LIST
225 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
226 #include "clang/Parse/AttrParserStringSwitches.inc"
228 #undef CLANG_ATTR_ARG_CONTEXT_LIST
231 IdentifierLoc *Parser::ParseIdentifierLoc() {
232 assert(Tok.is(tok::identifier) && "expected an identifier");
233 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
235 Tok.getIdentifierInfo());
240 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
241 SourceLocation AttrNameLoc,
242 ParsedAttributes &Attrs,
243 SourceLocation *EndLoc,
244 IdentifierInfo *ScopeName,
245 SourceLocation ScopeLoc,
246 AttributeList::Syntax Syntax) {
247 BalancedDelimiterTracker Parens(*this, tok::l_paren);
248 Parens.consumeOpen();
251 if (Tok.isNot(tok::r_paren))
254 if (Parens.consumeClose())
261 Attrs.addNewTypeAttr(&AttrName,
262 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
263 ScopeName, ScopeLoc, T.get(), Syntax);
265 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
266 ScopeName, ScopeLoc, nullptr, 0, Syntax);
269 unsigned Parser::ParseAttributeArgsCommon(
270 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
271 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
272 SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
273 // Ignore the left paren location for now.
277 if (Tok.is(tok::identifier)) {
278 // If this attribute wants an 'identifier' argument, make it so.
279 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
280 AttributeList::Kind AttrKind =
281 AttributeList::getKind(AttrName, ScopeName, Syntax);
283 // If we don't know how to parse this attribute, but this is the only
284 // token in this argument, assume it's meant to be an identifier.
285 if (AttrKind == AttributeList::UnknownAttribute ||
286 AttrKind == AttributeList::IgnoredAttribute) {
287 const Token &Next = NextToken();
288 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
292 ArgExprs.push_back(ParseIdentifierLoc());
295 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
297 if (!ArgExprs.empty())
300 // Parse the non-empty comma-separated list of expressions.
302 std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated;
303 if (attributeParsedArgsUnevaluated(*AttrName))
305 new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated));
308 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
309 if (ArgExpr.isInvalid()) {
310 SkipUntil(tok::r_paren, StopAtSemi);
313 ArgExprs.push_back(ArgExpr.get());
314 // Eat the comma, move to the next argument
315 } while (TryConsumeToken(tok::comma));
318 SourceLocation RParen = Tok.getLocation();
319 if (!ExpectAndConsume(tok::r_paren)) {
320 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
321 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
322 ArgExprs.data(), ArgExprs.size(), Syntax);
328 return static_cast<unsigned>(ArgExprs.size());
331 /// Parse the arguments to a parameterized GNU attribute or
332 /// a C++11 attribute in "gnu" namespace.
333 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
334 SourceLocation AttrNameLoc,
335 ParsedAttributes &Attrs,
336 SourceLocation *EndLoc,
337 IdentifierInfo *ScopeName,
338 SourceLocation ScopeLoc,
339 AttributeList::Syntax Syntax,
342 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
344 AttributeList::Kind AttrKind =
345 AttributeList::getKind(AttrName, ScopeName, Syntax);
347 if (AttrKind == AttributeList::AT_Availability) {
348 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
351 } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
352 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
353 ScopeName, ScopeLoc, Syntax);
355 } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
356 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
357 ScopeName, ScopeLoc, Syntax);
359 } else if (attributeIsTypeArgAttr(*AttrName)) {
360 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
365 // These may refer to the function arguments, but need to be parsed early to
366 // participate in determining whether it's a redeclaration.
367 std::unique_ptr<ParseScope> PrototypeScope;
368 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
369 D && D->isFunctionDeclarator()) {
370 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
371 PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope |
372 Scope::FunctionDeclarationScope |
374 for (unsigned i = 0; i != FTI.NumParams; ++i) {
375 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
376 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
380 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
384 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
385 SourceLocation AttrNameLoc,
386 ParsedAttributes &Attrs) {
387 // If the attribute isn't known, we will not attempt to parse any
389 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
390 getTargetInfo().getTriple(), getLangOpts())) {
391 // Eat the left paren, then skip to the ending right paren.
393 SkipUntil(tok::r_paren);
397 SourceLocation OpenParenLoc = Tok.getLocation();
399 if (AttrName->getName() == "property") {
400 // The property declspec is more complex in that it can take one or two
401 // assignment expressions as a parameter, but the lhs of the assignment
402 // must be named get or put.
404 BalancedDelimiterTracker T(*this, tok::l_paren);
405 T.expectAndConsume(diag::err_expected_lparen_after,
406 AttrName->getNameStart(), tok::r_paren);
411 AK_Get = 1 // indices into AccessorNames
413 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
414 bool HasInvalidAccessor = false;
416 // Parse the accessor specifications.
418 // Stop if this doesn't look like an accessor spec.
419 if (!Tok.is(tok::identifier)) {
420 // If the user wrote a completely empty list, use a special diagnostic.
421 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
422 AccessorNames[AK_Put] == nullptr &&
423 AccessorNames[AK_Get] == nullptr) {
424 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
428 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
433 SourceLocation KindLoc = Tok.getLocation();
434 StringRef KindStr = Tok.getIdentifierInfo()->getName();
435 if (KindStr == "get") {
437 } else if (KindStr == "put") {
440 // Recover from the common mistake of using 'set' instead of 'put'.
441 } else if (KindStr == "set") {
442 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
443 << FixItHint::CreateReplacement(KindLoc, "put");
446 // Handle the mistake of forgetting the accessor kind by skipping
448 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
449 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
451 HasInvalidAccessor = true;
452 goto next_property_accessor;
454 // Otherwise, complain about the unknown accessor kind.
456 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
457 HasInvalidAccessor = true;
460 // Try to keep parsing unless it doesn't look like an accessor spec.
461 if (!NextToken().is(tok::equal))
465 // Consume the identifier.
469 if (!TryConsumeToken(tok::equal)) {
470 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
475 // Expect the method name.
476 if (!Tok.is(tok::identifier)) {
477 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
481 if (Kind == AK_Invalid) {
482 // Just drop invalid accessors.
483 } else if (AccessorNames[Kind] != nullptr) {
484 // Complain about the repeated accessor, ignore it, and keep parsing.
485 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
487 AccessorNames[Kind] = Tok.getIdentifierInfo();
491 next_property_accessor:
492 // Keep processing accessors until we run out.
493 if (TryConsumeToken(tok::comma))
496 // If we run into the ')', stop without consuming it.
497 if (Tok.is(tok::r_paren))
500 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
504 // Only add the property attribute if it was well-formed.
505 if (!HasInvalidAccessor)
506 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
507 AccessorNames[AK_Get], AccessorNames[AK_Put],
508 AttributeList::AS_Declspec);
510 return !HasInvalidAccessor;
514 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
515 SourceLocation(), AttributeList::AS_Declspec);
517 // If this attribute's args were parsed, and it was expected to have
518 // arguments but none were provided, emit a diagnostic.
519 const AttributeList *Attr = Attrs.getList();
520 if (Attr && Attr->getMaxArgs() && !NumArgs) {
521 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
527 /// [MS] decl-specifier:
528 /// __declspec ( extended-decl-modifier-seq )
530 /// [MS] extended-decl-modifier-seq:
531 /// extended-decl-modifier[opt]
532 /// extended-decl-modifier extended-decl-modifier-seq
533 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
534 SourceLocation *End) {
535 assert((getLangOpts().MicrosoftExt || getLangOpts().Borland ||
536 getLangOpts().CUDA) &&
537 "Incorrect language options for parsing __declspec");
538 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
540 while (Tok.is(tok::kw___declspec)) {
542 BalancedDelimiterTracker T(*this, tok::l_paren);
543 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
547 // An empty declspec is perfectly legal and should not warn. Additionally,
548 // you can specify multiple attributes per declspec.
549 while (Tok.isNot(tok::r_paren)) {
550 // Attribute not present.
551 if (TryConsumeToken(tok::comma))
554 // We expect either a well-known identifier or a generic string. Anything
555 // else is a malformed declspec.
556 bool IsString = Tok.getKind() == tok::string_literal;
557 if (!IsString && Tok.getKind() != tok::identifier &&
558 Tok.getKind() != tok::kw_restrict) {
559 Diag(Tok, diag::err_ms_declspec_type);
564 IdentifierInfo *AttrName;
565 SourceLocation AttrNameLoc;
567 SmallString<8> StrBuffer;
568 bool Invalid = false;
569 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
574 AttrName = PP.getIdentifierInfo(Str);
575 AttrNameLoc = ConsumeStringToken();
577 AttrName = Tok.getIdentifierInfo();
578 AttrNameLoc = ConsumeToken();
581 bool AttrHandled = false;
583 // Parse attribute arguments.
584 if (Tok.is(tok::l_paren))
585 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
586 else if (AttrName->getName() == "property")
587 // The property attribute must have an argument list.
588 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
589 << AttrName->getName();
592 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
593 AttributeList::AS_Declspec);
597 *End = T.getCloseLocation();
601 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
602 // Treat these like attributes
604 switch (Tok.getKind()) {
605 case tok::kw___fastcall:
606 case tok::kw___stdcall:
607 case tok::kw___thiscall:
608 case tok::kw___cdecl:
609 case tok::kw___vectorcall:
610 case tok::kw___ptr64:
612 case tok::kw___ptr32:
613 case tok::kw___unaligned:
615 case tok::kw___uptr: {
616 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
617 SourceLocation AttrNameLoc = ConsumeToken();
618 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
619 AttributeList::AS_Keyword);
628 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
629 SourceLocation StartLoc = Tok.getLocation();
630 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
632 if (EndLoc.isValid()) {
633 SourceRange Range(StartLoc, EndLoc);
634 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
638 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
639 SourceLocation EndLoc;
642 switch (Tok.getKind()) {
644 case tok::kw_volatile:
645 case tok::kw___fastcall:
646 case tok::kw___stdcall:
647 case tok::kw___thiscall:
648 case tok::kw___cdecl:
649 case tok::kw___vectorcall:
650 case tok::kw___ptr32:
651 case tok::kw___ptr64:
653 case tok::kw___unaligned:
656 EndLoc = ConsumeToken();
664 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
665 // Treat these like attributes
666 while (Tok.is(tok::kw___pascal)) {
667 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
668 SourceLocation AttrNameLoc = ConsumeToken();
669 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
670 AttributeList::AS_Keyword);
674 void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
675 // Treat these like attributes
676 while (Tok.is(tok::kw___kernel)) {
677 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
678 SourceLocation AttrNameLoc = ConsumeToken();
679 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
680 AttributeList::AS_Keyword);
684 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
685 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
686 SourceLocation AttrNameLoc = Tok.getLocation();
687 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
688 AttributeList::AS_Keyword);
691 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
692 // Treat these like attributes, even though they're type specifiers.
694 switch (Tok.getKind()) {
695 case tok::kw__Nonnull:
696 case tok::kw__Nullable:
697 case tok::kw__Null_unspecified: {
698 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
699 SourceLocation AttrNameLoc = ConsumeToken();
700 if (!getLangOpts().ObjC1)
701 Diag(AttrNameLoc, diag::ext_nullability)
703 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
704 AttributeList::AS_Keyword);
713 static bool VersionNumberSeparator(const char Separator) {
714 return (Separator == '.' || Separator == '_');
717 /// \brief Parse a version number.
721 /// simple-integer ',' simple-integer
722 /// simple-integer ',' simple-integer ',' simple-integer
723 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
724 Range = Tok.getLocation();
726 if (!Tok.is(tok::numeric_constant)) {
727 Diag(Tok, diag::err_expected_version);
728 SkipUntil(tok::comma, tok::r_paren,
729 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
730 return VersionTuple();
733 // Parse the major (and possibly minor and subminor) versions, which
734 // are stored in the numeric constant. We utilize a quirk of the
735 // lexer, which is that it handles something like 1.2.3 as a single
736 // numeric constant, rather than two separate tokens.
737 SmallString<512> Buffer;
738 Buffer.resize(Tok.getLength()+1);
739 const char *ThisTokBegin = &Buffer[0];
741 // Get the spelling of the token, which eliminates trigraphs, etc.
742 bool Invalid = false;
743 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
745 return VersionTuple();
747 // Parse the major version.
748 unsigned AfterMajor = 0;
750 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
751 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
755 if (AfterMajor == 0) {
756 Diag(Tok, diag::err_expected_version);
757 SkipUntil(tok::comma, tok::r_paren,
758 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
759 return VersionTuple();
762 if (AfterMajor == ActualLength) {
765 // We only had a single version component.
767 Diag(Tok, diag::err_zero_version);
768 return VersionTuple();
771 return VersionTuple(Major);
774 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
775 if (!VersionNumberSeparator(AfterMajorSeparator)
776 || (AfterMajor + 1 == ActualLength)) {
777 Diag(Tok, diag::err_expected_version);
778 SkipUntil(tok::comma, tok::r_paren,
779 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
780 return VersionTuple();
783 // Parse the minor version.
784 unsigned AfterMinor = AfterMajor + 1;
786 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
787 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
791 if (AfterMinor == ActualLength) {
794 // We had major.minor.
795 if (Major == 0 && Minor == 0) {
796 Diag(Tok, diag::err_zero_version);
797 return VersionTuple();
800 return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
803 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
804 // If what follows is not a '.' or '_', we have a problem.
805 if (!VersionNumberSeparator(AfterMinorSeparator)) {
806 Diag(Tok, diag::err_expected_version);
807 SkipUntil(tok::comma, tok::r_paren,
808 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
809 return VersionTuple();
812 // Warn if separators, be it '.' or '_', do not match.
813 if (AfterMajorSeparator != AfterMinorSeparator)
814 Diag(Tok, diag::warn_expected_consistent_version_separator);
816 // Parse the subminor version.
817 unsigned AfterSubminor = AfterMinor + 1;
818 unsigned Subminor = 0;
819 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
820 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
824 if (AfterSubminor != ActualLength) {
825 Diag(Tok, diag::err_expected_version);
826 SkipUntil(tok::comma, tok::r_paren,
827 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
828 return VersionTuple();
831 return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
834 /// \brief Parse the contents of the "availability" attribute.
836 /// availability-attribute:
837 /// 'availability' '(' platform ',' version-arg-list, opt-message')'
842 /// version-arg-list:
844 /// version-arg ',' version-arg-list
847 /// 'introduced' '=' version
848 /// 'deprecated' '=' version
849 /// 'obsoleted' = version
852 /// 'message' '=' <string>
853 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
854 SourceLocation AvailabilityLoc,
855 ParsedAttributes &attrs,
856 SourceLocation *endLoc,
857 IdentifierInfo *ScopeName,
858 SourceLocation ScopeLoc,
859 AttributeList::Syntax Syntax) {
860 enum { Introduced, Deprecated, Obsoleted, Unknown };
861 AvailabilityChange Changes[Unknown];
862 ExprResult MessageExpr;
865 BalancedDelimiterTracker T(*this, tok::l_paren);
866 if (T.consumeOpen()) {
867 Diag(Tok, diag::err_expected) << tok::l_paren;
871 // Parse the platform name,
872 if (Tok.isNot(tok::identifier)) {
873 Diag(Tok, diag::err_availability_expected_platform);
874 SkipUntil(tok::r_paren, StopAtSemi);
877 IdentifierLoc *Platform = ParseIdentifierLoc();
879 // Parse the ',' following the platform name.
880 if (ExpectAndConsume(tok::comma)) {
881 SkipUntil(tok::r_paren, StopAtSemi);
885 // If we haven't grabbed the pointers for the identifiers
886 // "introduced", "deprecated", and "obsoleted", do so now.
887 if (!Ident_introduced) {
888 Ident_introduced = PP.getIdentifierInfo("introduced");
889 Ident_deprecated = PP.getIdentifierInfo("deprecated");
890 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
891 Ident_unavailable = PP.getIdentifierInfo("unavailable");
892 Ident_message = PP.getIdentifierInfo("message");
895 // Parse the set of introductions/deprecations/removals.
896 SourceLocation UnavailableLoc;
898 if (Tok.isNot(tok::identifier)) {
899 Diag(Tok, diag::err_availability_expected_change);
900 SkipUntil(tok::r_paren, StopAtSemi);
903 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
904 SourceLocation KeywordLoc = ConsumeToken();
906 if (Keyword == Ident_unavailable) {
907 if (UnavailableLoc.isValid()) {
908 Diag(KeywordLoc, diag::err_availability_redundant)
909 << Keyword << SourceRange(UnavailableLoc);
911 UnavailableLoc = KeywordLoc;
915 if (Tok.isNot(tok::equal)) {
916 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
917 SkipUntil(tok::r_paren, StopAtSemi);
921 if (Keyword == Ident_message) {
922 if (Tok.isNot(tok::string_literal)) {
923 Diag(Tok, diag::err_expected_string_literal)
924 << /*Source='availability attribute'*/2;
925 SkipUntil(tok::r_paren, StopAtSemi);
928 MessageExpr = ParseStringLiteralExpression();
929 // Also reject wide string literals.
930 if (StringLiteral *MessageStringLiteral =
931 cast_or_null<StringLiteral>(MessageExpr.get())) {
932 if (MessageStringLiteral->getCharByteWidth() != 1) {
933 Diag(MessageStringLiteral->getSourceRange().getBegin(),
934 diag::err_expected_string_literal)
935 << /*Source='availability attribute'*/ 2;
936 SkipUntil(tok::r_paren, StopAtSemi);
943 // Special handling of 'NA' only when applied to introduced or
945 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
946 Tok.is(tok::identifier)) {
947 IdentifierInfo *NA = Tok.getIdentifierInfo();
948 if (NA->getName() == "NA") {
950 if (Keyword == Ident_introduced)
951 UnavailableLoc = KeywordLoc;
956 SourceRange VersionRange;
957 VersionTuple Version = ParseVersionTuple(VersionRange);
959 if (Version.empty()) {
960 SkipUntil(tok::r_paren, StopAtSemi);
965 if (Keyword == Ident_introduced)
967 else if (Keyword == Ident_deprecated)
969 else if (Keyword == Ident_obsoleted)
974 if (Index < Unknown) {
975 if (!Changes[Index].KeywordLoc.isInvalid()) {
976 Diag(KeywordLoc, diag::err_availability_redundant)
978 << SourceRange(Changes[Index].KeywordLoc,
979 Changes[Index].VersionRange.getEnd());
982 Changes[Index].KeywordLoc = KeywordLoc;
983 Changes[Index].Version = Version;
984 Changes[Index].VersionRange = VersionRange;
986 Diag(KeywordLoc, diag::err_availability_unknown_change)
987 << Keyword << VersionRange;
990 } while (TryConsumeToken(tok::comma));
993 if (T.consumeClose())
997 *endLoc = T.getCloseLocation();
999 // The 'unavailable' availability cannot be combined with any other
1000 // availability changes. Make sure that hasn't happened.
1001 if (UnavailableLoc.isValid()) {
1002 bool Complained = false;
1003 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1004 if (Changes[Index].KeywordLoc.isValid()) {
1006 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1007 << SourceRange(Changes[Index].KeywordLoc,
1008 Changes[Index].VersionRange.getEnd());
1012 // Clear out the availability.
1013 Changes[Index] = AvailabilityChange();
1018 // Record this attribute
1019 attrs.addNew(&Availability,
1020 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1021 ScopeName, ScopeLoc,
1023 Changes[Introduced],
1024 Changes[Deprecated],
1026 UnavailableLoc, MessageExpr.get(),
1030 /// \brief Parse the contents of the "objc_bridge_related" attribute.
1031 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1035 /// opt-class_method:
1036 /// Identifier: | <empty>
1038 /// opt-instance_method:
1039 /// Identifier | <empty>
1041 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1042 SourceLocation ObjCBridgeRelatedLoc,
1043 ParsedAttributes &attrs,
1044 SourceLocation *endLoc,
1045 IdentifierInfo *ScopeName,
1046 SourceLocation ScopeLoc,
1047 AttributeList::Syntax Syntax) {
1049 BalancedDelimiterTracker T(*this, tok::l_paren);
1050 if (T.consumeOpen()) {
1051 Diag(Tok, diag::err_expected) << tok::l_paren;
1055 // Parse the related class name.
1056 if (Tok.isNot(tok::identifier)) {
1057 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1058 SkipUntil(tok::r_paren, StopAtSemi);
1061 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1062 if (ExpectAndConsume(tok::comma)) {
1063 SkipUntil(tok::r_paren, StopAtSemi);
1067 // Parse optional class method name.
1068 IdentifierLoc *ClassMethod = nullptr;
1069 if (Tok.is(tok::identifier)) {
1070 ClassMethod = ParseIdentifierLoc();
1071 if (!TryConsumeToken(tok::colon)) {
1072 Diag(Tok, diag::err_objcbridge_related_selector_name);
1073 SkipUntil(tok::r_paren, StopAtSemi);
1077 if (!TryConsumeToken(tok::comma)) {
1078 if (Tok.is(tok::colon))
1079 Diag(Tok, diag::err_objcbridge_related_selector_name);
1081 Diag(Tok, diag::err_expected) << tok::comma;
1082 SkipUntil(tok::r_paren, StopAtSemi);
1086 // Parse optional instance method name.
1087 IdentifierLoc *InstanceMethod = nullptr;
1088 if (Tok.is(tok::identifier))
1089 InstanceMethod = ParseIdentifierLoc();
1090 else if (Tok.isNot(tok::r_paren)) {
1091 Diag(Tok, diag::err_expected) << tok::r_paren;
1092 SkipUntil(tok::r_paren, StopAtSemi);
1097 if (T.consumeClose())
1101 *endLoc = T.getCloseLocation();
1103 // Record this attribute
1104 attrs.addNew(&ObjCBridgeRelated,
1105 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1106 ScopeName, ScopeLoc,
1113 // Late Parsed Attributes:
1114 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1116 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1118 void Parser::LateParsedClass::ParseLexedAttributes() {
1119 Self->ParseLexedAttributes(*Class);
1122 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1123 Self->ParseLexedAttribute(*this, true, false);
1126 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1127 /// scope appropriately.
1128 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1129 // Deal with templates
1130 // FIXME: Test cases to make sure this does the right thing for templates.
1131 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1132 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1134 if (HasTemplateScope)
1135 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1137 // Set or update the scope flags.
1138 bool AlreadyHasClassScope = Class.TopLevelClass;
1139 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1140 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1141 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1143 // Enter the scope of nested classes
1144 if (!AlreadyHasClassScope)
1145 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1146 Class.TagOrTemplate);
1147 if (!Class.LateParsedDeclarations.empty()) {
1148 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1149 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1153 if (!AlreadyHasClassScope)
1154 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1155 Class.TagOrTemplate);
1159 /// \brief Parse all attributes in LAs, and attach them to Decl D.
1160 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1161 bool EnterScope, bool OnDefinition) {
1162 assert(LAs.parseSoon() &&
1163 "Attribute list should be marked for immediate parsing.");
1164 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1167 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1174 /// \brief Finish parsing an attribute for which parsing was delayed.
1175 /// This will be called at the end of parsing a class declaration
1176 /// for each LateParsedAttribute. We consume the saved tokens and
1177 /// create an attribute with the arguments filled in. We add this
1178 /// to the Attribute list for the decl.
1179 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1180 bool EnterScope, bool OnDefinition) {
1181 // Create a fake EOF so that attribute parsing won't go off the end of the
1184 AttrEnd.startToken();
1185 AttrEnd.setKind(tok::eof);
1186 AttrEnd.setLocation(Tok.getLocation());
1187 AttrEnd.setEofData(LA.Toks.data());
1188 LA.Toks.push_back(AttrEnd);
1190 // Append the current token at the end of the new token stream so that it
1191 // doesn't get lost.
1192 LA.Toks.push_back(Tok);
1193 PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
1194 // Consume the previously pushed token.
1195 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1197 ParsedAttributes Attrs(AttrFactory);
1198 SourceLocation endLoc;
1200 if (LA.Decls.size() > 0) {
1201 Decl *D = LA.Decls[0];
1202 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1203 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1205 // Allow 'this' within late-parsed attributes.
1206 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1207 ND && ND->isCXXInstanceMember());
1209 if (LA.Decls.size() == 1) {
1210 // If the Decl is templatized, add template parameters to scope.
1211 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1212 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1213 if (HasTemplateScope)
1214 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1216 // If the Decl is on a function, add function parameters to the scope.
1217 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1218 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
1220 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1222 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1223 nullptr, SourceLocation(), AttributeList::AS_GNU,
1227 Actions.ActOnExitFunctionContext();
1228 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1230 if (HasTemplateScope) {
1234 // If there are multiple decls, then the decl cannot be within the
1236 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1237 nullptr, SourceLocation(), AttributeList::AS_GNU,
1241 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1244 const AttributeList *AL = Attrs.getList();
1245 if (OnDefinition && AL && !AL->isCXX11Attribute() &&
1247 Diag(Tok, diag::warn_attribute_on_function_definition)
1250 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1251 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1253 // Due to a parsing error, we either went over the cached tokens or
1254 // there are still cached tokens left, so we skip the leftover tokens.
1255 while (Tok.isNot(tok::eof))
1258 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1262 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1263 SourceLocation AttrNameLoc,
1264 ParsedAttributes &Attrs,
1265 SourceLocation *EndLoc,
1266 IdentifierInfo *ScopeName,
1267 SourceLocation ScopeLoc,
1268 AttributeList::Syntax Syntax) {
1269 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1271 BalancedDelimiterTracker T(*this, tok::l_paren);
1274 if (Tok.isNot(tok::identifier)) {
1275 Diag(Tok, diag::err_expected) << tok::identifier;
1279 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1281 if (ExpectAndConsume(tok::comma)) {
1286 SourceRange MatchingCTypeRange;
1287 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1288 if (MatchingCType.isInvalid()) {
1293 bool LayoutCompatible = false;
1294 bool MustBeNull = false;
1295 while (TryConsumeToken(tok::comma)) {
1296 if (Tok.isNot(tok::identifier)) {
1297 Diag(Tok, diag::err_expected) << tok::identifier;
1301 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1302 if (Flag->isStr("layout_compatible"))
1303 LayoutCompatible = true;
1304 else if (Flag->isStr("must_be_null"))
1307 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1311 ConsumeToken(); // consume flag
1314 if (!T.consumeClose()) {
1315 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1316 ArgumentKind, MatchingCType.get(),
1317 LayoutCompatible, MustBeNull, Syntax);
1321 *EndLoc = T.getCloseLocation();
1324 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1325 /// of a C++11 attribute-specifier in a location where an attribute is not
1326 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1329 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1330 /// this doesn't appear to actually be an attribute-specifier, and the caller
1331 /// should try to parse it.
1332 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1333 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1335 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1336 case CAK_NotAttributeSpecifier:
1337 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1340 case CAK_InvalidAttributeSpecifier:
1341 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1344 case CAK_AttributeSpecifier:
1345 // Parse and discard the attributes.
1346 SourceLocation BeginLoc = ConsumeBracket();
1348 SkipUntil(tok::r_square);
1349 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1350 SourceLocation EndLoc = ConsumeBracket();
1351 Diag(BeginLoc, diag::err_attributes_not_allowed)
1352 << SourceRange(BeginLoc, EndLoc);
1355 llvm_unreachable("All cases handled above.");
1358 /// \brief We have found the opening square brackets of a C++11
1359 /// attribute-specifier in a location where an attribute is not permitted, but
1360 /// we know where the attributes ought to be written. Parse them anyway, and
1361 /// provide a fixit moving them to the right place.
1362 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1363 SourceLocation CorrectLocation) {
1364 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1365 Tok.is(tok::kw_alignas));
1367 // Consume the attributes.
1368 SourceLocation Loc = Tok.getLocation();
1369 ParseCXX11Attributes(Attrs);
1370 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1372 Diag(Loc, diag::err_attributes_not_allowed)
1373 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1374 << FixItHint::CreateRemoval(AttrRange);
1377 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
1378 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
1382 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) {
1383 AttributeList *AttrList = attrs.getList();
1385 if (AttrList->isCXX11Attribute()) {
1386 Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr)
1387 << AttrList->getName();
1388 AttrList->setInvalid();
1390 AttrList = AttrList->getNext();
1394 // As an exception to the rule, __declspec(align(...)) before the
1395 // class-key affects the type instead of the variable.
1396 void Parser::handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs,
1398 Sema::TagUseKind TUK) {
1399 if (TUK == Sema::TUK_Reference)
1402 ParsedAttributes &PA = DS.getAttributes();
1403 AttributeList *AL = PA.getList();
1404 AttributeList *Prev = nullptr;
1406 AttributeList *Next = AL->getNext();
1408 // We only consider attributes using the appropriate '__declspec' spelling,
1409 // this behavior doesn't extend to any other spellings.
1410 if (AL->getKind() == AttributeList::AT_Aligned &&
1411 AL->isDeclspecAttribute()) {
1412 // Stitch the attribute into the tag's attribute list.
1413 AL->setNext(nullptr);
1416 // Remove the attribute from the variable's attribute list.
1418 // Set the last variable attribute's next attribute to be the attribute
1419 // after the current one.
1420 Prev->setNext(Next);
1422 // Removing the head of the list requires us to reset the head to the
1434 /// ParseDeclaration - Parse a full 'declaration', which consists of
1435 /// declaration-specifiers, some number of declarators, and a semicolon.
1436 /// 'Context' should be a Declarator::TheContext value. This returns the
1437 /// location of the semicolon in DeclEnd.
1439 /// declaration: [C99 6.7]
1440 /// block-declaration ->
1441 /// simple-declaration
1443 /// [C++] template-declaration
1444 /// [C++] namespace-definition
1445 /// [C++] using-directive
1446 /// [C++] using-declaration
1447 /// [C++11/C11] static_assert-declaration
1448 /// others... [FIXME]
1450 Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
1451 SourceLocation &DeclEnd,
1452 ParsedAttributesWithRange &attrs) {
1453 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1454 // Must temporarily exit the objective-c container scope for
1455 // parsing c none objective-c decls.
1456 ObjCDeclContextSwitch ObjCDC(*this);
1458 Decl *SingleDecl = nullptr;
1459 Decl *OwnedType = nullptr;
1460 switch (Tok.getKind()) {
1461 case tok::kw_template:
1462 case tok::kw_export:
1463 ProhibitAttributes(attrs);
1464 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
1466 case tok::kw_inline:
1467 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1468 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1469 ProhibitAttributes(attrs);
1470 SourceLocation InlineLoc = ConsumeToken();
1471 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
1474 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1476 case tok::kw_namespace:
1477 ProhibitAttributes(attrs);
1478 SingleDecl = ParseNamespace(Context, DeclEnd);
1481 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1482 DeclEnd, attrs, &OwnedType);
1484 case tok::kw_static_assert:
1485 case tok::kw__Static_assert:
1486 ProhibitAttributes(attrs);
1487 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1490 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1493 // This routine returns a DeclGroup, if the thing we parsed only contains a
1494 // single decl, convert it now. Alias declarations can also declare a type;
1495 // include that too if it is present.
1496 return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
1499 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1500 /// declaration-specifiers init-declarator-list[opt] ';'
1501 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1502 /// init-declarator-list ';'
1503 ///[C90/C++]init-declarator-list ';' [TODO]
1504 /// [OMP] threadprivate-directive [TODO]
1506 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1507 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1509 /// If RequireSemi is false, this does not check for a ';' at the end of the
1510 /// declaration. If it is true, it checks for and eats it.
1512 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1513 /// of a simple-declaration. If we find that we are, we also parse the
1514 /// for-range-initializer, and place it here.
1515 Parser::DeclGroupPtrTy
1516 Parser::ParseSimpleDeclaration(unsigned Context,
1517 SourceLocation &DeclEnd,
1518 ParsedAttributesWithRange &Attrs,
1519 bool RequireSemi, ForRangeInit *FRI) {
1520 // Parse the common declaration-specifiers piece.
1521 ParsingDeclSpec DS(*this);
1523 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1524 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1526 // If we had a free-standing type definition with a missing semicolon, we
1527 // may get this far before the problem becomes obvious.
1528 if (DS.hasTagDefinition() &&
1529 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1530 return DeclGroupPtrTy();
1532 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1533 // declaration-specifiers init-declarator-list[opt] ';'
1534 if (Tok.is(tok::semi)) {
1535 ProhibitAttributes(Attrs);
1536 DeclEnd = Tok.getLocation();
1537 if (RequireSemi) ConsumeToken();
1538 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1540 DS.complete(TheDecl);
1541 return Actions.ConvertDeclToDeclGroup(TheDecl);
1544 DS.takeAttributesFrom(Attrs);
1545 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1548 /// Returns true if this might be the start of a declarator, or a common typo
1549 /// for a declarator.
1550 bool Parser::MightBeDeclarator(unsigned Context) {
1551 switch (Tok.getKind()) {
1552 case tok::annot_cxxscope:
1553 case tok::annot_template_id:
1555 case tok::code_completion:
1556 case tok::coloncolon:
1558 case tok::kw___attribute:
1559 case tok::kw_operator:
1566 return getLangOpts().CPlusPlus;
1568 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1569 return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
1570 NextToken().is(tok::l_square);
1572 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1573 return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
1575 case tok::identifier:
1576 switch (NextToken().getKind()) {
1577 case tok::code_completion:
1578 case tok::coloncolon:
1581 case tok::equalequal: // Might be a typo for '='.
1582 case tok::kw_alignas:
1584 case tok::kw___attribute:
1596 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1597 // and in block scope it's probably a label. Inside a class definition,
1598 // this is a bit-field.
1599 return Context == Declarator::MemberContext ||
1600 (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
1602 case tok::identifier: // Possible virt-specifier.
1603 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1614 /// Skip until we reach something which seems like a sensible place to pick
1615 /// up parsing after a malformed declaration. This will sometimes stop sooner
1616 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1617 void Parser::SkipMalformedDecl() {
1619 switch (Tok.getKind()) {
1621 // Skip until matching }, then stop. We've probably skipped over
1622 // a malformed class or function definition or similar.
1624 SkipUntil(tok::r_brace);
1625 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1626 // This declaration isn't over yet. Keep skipping.
1629 TryConsumeToken(tok::semi);
1634 SkipUntil(tok::r_square);
1639 SkipUntil(tok::r_paren);
1649 case tok::kw_inline:
1650 // 'inline namespace' at the start of a line is almost certainly
1651 // a good place to pick back up parsing, except in an Objective-C
1652 // @interface context.
1653 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1654 (!ParsingInObjCContainer || CurParsedObjCImpl))
1658 case tok::kw_namespace:
1659 // 'namespace' at the start of a line is almost certainly a good
1660 // place to pick back up parsing, except in an Objective-C
1661 // @interface context.
1662 if (Tok.isAtStartOfLine() &&
1663 (!ParsingInObjCContainer || CurParsedObjCImpl))
1668 // @end is very much like } in Objective-C contexts.
1669 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1670 ParsingInObjCContainer)
1676 // - and + probably start new method declarations in Objective-C contexts.
1677 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1682 case tok::annot_module_begin:
1683 case tok::annot_module_end:
1684 case tok::annot_module_include:
1695 /// ParseDeclGroup - Having concluded that this is either a function
1696 /// definition or a group of object declarations, actually parse the
1698 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1700 SourceLocation *DeclEnd,
1701 ForRangeInit *FRI) {
1702 // Parse the first declarator.
1703 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
1706 // Bail out if the first declarator didn't seem well-formed.
1707 if (!D.hasName() && !D.mayOmitIdentifier()) {
1708 SkipMalformedDecl();
1709 return DeclGroupPtrTy();
1712 // Save late-parsed attributes for now; they need to be parsed in the
1713 // appropriate function scope after the function Decl has been constructed.
1714 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1715 LateParsedAttrList LateParsedAttrs(true);
1716 if (D.isFunctionDeclarator()) {
1717 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1719 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1720 // attribute. If we find the keyword here, tell the user to put it
1721 // at the start instead.
1722 if (Tok.is(tok::kw__Noreturn)) {
1723 SourceLocation Loc = ConsumeToken();
1724 const char *PrevSpec;
1727 // We can offer a fixit if it's valid to mark this function as _Noreturn
1728 // and we don't have any other declarators in this declaration.
1729 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1730 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1731 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1733 Diag(Loc, diag::err_c11_noreturn_misplaced)
1734 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1735 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1740 // Check to see if we have a function *definition* which must have a body.
1741 if (D.isFunctionDeclarator() &&
1742 // Look at the next token to make sure that this isn't a function
1743 // declaration. We have to check this because __attribute__ might be the
1744 // start of a function definition in GCC-extended K&R C.
1745 !isDeclarationAfterDeclarator()) {
1747 // Function definitions are only allowed at file scope and in C++ classes.
1748 // The C++ inline method definition case is handled elsewhere, so we only
1749 // need to handle the file scope definition case.
1750 if (Context == Declarator::FileContext) {
1751 if (isStartOfFunctionDefinition(D)) {
1752 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1753 Diag(Tok, diag::err_function_declared_typedef);
1755 // Recover by treating the 'typedef' as spurious.
1756 DS.ClearStorageClassSpecs();
1760 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1761 return Actions.ConvertDeclToDeclGroup(TheDecl);
1764 if (isDeclarationSpecifier()) {
1765 // If there is an invalid declaration specifier right after the
1766 // function prototype, then we must be in a missing semicolon case
1767 // where this isn't actually a body. Just fall through into the code
1768 // that handles it as a prototype, and let the top-level code handle
1769 // the erroneous declspec where it would otherwise expect a comma or
1772 Diag(Tok, diag::err_expected_fn_body);
1773 SkipUntil(tok::semi);
1774 return DeclGroupPtrTy();
1777 if (Tok.is(tok::l_brace)) {
1778 Diag(Tok, diag::err_function_definition_not_allowed);
1779 SkipMalformedDecl();
1780 return DeclGroupPtrTy();
1785 if (ParseAsmAttributesAfterDeclarator(D))
1786 return DeclGroupPtrTy();
1788 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1789 // must parse and analyze the for-range-initializer before the declaration is
1792 // Handle the Objective-C for-in loop variable similarly, although we
1793 // don't need to parse the container in advance.
1794 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
1795 bool IsForRangeLoop = false;
1796 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
1797 IsForRangeLoop = true;
1798 if (Tok.is(tok::l_brace))
1799 FRI->RangeExpr = ParseBraceInitializer();
1801 FRI->RangeExpr = ParseExpression();
1804 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1806 Actions.ActOnCXXForRangeDecl(ThisDecl);
1807 Actions.FinalizeDeclaration(ThisDecl);
1808 D.complete(ThisDecl);
1809 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
1812 SmallVector<Decl *, 8> DeclsInGroup;
1813 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
1814 D, ParsedTemplateInfo(), FRI);
1815 if (LateParsedAttrs.size() > 0)
1816 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
1817 D.complete(FirstDecl);
1819 DeclsInGroup.push_back(FirstDecl);
1821 bool ExpectSemi = Context != Declarator::ForContext;
1823 // If we don't have a comma, it is either the end of the list (a ';') or an
1825 SourceLocation CommaLoc;
1826 while (TryConsumeToken(tok::comma, CommaLoc)) {
1827 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
1828 // This comma was followed by a line-break and something which can't be
1829 // the start of a declarator. The comma was probably a typo for a
1831 Diag(CommaLoc, diag::err_expected_semi_declaration)
1832 << FixItHint::CreateReplacement(CommaLoc, ";");
1837 // Parse the next declarator.
1839 D.setCommaLoc(CommaLoc);
1841 // Accept attributes in an init-declarator. In the first declarator in a
1842 // declaration, these would be part of the declspec. In subsequent
1843 // declarators, they become part of the declarator itself, so that they
1844 // don't apply to declarators after *this* one. Examples:
1845 // short __attribute__((common)) var; -> declspec
1846 // short var __attribute__((common)); -> declarator
1847 // short x, __attribute__((common)) var; -> declarator
1848 MaybeParseGNUAttributes(D);
1850 // MSVC parses but ignores qualifiers after the comma as an extension.
1851 if (getLangOpts().MicrosoftExt)
1852 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
1855 if (!D.isInvalidType()) {
1856 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
1857 D.complete(ThisDecl);
1859 DeclsInGroup.push_back(ThisDecl);
1864 *DeclEnd = Tok.getLocation();
1867 ExpectAndConsumeSemi(Context == Declarator::FileContext
1868 ? diag::err_invalid_token_after_toplevel_declarator
1869 : diag::err_expected_semi_declaration)) {
1870 // Okay, there was no semicolon and one was expected. If we see a
1871 // declaration specifier, just assume it was missing and continue parsing.
1872 // Otherwise things are very confused and we skip to recover.
1873 if (!isDeclarationSpecifier()) {
1874 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1875 TryConsumeToken(tok::semi);
1879 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1882 /// Parse an optional simple-asm-expr and attributes, and attach them to a
1883 /// declarator. Returns true on an error.
1884 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
1885 // If a simple-asm-expr is present, parse it.
1886 if (Tok.is(tok::kw_asm)) {
1888 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1889 if (AsmLabel.isInvalid()) {
1890 SkipUntil(tok::semi, StopBeforeMatch);
1894 D.setAsmLabel(AsmLabel.get());
1898 MaybeParseGNUAttributes(D);
1902 /// \brief Parse 'declaration' after parsing 'declaration-specifiers
1903 /// declarator'. This method parses the remainder of the declaration
1904 /// (including any attributes or initializer, among other things) and
1905 /// finalizes the declaration.
1907 /// init-declarator: [C99 6.7]
1909 /// declarator '=' initializer
1910 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
1911 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
1912 /// [C++] declarator initializer[opt]
1914 /// [C++] initializer:
1915 /// [C++] '=' initializer-clause
1916 /// [C++] '(' expression-list ')'
1917 /// [C++0x] '=' 'default' [TODO]
1918 /// [C++0x] '=' 'delete'
1919 /// [C++0x] braced-init-list
1921 /// According to the standard grammar, =default and =delete are function
1922 /// definitions, but that definitely doesn't fit with the parser here.
1924 Decl *Parser::ParseDeclarationAfterDeclarator(
1925 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
1926 if (ParseAsmAttributesAfterDeclarator(D))
1929 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
1932 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
1933 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
1934 // Inform the current actions module that we just parsed this declarator.
1935 Decl *ThisDecl = nullptr;
1936 switch (TemplateInfo.Kind) {
1937 case ParsedTemplateInfo::NonTemplate:
1938 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1941 case ParsedTemplateInfo::Template:
1942 case ParsedTemplateInfo::ExplicitSpecialization: {
1943 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
1944 *TemplateInfo.TemplateParams,
1946 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
1947 // Re-direct this decl to refer to the templated decl so that we can
1949 ThisDecl = VT->getTemplatedDecl();
1952 case ParsedTemplateInfo::ExplicitInstantiation: {
1953 if (Tok.is(tok::semi)) {
1954 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
1955 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
1956 if (ThisRes.isInvalid()) {
1957 SkipUntil(tok::semi, StopBeforeMatch);
1960 ThisDecl = ThisRes.get();
1962 // FIXME: This check should be for a variable template instantiation only.
1964 // Check that this is a valid instantiation
1965 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
1966 // If the declarator-id is not a template-id, issue a diagnostic and
1967 // recover by ignoring the 'template' keyword.
1968 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1969 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1970 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
1972 SourceLocation LAngleLoc =
1973 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1974 Diag(D.getIdentifierLoc(),
1975 diag::err_explicit_instantiation_with_definition)
1976 << SourceRange(TemplateInfo.TemplateLoc)
1977 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1979 // Recover as if it were an explicit specialization.
1980 TemplateParameterLists FakedParamLists;
1981 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1982 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1986 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
1993 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1995 // Parse declarator '=' initializer.
1996 // If a '==' or '+=' is found, suggest a fixit to '='.
1997 if (isTokenEqualOrEqualTypo()) {
1998 SourceLocation EqualLoc = ConsumeToken();
2000 if (Tok.is(tok::kw_delete)) {
2001 if (D.isFunctionDeclarator())
2002 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2005 Diag(ConsumeToken(), diag::err_deleted_non_function);
2006 } else if (Tok.is(tok::kw_default)) {
2007 if (D.isFunctionDeclarator())
2008 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2011 Diag(ConsumeToken(), diag::err_default_special_members);
2013 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2015 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2018 if (Tok.is(tok::code_completion)) {
2019 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2020 Actions.FinalizeDeclaration(ThisDecl);
2025 ExprResult Init(ParseInitializer());
2027 // If this is the only decl in (possibly) range based for statement,
2028 // our best guess is that the user meant ':' instead of '='.
2029 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2030 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2031 << FixItHint::CreateReplacement(EqualLoc, ":");
2032 // We are trying to stop parser from looking for ';' in this for
2033 // statement, therefore preventing spurious errors to be issued.
2034 FRI->ColonLoc = EqualLoc;
2036 FRI->RangeExpr = Init;
2039 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2040 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2044 if (Init.isInvalid()) {
2045 SmallVector<tok::TokenKind, 2> StopTokens;
2046 StopTokens.push_back(tok::comma);
2047 if (D.getContext() == Declarator::ForContext)
2048 StopTokens.push_back(tok::r_paren);
2049 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2050 Actions.ActOnInitializerError(ThisDecl);
2052 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2053 /*DirectInit=*/false, TypeContainsAuto);
2055 } else if (Tok.is(tok::l_paren)) {
2056 // Parse C++ direct initializer: '(' expression-list ')'
2057 BalancedDelimiterTracker T(*this, tok::l_paren);
2061 CommaLocsTy CommaLocs;
2063 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2065 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2068 if (ParseExpressionList(Exprs, CommaLocs, [&] {
2069 Actions.CodeCompleteConstructor(getCurScope(),
2070 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
2071 ThisDecl->getLocation(), Exprs);
2073 Actions.ActOnInitializerError(ThisDecl);
2074 SkipUntil(tok::r_paren, StopAtSemi);
2076 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2077 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2084 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2085 "Unexpected number of commas!");
2087 if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
2088 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2092 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2093 T.getCloseLocation(),
2095 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2096 /*DirectInit=*/true, TypeContainsAuto);
2098 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2099 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2100 // Parse C++0x braced-init-list.
2101 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2103 if (D.getCXXScopeSpec().isSet()) {
2105 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
2108 ExprResult Init(ParseBraceInitializer());
2110 if (D.getCXXScopeSpec().isSet()) {
2111 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
2115 if (Init.isInvalid()) {
2116 Actions.ActOnInitializerError(ThisDecl);
2118 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2119 /*DirectInit=*/true, TypeContainsAuto);
2122 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
2125 Actions.FinalizeDeclaration(ThisDecl);
2130 /// ParseSpecifierQualifierList
2131 /// specifier-qualifier-list:
2132 /// type-specifier specifier-qualifier-list[opt]
2133 /// type-qualifier specifier-qualifier-list[opt]
2134 /// [GNU] attributes specifier-qualifier-list[opt]
2136 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2137 DeclSpecContext DSC) {
2138 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2139 /// parse declaration-specifiers and complain about extra stuff.
2140 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2141 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2143 // Validate declspec for type-name.
2144 unsigned Specs = DS.getParsedSpecifiers();
2145 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2146 Diag(Tok, diag::err_expected_type);
2147 DS.SetTypeSpecError();
2148 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2149 Diag(Tok, diag::err_typename_requires_specqual);
2150 if (!DS.hasTypeSpecifier())
2151 DS.SetTypeSpecError();
2154 // Issue diagnostic and remove storage class if present.
2155 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2156 if (DS.getStorageClassSpecLoc().isValid())
2157 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2159 Diag(DS.getThreadStorageClassSpecLoc(),
2160 diag::err_typename_invalid_storageclass);
2161 DS.ClearStorageClassSpecs();
2164 // Issue diagnostic and remove function specfier if present.
2165 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2166 if (DS.isInlineSpecified())
2167 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2168 if (DS.isVirtualSpecified())
2169 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2170 if (DS.isExplicitSpecified())
2171 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2172 DS.ClearFunctionSpecs();
2175 // Issue diagnostic and remove constexpr specfier if present.
2176 if (DS.isConstexprSpecified() && DSC != DSC_condition) {
2177 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2178 DS.ClearConstexprSpec();
2182 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2183 /// specified token is valid after the identifier in a declarator which
2184 /// immediately follows the declspec. For example, these things are valid:
2186 /// int x [ 4]; // direct-declarator
2187 /// int x ( int y); // direct-declarator
2188 /// int(int x ) // direct-declarator
2189 /// int x ; // simple-declaration
2190 /// int x = 17; // init-declarator-list
2191 /// int x , y; // init-declarator-list
2192 /// int x __asm__ ("foo"); // init-declarator-list
2193 /// int x : 4; // struct-declarator
2194 /// int x { 5}; // C++'0x unified initializers
2196 /// This is not, because 'x' does not immediately follow the declspec (though
2197 /// ')' happens to be valid anyway).
2200 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2201 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2202 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2207 /// ParseImplicitInt - This method is called when we have an non-typename
2208 /// identifier in a declspec (which normally terminates the decl spec) when
2209 /// the declspec has no type specifier. In this case, the declspec is either
2210 /// malformed or is "implicit int" (in K&R and C89).
2212 /// This method handles diagnosing this prettily and returns false if the
2213 /// declspec is done being processed. If it recovers and thinks there may be
2214 /// other pieces of declspec after it, it returns true.
2216 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2217 const ParsedTemplateInfo &TemplateInfo,
2218 AccessSpecifier AS, DeclSpecContext DSC,
2219 ParsedAttributesWithRange &Attrs) {
2220 assert(Tok.is(tok::identifier) && "should have identifier");
2222 SourceLocation Loc = Tok.getLocation();
2223 // If we see an identifier that is not a type name, we normally would
2224 // parse it as the identifer being declared. However, when a typename
2225 // is typo'd or the definition is not included, this will incorrectly
2226 // parse the typename as the identifier name and fall over misparsing
2227 // later parts of the diagnostic.
2229 // As such, we try to do some look-ahead in cases where this would
2230 // otherwise be an "implicit-int" case to see if this is invalid. For
2231 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2232 // an identifier with implicit int, we'd get a parse error because the
2233 // next token is obviously invalid for a type. Parse these as a case
2234 // with an invalid type specifier.
2235 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2237 // Since we know that this either implicit int (which is rare) or an
2238 // error, do lookahead to try to do better recovery. This never applies
2239 // within a type specifier. Outside of C++, we allow this even if the
2240 // language doesn't "officially" support implicit int -- we support
2241 // implicit int as an extension in C99 and C11.
2242 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2243 isValidAfterIdentifierInDeclarator(NextToken())) {
2244 // If this token is valid for implicit int, e.g. "static x = 4", then
2245 // we just avoid eating the identifier, so it will be parsed as the
2246 // identifier in the declarator.
2250 if (getLangOpts().CPlusPlus &&
2251 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2252 // Don't require a type specifier if we have the 'auto' storage class
2253 // specifier in C++98 -- we'll promote it to a type specifier.
2255 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2259 // Otherwise, if we don't consume this token, we are going to emit an
2260 // error anyway. Try to recover from various common problems. Check
2261 // to see if this was a reference to a tag name without a tag specified.
2262 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2264 // C++ doesn't need this, and isTagName doesn't take SS.
2265 if (SS == nullptr) {
2266 const char *TagName = nullptr, *FixitTagName = nullptr;
2267 tok::TokenKind TagKind = tok::unknown;
2269 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2271 case DeclSpec::TST_enum:
2272 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2273 case DeclSpec::TST_union:
2274 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2275 case DeclSpec::TST_struct:
2276 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2277 case DeclSpec::TST_interface:
2278 TagName="__interface"; FixitTagName = "__interface ";
2279 TagKind=tok::kw___interface;break;
2280 case DeclSpec::TST_class:
2281 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2285 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2286 LookupResult R(Actions, TokenName, SourceLocation(),
2287 Sema::LookupOrdinaryName);
2289 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2290 << TokenName << TagName << getLangOpts().CPlusPlus
2291 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2293 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2294 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2296 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2297 << TokenName << TagName;
2300 // Parse this as a tag as if the missing tag were present.
2301 if (TagKind == tok::kw_enum)
2302 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
2304 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2305 /*EnteringContext*/ false, DSC_normal, Attrs);
2310 // Determine whether this identifier could plausibly be the name of something
2311 // being declared (with a missing type).
2312 if (!isTypeSpecifier(DSC) &&
2313 (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
2314 // Look ahead to the next token to try to figure out what this declaration
2315 // was supposed to be.
2316 switch (NextToken().getKind()) {
2317 case tok::l_paren: {
2318 // static x(4); // 'x' is not a type
2319 // x(int n); // 'x' is not a type
2320 // x (*p)[]; // 'x' is a type
2322 // Since we're in an error case, we can afford to perform a tentative
2323 // parse to determine which case we're in.
2324 TentativeParsingAction PA(*this);
2326 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2329 if (TPR != TPResult::False) {
2330 // The identifier is followed by a parenthesized declarator.
2331 // It's supposed to be a type.
2335 // If we're in a context where we could be declaring a constructor,
2336 // check whether this is a constructor declaration with a bogus name.
2337 if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
2338 IdentifierInfo *II = Tok.getIdentifierInfo();
2339 if (Actions.isCurrentClassNameTypo(II, SS)) {
2340 Diag(Loc, diag::err_constructor_bad_name)
2341 << Tok.getIdentifierInfo() << II
2342 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2343 Tok.setIdentifierInfo(II);
2354 // This looks like a variable or function declaration. The type is
2355 // probably missing. We're done parsing decl-specifiers.
2357 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2361 // This is probably supposed to be a type. This includes cases like:
2363 // struct S { unsinged : 4; };
2368 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2369 // and attempt to recover.
2371 IdentifierInfo *II = Tok.getIdentifierInfo();
2372 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2373 getLangOpts().CPlusPlus &&
2374 NextToken().is(tok::less));
2376 // The action has suggested that the type T could be used. Set that as
2377 // the type in the declaration specifiers, consume the would-be type
2378 // name token, and we're done.
2379 const char *PrevSpec;
2381 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2382 Actions.getASTContext().getPrintingPolicy());
2383 DS.SetRangeEnd(Tok.getLocation());
2385 // There may be other declaration specifiers after this.
2387 } else if (II != Tok.getIdentifierInfo()) {
2388 // If no type was suggested, the correction is to a keyword
2389 Tok.setKind(II->getTokenID());
2390 // There may be other declaration specifiers after this.
2394 // Otherwise, the action had no suggestion for us. Mark this as an error.
2395 DS.SetTypeSpecError();
2396 DS.SetRangeEnd(Tok.getLocation());
2399 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2400 // avoid rippling error messages on subsequent uses of the same type,
2401 // could be useful if #include was forgotten.
2405 /// \brief Determine the declaration specifier context from the declarator
2408 /// \param Context the declarator context, which is one of the
2409 /// Declarator::TheContext enumerator values.
2410 Parser::DeclSpecContext
2411 Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
2412 if (Context == Declarator::MemberContext)
2414 if (Context == Declarator::FileContext)
2415 return DSC_top_level;
2416 if (Context == Declarator::TemplateTypeArgContext)
2417 return DSC_template_type_arg;
2418 if (Context == Declarator::TrailingReturnContext)
2419 return DSC_trailing;
2420 if (Context == Declarator::AliasDeclContext ||
2421 Context == Declarator::AliasTemplateContext)
2422 return DSC_alias_declaration;
2426 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2428 /// FIXME: Simply returns an alignof() expression if the argument is a
2429 /// type. Ideally, the type should be propagated directly into Sema.
2432 /// [C11] constant-expression
2433 /// [C++0x] type-id ...[opt]
2434 /// [C++0x] assignment-expression ...[opt]
2435 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2436 SourceLocation &EllipsisLoc) {
2438 if (isTypeIdInParens()) {
2439 SourceLocation TypeLoc = Tok.getLocation();
2440 ParsedType Ty = ParseTypeName().get();
2441 SourceRange TypeRange(Start, Tok.getLocation());
2442 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2443 Ty.getAsOpaquePtr(), TypeRange);
2445 ER = ParseConstantExpression();
2447 if (getLangOpts().CPlusPlus11)
2448 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2453 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2454 /// attribute to Attrs.
2456 /// alignment-specifier:
2457 /// [C11] '_Alignas' '(' type-id ')'
2458 /// [C11] '_Alignas' '(' constant-expression ')'
2459 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2460 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2461 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2462 SourceLocation *EndLoc) {
2463 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2464 "Not an alignment-specifier!");
2466 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2467 SourceLocation KWLoc = ConsumeToken();
2469 BalancedDelimiterTracker T(*this, tok::l_paren);
2470 if (T.expectAndConsume())
2473 SourceLocation EllipsisLoc;
2474 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2475 if (ArgExpr.isInvalid()) {
2482 *EndLoc = T.getCloseLocation();
2484 ArgsVector ArgExprs;
2485 ArgExprs.push_back(ArgExpr.get());
2486 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2487 AttributeList::AS_Keyword, EllipsisLoc);
2490 /// Determine whether we're looking at something that might be a declarator
2491 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2492 /// diagnose a missing semicolon after a prior tag definition in the decl
2495 /// \return \c true if an error occurred and this can't be any kind of
2498 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2499 DeclSpecContext DSContext,
2500 LateParsedAttrList *LateAttrs) {
2501 assert(DS.hasTagDefinition() && "shouldn't call this");
2503 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2505 if (getLangOpts().CPlusPlus &&
2506 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2507 tok::annot_template_id) &&
2508 TryAnnotateCXXScopeToken(EnteringContext)) {
2509 SkipMalformedDecl();
2513 bool HasScope = Tok.is(tok::annot_cxxscope);
2514 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2515 Token AfterScope = HasScope ? NextToken() : Tok;
2517 // Determine whether the following tokens could possibly be a
2519 bool MightBeDeclarator = true;
2520 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2521 // A declarator-id can't start with 'typename'.
2522 MightBeDeclarator = false;
2523 } else if (AfterScope.is(tok::annot_template_id)) {
2524 // If we have a type expressed as a template-id, this cannot be a
2525 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2526 TemplateIdAnnotation *Annot =
2527 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2528 if (Annot->Kind == TNK_Type_template)
2529 MightBeDeclarator = false;
2530 } else if (AfterScope.is(tok::identifier)) {
2531 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2533 // These tokens cannot come after the declarator-id in a
2534 // simple-declaration, and are likely to come after a type-specifier.
2535 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2536 tok::annot_cxxscope, tok::coloncolon)) {
2537 // Missing a semicolon.
2538 MightBeDeclarator = false;
2539 } else if (HasScope) {
2540 // If the declarator-id has a scope specifier, it must redeclare a
2541 // previously-declared entity. If that's a type (and this is not a
2542 // typedef), that's an error.
2544 Actions.RestoreNestedNameSpecifierAnnotation(
2545 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2546 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2547 Sema::NameClassification Classification = Actions.ClassifyName(
2548 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2549 /*IsAddressOfOperand*/false);
2550 switch (Classification.getKind()) {
2551 case Sema::NC_Error:
2552 SkipMalformedDecl();
2555 case Sema::NC_Keyword:
2556 case Sema::NC_NestedNameSpecifier:
2557 llvm_unreachable("typo correction and nested name specifiers not "
2561 case Sema::NC_TypeTemplate:
2562 // Not a previously-declared non-type entity.
2563 MightBeDeclarator = false;
2566 case Sema::NC_Unknown:
2567 case Sema::NC_Expression:
2568 case Sema::NC_VarTemplate:
2569 case Sema::NC_FunctionTemplate:
2570 // Might be a redeclaration of a prior entity.
2576 if (MightBeDeclarator)
2579 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2580 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2581 diag::err_expected_after)
2582 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2584 // Try to recover from the typo, by dropping the tag definition and parsing
2585 // the problematic tokens as a type.
2587 // FIXME: Split the DeclSpec into pieces for the standalone
2588 // declaration and pieces for the following declaration, instead
2589 // of assuming that all the other pieces attach to new declaration,
2590 // and call ParsedFreeStandingDeclSpec as appropriate.
2591 DS.ClearTypeSpecType();
2592 ParsedTemplateInfo NotATemplate;
2593 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2597 /// ParseDeclarationSpecifiers
2598 /// declaration-specifiers: [C99 6.7]
2599 /// storage-class-specifier declaration-specifiers[opt]
2600 /// type-specifier declaration-specifiers[opt]
2601 /// [C99] function-specifier declaration-specifiers[opt]
2602 /// [C11] alignment-specifier declaration-specifiers[opt]
2603 /// [GNU] attributes declaration-specifiers[opt]
2604 /// [Clang] '__module_private__' declaration-specifiers[opt]
2605 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2607 /// storage-class-specifier: [C99 6.7.1]
2614 /// [C++11] 'thread_local'
2615 /// [C11] '_Thread_local'
2616 /// [GNU] '__thread'
2617 /// function-specifier: [C99 6.7.4]
2620 /// [C++] 'explicit'
2621 /// [OpenCL] '__kernel'
2622 /// 'friend': [C++ dcl.friend]
2623 /// 'constexpr': [C++0x dcl.constexpr]
2626 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2627 const ParsedTemplateInfo &TemplateInfo,
2629 DeclSpecContext DSContext,
2630 LateParsedAttrList *LateAttrs) {
2631 if (DS.getSourceRange().isInvalid()) {
2632 // Start the range at the current token but make the end of the range
2633 // invalid. This will make the entire range invalid unless we successfully
2635 DS.SetRangeStart(Tok.getLocation());
2636 DS.SetRangeEnd(SourceLocation());
2639 bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
2640 bool AttrsLastTime = false;
2641 ParsedAttributesWithRange attrs(AttrFactory);
2642 // We use Sema's policy to get bool macros right.
2643 const PrintingPolicy &Policy = Actions.getPrintingPolicy();
2645 bool isInvalid = false;
2646 bool isStorageClass = false;
2647 const char *PrevSpec = nullptr;
2648 unsigned DiagID = 0;
2650 SourceLocation Loc = Tok.getLocation();
2652 switch (Tok.getKind()) {
2656 ProhibitAttributes(attrs);
2658 // Reject C++11 attributes that appertain to decl specifiers as
2659 // we don't support any C++11 attributes that appertain to decl
2660 // specifiers. This also conforms to what g++ 4.8 is doing.
2661 ProhibitCXX11Attributes(attrs);
2663 DS.takeAttributesFrom(attrs);
2666 // If this is not a declaration specifier token, we're done reading decl
2667 // specifiers. First verify that DeclSpec's are consistent.
2668 DS.Finish(Diags, PP, Policy);
2672 case tok::kw_alignas:
2673 if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
2674 goto DoneWithDeclSpec;
2676 ProhibitAttributes(attrs);
2677 // FIXME: It would be good to recover by accepting the attributes,
2678 // but attempting to do that now would cause serious
2679 // madness in terms of diagnostics.
2681 attrs.Range = SourceRange();
2683 ParseCXX11Attributes(attrs);
2684 AttrsLastTime = true;
2687 case tok::code_completion: {
2688 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2689 if (DS.hasTypeSpecifier()) {
2690 bool AllowNonIdentifiers
2691 = (getCurScope()->getFlags() & (Scope::ControlScope |
2693 Scope::TemplateParamScope |
2694 Scope::FunctionPrototypeScope |
2695 Scope::AtCatchScope)) == 0;
2696 bool AllowNestedNameSpecifiers
2697 = DSContext == DSC_top_level ||
2698 (DSContext == DSC_class && DS.isFriendSpecified());
2700 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2701 AllowNonIdentifiers,
2702 AllowNestedNameSpecifiers);
2703 return cutOffParsing();
2706 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2707 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2708 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2709 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
2710 : Sema::PCC_Template;
2711 else if (DSContext == DSC_class)
2712 CCC = Sema::PCC_Class;
2713 else if (CurParsedObjCImpl)
2714 CCC = Sema::PCC_ObjCImplementation;
2716 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
2717 return cutOffParsing();
2720 case tok::coloncolon: // ::foo::bar
2721 // C++ scope specifier. Annotate and loop, or bail out on error.
2722 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2723 if (!DS.hasTypeSpecifier())
2724 DS.SetTypeSpecError();
2725 goto DoneWithDeclSpec;
2727 if (Tok.is(tok::coloncolon)) // ::new or ::delete
2728 goto DoneWithDeclSpec;
2731 case tok::annot_cxxscope: {
2732 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
2733 goto DoneWithDeclSpec;
2736 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
2737 Tok.getAnnotationRange(),
2740 // We are looking for a qualified typename.
2741 Token Next = NextToken();
2742 if (Next.is(tok::annot_template_id) &&
2743 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
2744 ->Kind == TNK_Type_template) {
2745 // We have a qualified template-id, e.g., N::A<int>
2747 // C++ [class.qual]p2:
2748 // In a lookup in which the constructor is an acceptable lookup
2749 // result and the nested-name-specifier nominates a class C:
2751 // - if the name specified after the
2752 // nested-name-specifier, when looked up in C, is the
2753 // injected-class-name of C (Clause 9), or
2755 // - if the name specified after the nested-name-specifier
2756 // is the same as the identifier or the
2757 // simple-template-id's template-name in the last
2758 // component of the nested-name-specifier,
2760 // the name is instead considered to name the constructor of
2763 // Thus, if the template-name is actually the constructor
2764 // name, then the code is ill-formed; this interpretation is
2765 // reinforced by the NAD status of core issue 635.
2766 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
2767 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2769 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2770 if (isConstructorDeclarator(/*Unqualified*/false)) {
2771 // The user meant this to be an out-of-line constructor
2772 // definition, but template arguments are not allowed
2773 // there. Just allow this as a constructor; we'll
2774 // complain about it later.
2775 goto DoneWithDeclSpec;
2778 // The user meant this to name a type, but it actually names
2779 // a constructor with some extraneous template
2780 // arguments. Complain, then parse it as a type as the user
2782 Diag(TemplateId->TemplateNameLoc,
2783 diag::err_out_of_line_template_id_names_constructor)
2784 << TemplateId->Name;
2787 DS.getTypeSpecScope() = SS;
2788 ConsumeToken(); // The C++ scope.
2789 assert(Tok.is(tok::annot_template_id) &&
2790 "ParseOptionalCXXScopeSpecifier not working");
2791 AnnotateTemplateIdTokenAsType();
2795 if (Next.is(tok::annot_typename)) {
2796 DS.getTypeSpecScope() = SS;
2797 ConsumeToken(); // The C++ scope.
2798 if (Tok.getAnnotationValue()) {
2799 ParsedType T = getTypeAnnotation(Tok);
2800 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
2801 Tok.getAnnotationEndLoc(),
2802 PrevSpec, DiagID, T, Policy);
2807 DS.SetTypeSpecError();
2808 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2809 ConsumeToken(); // The typename
2812 if (Next.isNot(tok::identifier))
2813 goto DoneWithDeclSpec;
2815 // If we're in a context where the identifier could be a class name,
2816 // check whether this is a constructor declaration.
2817 if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
2818 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
2820 if (isConstructorDeclarator(/*Unqualified*/false))
2821 goto DoneWithDeclSpec;
2823 // As noted in C++ [class.qual]p2 (cited above), when the name
2824 // of the class is qualified in a context where it could name
2825 // a constructor, its a constructor name. However, we've
2826 // looked at the declarator, and the user probably meant this
2827 // to be a type. Complain that it isn't supposed to be treated
2828 // as a type, then proceed to parse it as a type.
2829 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
2830 << Next.getIdentifierInfo();
2833 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
2836 false, false, ParsedType(),
2837 /*IsCtorOrDtorName=*/false,
2838 /*NonTrivialSourceInfo=*/true);
2840 // If the referenced identifier is not a type, then this declspec is
2841 // erroneous: We already checked about that it has no type specifier, and
2842 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
2845 ConsumeToken(); // Eat the scope spec so the identifier is current.
2846 ParsedAttributesWithRange Attrs(AttrFactory);
2847 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
2848 if (!Attrs.empty()) {
2849 AttrsLastTime = true;
2850 attrs.takeAllFrom(Attrs);
2854 goto DoneWithDeclSpec;
2857 DS.getTypeSpecScope() = SS;
2858 ConsumeToken(); // The C++ scope.
2860 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2861 DiagID, TypeRep, Policy);
2865 DS.SetRangeEnd(Tok.getLocation());
2866 ConsumeToken(); // The typename.
2871 case tok::annot_typename: {
2872 // If we've previously seen a tag definition, we were almost surely
2873 // missing a semicolon after it.
2874 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
2875 goto DoneWithDeclSpec;
2877 if (Tok.getAnnotationValue()) {
2878 ParsedType T = getTypeAnnotation(Tok);
2879 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2882 DS.SetTypeSpecError();
2887 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2888 ConsumeToken(); // The typename
2893 case tok::kw___is_signed:
2894 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
2895 // typically treats it as a trait. If we see __is_signed as it appears
2896 // in libstdc++, e.g.,
2898 // static const bool __is_signed;
2900 // then treat __is_signed as an identifier rather than as a keyword.
2901 if (DS.getTypeSpecType() == TST_bool &&
2902 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
2903 DS.getStorageClassSpec() == DeclSpec::SCS_static)
2904 TryKeywordIdentFallback(true);
2906 // We're done with the declaration-specifiers.
2907 goto DoneWithDeclSpec;
2910 case tok::kw___super:
2911 case tok::kw_decltype:
2912 case tok::identifier: {
2913 // This identifier can only be a typedef name if we haven't already seen
2914 // a type-specifier. Without this check we misparse:
2915 // typedef int X; struct Y { short X; }; as 'short int'.
2916 if (DS.hasTypeSpecifier())
2917 goto DoneWithDeclSpec;
2919 // In C++, check to see if this is a scope specifier like foo::bar::, if
2920 // so handle it as such. This is important for ctor parsing.
2921 if (getLangOpts().CPlusPlus) {
2922 if (TryAnnotateCXXScopeToken(EnteringContext)) {
2923 DS.SetTypeSpecError();
2924 goto DoneWithDeclSpec;
2926 if (!Tok.is(tok::identifier))
2930 // Check for need to substitute AltiVec keyword tokens.
2931 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
2934 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
2935 // allow the use of a typedef name as a type specifier.
2936 if (DS.isTypeAltiVecVector())
2937 goto DoneWithDeclSpec;
2939 if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
2940 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
2942 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2943 DiagID, TypeRep, Policy);
2947 DS.SetRangeEnd(Loc);
2952 ParsedType TypeRep =
2953 Actions.getTypeName(*Tok.getIdentifierInfo(),
2954 Tok.getLocation(), getCurScope());
2956 // MSVC: If we weren't able to parse a default template argument, and it's
2957 // just a simple identifier, create a DependentNameType. This will allow
2958 // us to defer the name lookup to template instantiation time, as long we
2959 // forge a NestedNameSpecifier for the current context.
2960 if (!TypeRep && DSContext == DSC_template_type_arg &&
2961 getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) {
2962 TypeRep = Actions.ActOnDelayedDefaultTemplateArg(
2963 *Tok.getIdentifierInfo(), Tok.getLocation());
2966 // If this is not a typedef name, don't parse it as part of the declspec,
2967 // it must be an implicit int or an error.
2969 ParsedAttributesWithRange Attrs(AttrFactory);
2970 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
2971 if (!Attrs.empty()) {
2972 AttrsLastTime = true;
2973 attrs.takeAllFrom(Attrs);
2977 goto DoneWithDeclSpec;
2980 // If we're in a context where the identifier could be a class name,
2981 // check whether this is a constructor declaration.
2982 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
2983 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
2984 isConstructorDeclarator(/*Unqualified*/true))
2985 goto DoneWithDeclSpec;
2987 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
2988 DiagID, TypeRep, Policy);
2992 DS.SetRangeEnd(Tok.getLocation());
2993 ConsumeToken(); // The identifier
2995 // Objective-C supports type arguments and protocol references
2996 // following an Objective-C object or object pointer
2997 // type. Handle either one of them.
2998 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
2999 SourceLocation NewEndLoc;
3000 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3001 Loc, TypeRep, /*consumeLastToken=*/true,
3003 if (NewTypeRep.isUsable()) {
3004 DS.UpdateTypeRep(NewTypeRep.get());
3005 DS.SetRangeEnd(NewEndLoc);
3009 // Need to support trailing type qualifiers (e.g. "id<p> const").
3010 // If a type specifier follows, it will be diagnosed elsewhere.
3015 case tok::annot_template_id: {
3016 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3017 if (TemplateId->Kind != TNK_Type_template) {
3018 // This template-id does not refer to a type name, so we're
3019 // done with the type-specifiers.
3020 goto DoneWithDeclSpec;
3023 // If we're in a context where the template-id could be a
3024 // constructor name or specialization, check whether this is a
3025 // constructor declaration.
3026 if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
3027 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3028 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3029 goto DoneWithDeclSpec;
3031 // Turn the template-id annotation token into a type annotation
3032 // token, then try again to parse it as a type-specifier.
3033 AnnotateTemplateIdTokenAsType();
3037 // GNU attributes support.
3038 case tok::kw___attribute:
3039 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3042 // Microsoft declspec support.
3043 case tok::kw___declspec:
3044 ParseMicrosoftDeclSpecs(DS.getAttributes());
3047 // Microsoft single token adornments.
3048 case tok::kw___forceinline: {
3049 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3050 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3051 SourceLocation AttrNameLoc = Tok.getLocation();
3052 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3053 nullptr, 0, AttributeList::AS_Keyword);
3057 case tok::kw___sptr:
3058 case tok::kw___uptr:
3059 case tok::kw___ptr64:
3060 case tok::kw___ptr32:
3062 case tok::kw___cdecl:
3063 case tok::kw___stdcall:
3064 case tok::kw___fastcall:
3065 case tok::kw___thiscall:
3066 case tok::kw___vectorcall:
3067 case tok::kw___unaligned:
3068 ParseMicrosoftTypeAttributes(DS.getAttributes());
3071 // Borland single token adornments.
3072 case tok::kw___pascal:
3073 ParseBorlandTypeAttributes(DS.getAttributes());
3076 // OpenCL single token adornments.
3077 case tok::kw___kernel:
3078 ParseOpenCLAttributes(DS.getAttributes());
3081 // Nullability type specifiers.
3082 case tok::kw__Nonnull:
3083 case tok::kw__Nullable:
3084 case tok::kw__Null_unspecified:
3085 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3088 // Objective-C 'kindof' types.
3089 case tok::kw___kindof:
3090 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3091 nullptr, 0, AttributeList::AS_Keyword);
3092 (void)ConsumeToken();
3095 // storage-class-specifier
3096 case tok::kw_typedef:
3097 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3098 PrevSpec, DiagID, Policy);
3099 isStorageClass = true;
3101 case tok::kw_extern:
3102 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3103 Diag(Tok, diag::ext_thread_before) << "extern";
3104 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3105 PrevSpec, DiagID, Policy);
3106 isStorageClass = true;
3108 case tok::kw___private_extern__:
3109 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3110 Loc, PrevSpec, DiagID, Policy);
3111 isStorageClass = true;
3113 case tok::kw_static:
3114 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3115 Diag(Tok, diag::ext_thread_before) << "static";
3116 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3117 PrevSpec, DiagID, Policy);
3118 isStorageClass = true;
3121 if (getLangOpts().CPlusPlus11) {
3122 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3123 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3124 PrevSpec, DiagID, Policy);
3126 Diag(Tok, diag::ext_auto_storage_class)
3127 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3129 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3132 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3133 PrevSpec, DiagID, Policy);
3134 isStorageClass = true;
3136 case tok::kw_register:
3137 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3138 PrevSpec, DiagID, Policy);
3139 isStorageClass = true;
3141 case tok::kw_mutable:
3142 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3143 PrevSpec, DiagID, Policy);
3144 isStorageClass = true;
3146 case tok::kw___thread:
3147 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3149 isStorageClass = true;
3151 case tok::kw_thread_local:
3152 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3155 case tok::kw__Thread_local:
3156 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3157 Loc, PrevSpec, DiagID);
3158 isStorageClass = true;
3161 // function-specifier
3162 case tok::kw_inline:
3163 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3165 case tok::kw_virtual:
3166 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3168 case tok::kw_explicit:
3169 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3171 case tok::kw__Noreturn:
3172 if (!getLangOpts().C11)
3173 Diag(Loc, diag::ext_c11_noreturn);
3174 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3177 // alignment-specifier
3178 case tok::kw__Alignas:
3179 if (!getLangOpts().C11)
3180 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3181 ParseAlignmentSpecifier(DS.getAttributes());
3185 case tok::kw_friend:
3186 if (DSContext == DSC_class)
3187 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3189 PrevSpec = ""; // not actually used by the diagnostic
3190 DiagID = diag::err_friend_invalid_in_context;
3196 case tok::kw___module_private__:
3197 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3201 case tok::kw_constexpr:
3202 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3206 case tok::kw_concept:
3207 isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
3212 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3216 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3217 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3220 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3223 case tok::kw___int64:
3224 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3227 case tok::kw_signed:
3228 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3231 case tok::kw_unsigned:
3232 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3235 case tok::kw__Complex:
3236 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3239 case tok::kw__Imaginary:
3240 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3244 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3248 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3252 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3255 case tok::kw___int128:
3256 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3260 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3264 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3267 case tok::kw_double:
3268 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3271 case tok::kw_wchar_t:
3272 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3275 case tok::kw_char16_t:
3276 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3279 case tok::kw_char32_t:
3280 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3285 if (Tok.is(tok::kw_bool) &&
3286 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3287 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3288 PrevSpec = ""; // Not used by the diagnostic.
3289 DiagID = diag::err_bool_redeclaration;
3290 // For better error recovery.
3291 Tok.setKind(tok::identifier);
3294 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3298 case tok::kw__Decimal32:
3299 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3302 case tok::kw__Decimal64:
3303 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3306 case tok::kw__Decimal128:
3307 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3310 case tok::kw___vector:
3311 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3313 case tok::kw___pixel:
3314 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3316 case tok::kw___bool:
3317 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3319 case tok::kw___unknown_anytype:
3320 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3321 PrevSpec, DiagID, Policy);
3326 case tok::kw_struct:
3327 case tok::kw___interface:
3328 case tok::kw_union: {
3329 tok::TokenKind Kind = Tok.getKind();
3332 // These are attributes following class specifiers.
3333 // To produce better diagnostic, we parse them when
3334 // parsing class specifier.
3335 ParsedAttributesWithRange Attributes(AttrFactory);
3336 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3337 EnteringContext, DSContext, Attributes);
3339 // If there are attributes following class specifier,
3340 // take them over and handle them here.
3341 if (!Attributes.empty()) {
3342 AttrsLastTime = true;
3343 attrs.takeAllFrom(Attributes);
3351 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3356 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3359 case tok::kw_volatile:
3360 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3363 case tok::kw_restrict:
3364 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3368 // C++ typename-specifier:
3369 case tok::kw_typename:
3370 if (TryAnnotateTypeOrScopeToken()) {
3371 DS.SetTypeSpecError();
3372 goto DoneWithDeclSpec;
3374 if (!Tok.is(tok::kw_typename))
3378 // GNU typeof support.
3379 case tok::kw_typeof:
3380 ParseTypeofSpecifier(DS);
3383 case tok::annot_decltype:
3384 ParseDecltypeSpecifier(DS);
3387 case tok::kw___underlying_type:
3388 ParseUnderlyingTypeSpecifier(DS);
3391 case tok::kw__Atomic:
3393 // If the _Atomic keyword is immediately followed by a left parenthesis,
3394 // it is interpreted as a type specifier (with a type name), not as a
3396 if (NextToken().is(tok::l_paren)) {
3397 ParseAtomicSpecifier(DS);
3400 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3404 // OpenCL qualifiers:
3405 case tok::kw___generic:
3406 // generic address space is introduced only in OpenCL v2.0
3407 // see OpenCL C Spec v2.0 s6.5.5
3408 if (Actions.getLangOpts().OpenCLVersion < 200) {
3409 DiagID = diag::err_opencl_unknown_type_specifier;
3410 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3414 case tok::kw___private:
3415 case tok::kw___global:
3416 case tok::kw___local:
3417 case tok::kw___constant:
3418 case tok::kw___read_only:
3419 case tok::kw___write_only:
3420 case tok::kw___read_write:
3421 ParseOpenCLQualifiers(DS.getAttributes());
3425 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3426 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3427 // but we support it.
3428 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3429 goto DoneWithDeclSpec;
3431 SourceLocation StartLoc = Tok.getLocation();
3432 SourceLocation EndLoc;
3433 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3434 if (Type.isUsable()) {
3435 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3436 PrevSpec, DiagID, Type.get(),
3437 Actions.getASTContext().getPrintingPolicy()))
3438 Diag(StartLoc, DiagID) << PrevSpec;
3440 DS.SetRangeEnd(EndLoc);
3442 DS.SetTypeSpecError();
3445 // Need to support trailing type qualifiers (e.g. "id<p> const").
3446 // If a type specifier follows, it will be diagnosed elsewhere.
3449 // If the specifier wasn't legal, issue a diagnostic.
3451 assert(PrevSpec && "Method did not return previous specifier!");
3454 if (DiagID == diag::ext_duplicate_declspec)
3456 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3457 else if (DiagID == diag::err_opencl_unknown_type_specifier)
3458 Diag(Tok, DiagID) << PrevSpec << isStorageClass;
3460 Diag(Tok, DiagID) << PrevSpec;
3463 DS.SetRangeEnd(Tok.getLocation());
3464 if (DiagID != diag::err_bool_redeclaration)
3467 AttrsLastTime = false;
3471 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3474 /// struct-declaration:
3475 /// specifier-qualifier-list struct-declarator-list
3476 /// [GNU] __extension__ struct-declaration
3477 /// [GNU] specifier-qualifier-list
3478 /// struct-declarator-list:
3479 /// struct-declarator
3480 /// struct-declarator-list ',' struct-declarator
3481 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3482 /// struct-declarator:
3484 /// [GNU] declarator attributes[opt]
3485 /// declarator[opt] ':' constant-expression
3486 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3488 void Parser::ParseStructDeclaration(
3489 ParsingDeclSpec &DS,
3490 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3492 if (Tok.is(tok::kw___extension__)) {
3493 // __extension__ silences extension warnings in the subexpression.
3494 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3496 return ParseStructDeclaration(DS, FieldsCallback);
3499 // Parse the common specifier-qualifiers-list piece.
3500 ParseSpecifierQualifierList(DS);
3502 // If there are no declarators, this is a free-standing declaration
3503 // specifier. Let the actions module cope with it.
3504 if (Tok.is(tok::semi)) {
3505 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3507 DS.complete(TheDecl);
3511 // Read struct-declarators until we find the semicolon.
3512 bool FirstDeclarator = true;
3513 SourceLocation CommaLoc;
3515 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3516 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3518 // Attributes are only allowed here on successive declarators.
3519 if (!FirstDeclarator)
3520 MaybeParseGNUAttributes(DeclaratorInfo.D);
3522 /// struct-declarator: declarator
3523 /// struct-declarator: declarator[opt] ':' constant-expression
3524 if (Tok.isNot(tok::colon)) {
3525 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3526 ColonProtectionRAIIObject X(*this);
3527 ParseDeclarator(DeclaratorInfo.D);
3529 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3531 if (TryConsumeToken(tok::colon)) {
3532 ExprResult Res(ParseConstantExpression());
3533 if (Res.isInvalid())
3534 SkipUntil(tok::semi, StopBeforeMatch);
3536 DeclaratorInfo.BitfieldSize = Res.get();
3539 // If attributes exist after the declarator, parse them.
3540 MaybeParseGNUAttributes(DeclaratorInfo.D);
3542 // We're done with this declarator; invoke the callback.
3543 FieldsCallback(DeclaratorInfo);
3545 // If we don't have a comma, it is either the end of the list (a ';')
3546 // or an error, bail out.
3547 if (!TryConsumeToken(tok::comma, CommaLoc))
3550 FirstDeclarator = false;
3554 /// ParseStructUnionBody
3555 /// struct-contents:
3556 /// struct-declaration-list
3558 /// [GNU] "struct-declaration-list" without terminatoring ';'
3559 /// struct-declaration-list:
3560 /// struct-declaration
3561 /// struct-declaration-list struct-declaration
3562 /// [OBC] '@' 'defs' '(' class-name ')'
3564 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3565 unsigned TagType, Decl *TagDecl) {
3566 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3567 "parsing struct/union body");
3568 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3570 BalancedDelimiterTracker T(*this, tok::l_brace);
3571 if (T.consumeOpen())
3574 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3575 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3577 SmallVector<Decl *, 32> FieldDecls;
3579 // While we still have something to read, read the declarations in the struct.
3580 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3581 // Each iteration of this loop reads one struct-declaration.
3583 // Check for extraneous top-level semicolon.
3584 if (Tok.is(tok::semi)) {
3585 ConsumeExtraSemi(InsideStruct, TagType);
3589 // Parse _Static_assert declaration.
3590 if (Tok.is(tok::kw__Static_assert)) {
3591 SourceLocation DeclEnd;
3592 ParseStaticAssertDeclaration(DeclEnd);
3596 if (Tok.is(tok::annot_pragma_pack)) {
3601 if (Tok.is(tok::annot_pragma_align)) {
3602 HandlePragmaAlign();
3606 if (Tok.is(tok::annot_pragma_openmp)) {
3607 // Result can be ignored, because it must be always empty.
3608 auto Res = ParseOpenMPDeclarativeDirective();
3610 // Silence possible warnings.
3614 if (!Tok.is(tok::at)) {
3615 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
3616 // Install the declarator into the current TagDecl.
3618 Actions.ActOnField(getCurScope(), TagDecl,
3619 FD.D.getDeclSpec().getSourceRange().getBegin(),
3620 FD.D, FD.BitfieldSize);
3621 FieldDecls.push_back(Field);
3625 // Parse all the comma separated declarators.
3626 ParsingDeclSpec DS(*this);
3627 ParseStructDeclaration(DS, CFieldCallback);
3628 } else { // Handle @defs
3630 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
3631 Diag(Tok, diag::err_unexpected_at);
3632 SkipUntil(tok::semi);
3636 ExpectAndConsume(tok::l_paren);
3637 if (!Tok.is(tok::identifier)) {
3638 Diag(Tok, diag::err_expected) << tok::identifier;
3639 SkipUntil(tok::semi);
3642 SmallVector<Decl *, 16> Fields;
3643 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
3644 Tok.getIdentifierInfo(), Fields);
3645 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
3647 ExpectAndConsume(tok::r_paren);
3650 if (TryConsumeToken(tok::semi))
3653 if (Tok.is(tok::r_brace)) {
3654 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
3658 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
3659 // Skip to end of block or statement to avoid ext-warning on extra ';'.
3660 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
3661 // If we stopped at a ';', eat it.
3662 TryConsumeToken(tok::semi);
3667 ParsedAttributes attrs(AttrFactory);
3668 // If attributes exist after struct contents, parse them.
3669 MaybeParseGNUAttributes(attrs);
3671 Actions.ActOnFields(getCurScope(),
3672 RecordLoc, TagDecl, FieldDecls,
3673 T.getOpenLocation(), T.getCloseLocation(),
3676 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3677 T.getCloseLocation());
3680 /// ParseEnumSpecifier
3681 /// enum-specifier: [C99 6.7.2.2]
3682 /// 'enum' identifier[opt] '{' enumerator-list '}'
3683 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
3684 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
3685 /// '}' attributes[opt]
3686 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
3688 /// 'enum' identifier
3689 /// [GNU] 'enum' attributes[opt] identifier
3691 /// [C++11] enum-head '{' enumerator-list[opt] '}'
3692 /// [C++11] enum-head '{' enumerator-list ',' '}'
3694 /// enum-head: [C++11]
3695 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
3696 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
3697 /// identifier enum-base[opt]
3699 /// enum-key: [C++11]
3704 /// enum-base: [C++11]
3705 /// ':' type-specifier-seq
3707 /// [C++] elaborated-type-specifier:
3708 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
3710 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
3711 const ParsedTemplateInfo &TemplateInfo,
3712 AccessSpecifier AS, DeclSpecContext DSC) {
3713 // Parse the tag portion of this.
3714 if (Tok.is(tok::code_completion)) {
3715 // Code completion for an enum name.
3716 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
3717 return cutOffParsing();
3720 // If attributes exist after tag, parse them.
3721 ParsedAttributesWithRange attrs(AttrFactory);
3722 MaybeParseGNUAttributes(attrs);
3723 MaybeParseCXX11Attributes(attrs);
3724 MaybeParseMicrosoftDeclSpecs(attrs);
3726 SourceLocation ScopedEnumKWLoc;
3727 bool IsScopedUsingClassTag = false;
3729 // In C++11, recognize 'enum class' and 'enum struct'.
3730 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
3731 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
3732 : diag::ext_scoped_enum);
3733 IsScopedUsingClassTag = Tok.is(tok::kw_class);
3734 ScopedEnumKWLoc = ConsumeToken();
3736 // Attributes are not allowed between these keywords. Diagnose,
3737 // but then just treat them like they appeared in the right place.
3738 ProhibitAttributes(attrs);
3740 // They are allowed afterwards, though.
3741 MaybeParseGNUAttributes(attrs);
3742 MaybeParseCXX11Attributes(attrs);
3743 MaybeParseMicrosoftDeclSpecs(attrs);
3746 // C++11 [temp.explicit]p12:
3747 // The usual access controls do not apply to names used to specify
3748 // explicit instantiations.
3749 // We extend this to also cover explicit specializations. Note that
3750 // we don't suppress if this turns out to be an elaborated type
3752 bool shouldDelayDiagsInTag =
3753 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3754 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3755 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
3757 // Enum definitions should not be parsed in a trailing-return-type.
3758 bool AllowDeclaration = DSC != DSC_trailing;
3760 bool AllowFixedUnderlyingType = AllowDeclaration &&
3761 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
3762 getLangOpts().ObjC2);
3764 CXXScopeSpec &SS = DS.getTypeSpecScope();
3765 if (getLangOpts().CPlusPlus) {
3766 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
3767 // if a fixed underlying type is allowed.
3768 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
3771 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(),
3772 /*EnteringContext=*/true))
3775 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
3776 Diag(Tok, diag::err_expected) << tok::identifier;
3777 if (Tok.isNot(tok::l_brace)) {
3778 // Has no name and is not a definition.
3779 // Skip the rest of this declarator, up until the comma or semicolon.
3780 SkipUntil(tok::comma, StopAtSemi);
3788 // Must have either 'enum name' or 'enum {...}'.
3789 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
3790 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
3791 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
3793 // Skip the rest of this declarator, up until the comma or semicolon.
3794 SkipUntil(tok::comma, StopAtSemi);
3798 // If an identifier is present, consume and remember it.
3799 IdentifierInfo *Name = nullptr;
3800 SourceLocation NameLoc;
3801 if (Tok.is(tok::identifier)) {
3802 Name = Tok.getIdentifierInfo();
3803 NameLoc = ConsumeToken();
3806 if (!Name && ScopedEnumKWLoc.isValid()) {
3807 // C++0x 7.2p2: The optional identifier shall not be omitted in the
3808 // declaration of a scoped enumeration.
3809 Diag(Tok, diag::err_scoped_enum_missing_identifier);
3810 ScopedEnumKWLoc = SourceLocation();
3811 IsScopedUsingClassTag = false;
3814 // Okay, end the suppression area. We'll decide whether to emit the
3815 // diagnostics in a second.
3816 if (shouldDelayDiagsInTag)
3817 diagsFromTag.done();
3819 TypeResult BaseType;
3821 // Parse the fixed underlying type.
3822 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
3823 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
3824 bool PossibleBitfield = false;
3825 if (CanBeBitfield) {
3826 // If we're in class scope, this can either be an enum declaration with
3827 // an underlying type, or a declaration of a bitfield member. We try to
3828 // use a simple disambiguation scheme first to catch the common cases
3829 // (integer literal, sizeof); if it's still ambiguous, we then consider
3830 // anything that's a simple-type-specifier followed by '(' as an
3831 // expression. This suffices because function types are not valid
3832 // underlying types anyway.
3833 EnterExpressionEvaluationContext Unevaluated(Actions,
3834 Sema::ConstantEvaluated);
3835 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
3836 // If the next token starts an expression, we know we're parsing a
3837 // bit-field. This is the common case.
3838 if (TPR == TPResult::True)
3839 PossibleBitfield = true;
3840 // If the next token starts a type-specifier-seq, it may be either a
3841 // a fixed underlying type or the start of a function-style cast in C++;
3842 // lookahead one more token to see if it's obvious that we have a
3843 // fixed underlying type.
3844 else if (TPR == TPResult::False &&
3845 GetLookAheadToken(2).getKind() == tok::semi) {
3849 // We have the start of a type-specifier-seq, so we have to perform
3850 // tentative parsing to determine whether we have an expression or a
3852 TentativeParsingAction TPA(*this);
3857 // If we see a type specifier followed by an open-brace, we have an
3858 // ambiguity between an underlying type and a C++11 braced
3859 // function-style cast. Resolve this by always treating it as an
3861 // FIXME: The standard is not entirely clear on how to disambiguate in
3863 if ((getLangOpts().CPlusPlus &&
3864 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
3865 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
3866 // We'll parse this as a bitfield later.
3867 PossibleBitfield = true;
3870 // We have a type-specifier-seq.
3879 if (!PossibleBitfield) {
3881 BaseType = ParseTypeName(&Range);
3883 if (getLangOpts().CPlusPlus11) {
3884 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
3885 } else if (!getLangOpts().ObjC2) {
3886 if (getLangOpts().CPlusPlus)
3887 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
3889 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
3894 // There are four options here. If we have 'friend enum foo;' then this is a
3895 // friend declaration, and cannot have an accompanying definition. If we have
3896 // 'enum foo;', then this is a forward declaration. If we have
3897 // 'enum foo {...' then this is a definition. Otherwise we have something
3898 // like 'enum foo xyz', a reference.
3900 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
3901 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
3902 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
3904 Sema::TagUseKind TUK;
3905 if (!AllowDeclaration) {
3906 TUK = Sema::TUK_Reference;
3907 } else if (Tok.is(tok::l_brace)) {
3908 if (DS.isFriendSpecified()) {
3909 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
3910 << SourceRange(DS.getFriendSpecLoc());
3912 SkipUntil(tok::r_brace, StopAtSemi);
3913 TUK = Sema::TUK_Friend;
3915 TUK = Sema::TUK_Definition;
3917 } else if (!isTypeSpecifier(DSC) &&
3918 (Tok.is(tok::semi) ||
3919 (Tok.isAtStartOfLine() &&
3920 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
3921 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
3922 if (Tok.isNot(tok::semi)) {
3923 // A semicolon was missing after this declaration. Diagnose and recover.
3924 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
3926 Tok.setKind(tok::semi);
3929 TUK = Sema::TUK_Reference;
3932 // If this is an elaborated type specifier, and we delayed
3933 // diagnostics before, just merge them into the current pool.
3934 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
3935 diagsFromTag.redelay();
3938 MultiTemplateParamsArg TParams;
3939 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
3940 TUK != Sema::TUK_Reference) {
3941 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
3942 // Skip the rest of this declarator, up until the comma or semicolon.
3943 Diag(Tok, diag::err_enum_template);
3944 SkipUntil(tok::comma, StopAtSemi);
3948 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
3949 // Enumerations can't be explicitly instantiated.
3950 DS.SetTypeSpecError();
3951 Diag(StartLoc, diag::err_explicit_instantiation_enum);
3955 assert(TemplateInfo.TemplateParams && "no template parameters");
3956 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
3957 TemplateInfo.TemplateParams->size());
3960 if (TUK == Sema::TUK_Reference)
3961 ProhibitAttributes(attrs);
3963 if (!Name && TUK != Sema::TUK_Definition) {
3964 Diag(Tok, diag::err_enumerator_unnamed_no_def);
3966 // Skip the rest of this declarator, up until the comma or semicolon.
3967 SkipUntil(tok::comma, StopAtSemi);
3971 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
3973 Sema::SkipBodyInfo SkipBody;
3974 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
3975 NextToken().is(tok::identifier))
3976 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
3977 NextToken().getIdentifierInfo(),
3978 NextToken().getLocation());
3981 bool IsDependent = false;
3982 const char *PrevSpec = nullptr;
3984 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
3985 StartLoc, SS, Name, NameLoc, attrs.getList(),
3986 AS, DS.getModulePrivateSpecLoc(), TParams,
3987 Owned, IsDependent, ScopedEnumKWLoc,
3988 IsScopedUsingClassTag, BaseType,
3989 DSC == DSC_type_specifier, &SkipBody);
3991 if (SkipBody.ShouldSkip) {
3992 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
3994 BalancedDelimiterTracker T(*this, tok::l_brace);
3998 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
3999 NameLoc.isValid() ? NameLoc : StartLoc,
4000 PrevSpec, DiagID, TagDecl, Owned,
4001 Actions.getASTContext().getPrintingPolicy()))
4002 Diag(StartLoc, DiagID) << PrevSpec;
4007 // This enum has a dependent nested-name-specifier. Handle it as a
4010 DS.SetTypeSpecError();
4011 Diag(Tok, diag::err_expected_type_name_after_typename);
4015 TypeResult Type = Actions.ActOnDependentTag(
4016 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4017 if (Type.isInvalid()) {
4018 DS.SetTypeSpecError();
4022 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4023 NameLoc.isValid() ? NameLoc : StartLoc,
4024 PrevSpec, DiagID, Type.get(),
4025 Actions.getASTContext().getPrintingPolicy()))
4026 Diag(StartLoc, DiagID) << PrevSpec;
4032 // The action failed to produce an enumeration tag. If this is a
4033 // definition, consume the entire definition.
4034 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4036 SkipUntil(tok::r_brace, StopAtSemi);
4039 DS.SetTypeSpecError();
4043 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
4044 ParseEnumBody(StartLoc, TagDecl);
4046 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4047 NameLoc.isValid() ? NameLoc : StartLoc,
4048 PrevSpec, DiagID, TagDecl, Owned,
4049 Actions.getASTContext().getPrintingPolicy()))
4050 Diag(StartLoc, DiagID) << PrevSpec;
4053 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4054 /// enumerator-list:
4056 /// enumerator-list ',' enumerator
4058 /// enumeration-constant attributes[opt]
4059 /// enumeration-constant attributes[opt] '=' constant-expression
4060 /// enumeration-constant:
4063 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4064 // Enter the scope of the enum body and start the definition.
4065 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4066 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4068 BalancedDelimiterTracker T(*this, tok::l_brace);
4071 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4072 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4073 Diag(Tok, diag::error_empty_enum);
4075 SmallVector<Decl *, 32> EnumConstantDecls;
4076 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4078 Decl *LastEnumConstDecl = nullptr;
4080 // Parse the enumerator-list.
4081 while (Tok.isNot(tok::r_brace)) {
4082 // Parse enumerator. If failed, try skipping till the start of the next
4083 // enumerator definition.
4084 if (Tok.isNot(tok::identifier)) {
4085 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4086 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4087 TryConsumeToken(tok::comma))
4091 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4092 SourceLocation IdentLoc = ConsumeToken();
4094 // If attributes exist after the enumerator, parse them.
4095 ParsedAttributesWithRange attrs(AttrFactory);
4096 MaybeParseGNUAttributes(attrs);
4097 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4098 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
4099 if (!getLangOpts().CPlusPlus1z)
4100 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
4101 << 1 /*enumerator*/;
4102 ParseCXX11Attributes(attrs);
4105 SourceLocation EqualLoc;
4106 ExprResult AssignedVal;
4107 EnumAvailabilityDiags.emplace_back(*this);
4109 if (TryConsumeToken(tok::equal, EqualLoc)) {
4110 AssignedVal = ParseConstantExpression();
4111 if (AssignedVal.isInvalid())
4112 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4115 // Install the enumerator constant into EnumDecl.
4116 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
4119 attrs.getList(), EqualLoc,
4121 EnumAvailabilityDiags.back().done();
4123 EnumConstantDecls.push_back(EnumConstDecl);
4124 LastEnumConstDecl = EnumConstDecl;
4126 if (Tok.is(tok::identifier)) {
4127 // We're missing a comma between enumerators.
4128 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
4129 Diag(Loc, diag::err_enumerator_list_missing_comma)
4130 << FixItHint::CreateInsertion(Loc, ", ");
4134 // Emumerator definition must be finished, only comma or r_brace are
4136 SourceLocation CommaLoc;
4137 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4138 if (EqualLoc.isValid())
4139 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4142 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4143 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4144 if (TryConsumeToken(tok::comma, CommaLoc))
4151 // If comma is followed by r_brace, emit appropriate warning.
4152 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4153 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4154 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4155 diag::ext_enumerator_list_comma_cxx :
4156 diag::ext_enumerator_list_comma_c)
4157 << FixItHint::CreateRemoval(CommaLoc);
4158 else if (getLangOpts().CPlusPlus11)
4159 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4160 << FixItHint::CreateRemoval(CommaLoc);
4168 // If attributes exist after the identifier list, parse them.
4169 ParsedAttributes attrs(AttrFactory);
4170 MaybeParseGNUAttributes(attrs);
4172 Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
4173 EnumDecl, EnumConstantDecls,
4177 // Now handle enum constant availability diagnostics.
4178 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4179 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4180 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4181 EnumAvailabilityDiags[i].redelay();
4182 PD.complete(EnumConstantDecls[i]);
4186 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
4187 T.getCloseLocation());
4189 // The next token must be valid after an enum definition. If not, a ';'
4190 // was probably forgotten.
4191 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4192 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4193 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4194 // Push this token back into the preprocessor and change our current token
4195 // to ';' so that the rest of the code recovers as though there were an
4196 // ';' after the definition.
4198 Tok.setKind(tok::semi);
4202 /// isTypeSpecifierQualifier - Return true if the current token could be the
4203 /// start of a type-qualifier-list.
4204 bool Parser::isTypeQualifier() const {
4205 switch (Tok.getKind()) {
4206 default: return false;
4209 case tok::kw_volatile:
4210 case tok::kw_restrict:
4211 case tok::kw___private:
4212 case tok::kw___local:
4213 case tok::kw___global:
4214 case tok::kw___constant:
4215 case tok::kw___generic:
4216 case tok::kw___read_only:
4217 case tok::kw___read_write:
4218 case tok::kw___write_only:
4223 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4224 /// is definitely a type-specifier. Return false if it isn't part of a type
4225 /// specifier or if we're not sure.
4226 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4227 switch (Tok.getKind()) {
4228 default: return false;
4232 case tok::kw___int64:
4233 case tok::kw___int128:
4234 case tok::kw_signed:
4235 case tok::kw_unsigned:
4236 case tok::kw__Complex:
4237 case tok::kw__Imaginary:
4240 case tok::kw_wchar_t:
4241 case tok::kw_char16_t:
4242 case tok::kw_char32_t:
4246 case tok::kw_double:
4249 case tok::kw__Decimal32:
4250 case tok::kw__Decimal64:
4251 case tok::kw__Decimal128:
4252 case tok::kw___vector:
4254 // struct-or-union-specifier (C99) or class-specifier (C++)
4256 case tok::kw_struct:
4257 case tok::kw___interface:
4263 case tok::annot_typename:
4268 /// isTypeSpecifierQualifier - Return true if the current token could be the
4269 /// start of a specifier-qualifier-list.
4270 bool Parser::isTypeSpecifierQualifier() {
4271 switch (Tok.getKind()) {
4272 default: return false;
4274 case tok::identifier: // foo::bar
4275 if (TryAltiVecVectorToken())
4278 case tok::kw_typename: // typename T::type
4279 // Annotate typenames and C++ scope specifiers. If we get one, just
4280 // recurse to handle whatever we get.
4281 if (TryAnnotateTypeOrScopeToken())
4283 if (Tok.is(tok::identifier))
4285 return isTypeSpecifierQualifier();
4287 case tok::coloncolon: // ::foo::bar
4288 if (NextToken().is(tok::kw_new) || // ::new
4289 NextToken().is(tok::kw_delete)) // ::delete
4292 if (TryAnnotateTypeOrScopeToken())
4294 return isTypeSpecifierQualifier();
4296 // GNU attributes support.
4297 case tok::kw___attribute:
4298 // GNU typeof support.
4299 case tok::kw_typeof:
4304 case tok::kw___int64:
4305 case tok::kw___int128:
4306 case tok::kw_signed:
4307 case tok::kw_unsigned:
4308 case tok::kw__Complex:
4309 case tok::kw__Imaginary:
4312 case tok::kw_wchar_t:
4313 case tok::kw_char16_t:
4314 case tok::kw_char32_t:
4318 case tok::kw_double:
4321 case tok::kw__Decimal32:
4322 case tok::kw__Decimal64:
4323 case tok::kw__Decimal128:
4324 case tok::kw___vector:
4326 // struct-or-union-specifier (C99) or class-specifier (C++)
4328 case tok::kw_struct:
4329 case tok::kw___interface:
4336 case tok::kw_volatile:
4337 case tok::kw_restrict:
4339 // Debugger support.
4340 case tok::kw___unknown_anytype:
4343 case tok::annot_typename:
4346 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4348 return getLangOpts().ObjC1;
4350 case tok::kw___cdecl:
4351 case tok::kw___stdcall:
4352 case tok::kw___fastcall:
4353 case tok::kw___thiscall:
4354 case tok::kw___vectorcall:
4356 case tok::kw___ptr64:
4357 case tok::kw___ptr32:
4358 case tok::kw___pascal:
4359 case tok::kw___unaligned:
4361 case tok::kw__Nonnull:
4362 case tok::kw__Nullable:
4363 case tok::kw__Null_unspecified:
4365 case tok::kw___kindof:
4367 case tok::kw___private:
4368 case tok::kw___local:
4369 case tok::kw___global:
4370 case tok::kw___constant:
4371 case tok::kw___generic:
4372 case tok::kw___read_only:
4373 case tok::kw___read_write:
4374 case tok::kw___write_only:
4379 case tok::kw__Atomic:
4384 /// isDeclarationSpecifier() - Return true if the current token is part of a
4385 /// declaration specifier.
4387 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4388 /// this check is to disambiguate between an expression and a declaration.
4389 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4390 switch (Tok.getKind()) {
4391 default: return false;
4393 case tok::identifier: // foo::bar
4394 // Unfortunate hack to support "Class.factoryMethod" notation.
4395 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4397 if (TryAltiVecVectorToken())
4400 case tok::kw_decltype: // decltype(T())::type
4401 case tok::kw_typename: // typename T::type
4402 // Annotate typenames and C++ scope specifiers. If we get one, just
4403 // recurse to handle whatever we get.
4404 if (TryAnnotateTypeOrScopeToken())
4406 if (Tok.is(tok::identifier))
4409 // If we're in Objective-C and we have an Objective-C class type followed
4410 // by an identifier and then either ':' or ']', in a place where an
4411 // expression is permitted, then this is probably a class message send
4412 // missing the initial '['. In this case, we won't consider this to be
4413 // the start of a declaration.
4414 if (DisambiguatingWithExpression &&
4415 isStartOfObjCClassMessageMissingOpenBracket())
4418 return isDeclarationSpecifier();
4420 case tok::coloncolon: // ::foo::bar
4421 if (NextToken().is(tok::kw_new) || // ::new
4422 NextToken().is(tok::kw_delete)) // ::delete
4425 // Annotate typenames and C++ scope specifiers. If we get one, just
4426 // recurse to handle whatever we get.
4427 if (TryAnnotateTypeOrScopeToken())
4429 return isDeclarationSpecifier();
4431 // storage-class-specifier
4432 case tok::kw_typedef:
4433 case tok::kw_extern:
4434 case tok::kw___private_extern__:
4435 case tok::kw_static:
4437 case tok::kw_register:
4438 case tok::kw___thread:
4439 case tok::kw_thread_local:
4440 case tok::kw__Thread_local:
4443 case tok::kw___module_private__:
4446 case tok::kw___unknown_anytype:
4451 case tok::kw___int64:
4452 case tok::kw___int128:
4453 case tok::kw_signed:
4454 case tok::kw_unsigned:
4455 case tok::kw__Complex:
4456 case tok::kw__Imaginary:
4459 case tok::kw_wchar_t:
4460 case tok::kw_char16_t:
4461 case tok::kw_char32_t:
4466 case tok::kw_double:
4469 case tok::kw__Decimal32:
4470 case tok::kw__Decimal64:
4471 case tok::kw__Decimal128:
4472 case tok::kw___vector:
4474 // struct-or-union-specifier (C99) or class-specifier (C++)
4476 case tok::kw_struct:
4478 case tok::kw___interface:
4484 case tok::kw_volatile:
4485 case tok::kw_restrict:
4487 // function-specifier
4488 case tok::kw_inline:
4489 case tok::kw_virtual:
4490 case tok::kw_explicit:
4491 case tok::kw__Noreturn:
4493 // alignment-specifier
4494 case tok::kw__Alignas:
4497 case tok::kw_friend:
4499 // static_assert-declaration
4500 case tok::kw__Static_assert:
4502 // GNU typeof support.
4503 case tok::kw_typeof:
4506 case tok::kw___attribute:
4508 // C++11 decltype and constexpr.
4509 case tok::annot_decltype:
4510 case tok::kw_constexpr:
4512 // C++ Concepts TS - concept
4513 case tok::kw_concept:
4516 case tok::kw__Atomic:
4519 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4521 return getLangOpts().ObjC1;
4524 case tok::annot_typename:
4525 return !DisambiguatingWithExpression ||
4526 !isStartOfObjCClassMessageMissingOpenBracket();
4528 case tok::kw___declspec:
4529 case tok::kw___cdecl:
4530 case tok::kw___stdcall:
4531 case tok::kw___fastcall:
4532 case tok::kw___thiscall:
4533 case tok::kw___vectorcall:
4535 case tok::kw___sptr:
4536 case tok::kw___uptr:
4537 case tok::kw___ptr64:
4538 case tok::kw___ptr32:
4539 case tok::kw___forceinline:
4540 case tok::kw___pascal:
4541 case tok::kw___unaligned:
4543 case tok::kw__Nonnull:
4544 case tok::kw__Nullable:
4545 case tok::kw__Null_unspecified:
4547 case tok::kw___kindof:
4549 case tok::kw___private:
4550 case tok::kw___local:
4551 case tok::kw___global:
4552 case tok::kw___constant:
4553 case tok::kw___generic:
4554 case tok::kw___read_only:
4555 case tok::kw___read_write:
4556 case tok::kw___write_only:
4562 bool Parser::isConstructorDeclarator(bool IsUnqualified) {
4563 TentativeParsingAction TPA(*this);
4565 // Parse the C++ scope specifier.
4567 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
4568 /*EnteringContext=*/true)) {
4573 // Parse the constructor name.
4574 if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) {
4575 // We already know that we have a constructor name; just consume
4583 // Current class name must be followed by a left parenthesis.
4584 if (Tok.isNot(tok::l_paren)) {
4590 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4591 // that we have a constructor.
4592 if (Tok.is(tok::r_paren) ||
4593 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
4598 // A C++11 attribute here signals that we have a constructor, and is an
4599 // attribute on the first constructor parameter.
4600 if (getLangOpts().CPlusPlus11 &&
4601 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
4602 /*OuterMightBeMessageSend*/ true)) {
4607 // If we need to, enter the specified scope.
4608 DeclaratorScopeObj DeclScopeObj(*this, SS);
4609 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
4610 DeclScopeObj.EnterDeclaratorScope();
4612 // Optionally skip Microsoft attributes.
4613 ParsedAttributes Attrs(AttrFactory);
4614 MaybeParseMicrosoftAttributes(Attrs);
4616 // Check whether the next token(s) are part of a declaration
4617 // specifier, in which case we have the start of a parameter and,
4618 // therefore, we know that this is a constructor.
4619 bool IsConstructor = false;
4620 if (isDeclarationSpecifier())
4621 IsConstructor = true;
4622 else if (Tok.is(tok::identifier) ||
4623 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
4624 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
4625 // This might be a parenthesized member name, but is more likely to
4626 // be a constructor declaration with an invalid argument type. Keep
4628 if (Tok.is(tok::annot_cxxscope))
4632 // If this is not a constructor, we must be parsing a declarator,
4633 // which must have one of the following syntactic forms (see the
4634 // grammar extract at the start of ParseDirectDeclarator):
4635 switch (Tok.getKind()) {
4640 // C(X [ [attribute]]);
4641 case tok::coloncolon:
4644 // Assume this isn't a constructor, rather than assuming it's a
4645 // constructor with an unnamed parameter of an ill-formed type.
4650 if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) {
4651 // Assume these were meant to be constructors:
4652 // C(X) : (the name of a bit-field cannot be parenthesized).
4653 // C(X) try (this is otherwise ill-formed).
4654 IsConstructor = true;
4656 if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) {
4657 // If we have a constructor name within the class definition,
4658 // assume these were meant to be constructors:
4661 // ... because otherwise we would be declaring a non-static data
4662 // member that is ill-formed because it's of the same type as its
4663 // surrounding class.
4665 // FIXME: We can actually do this whether or not the name is qualified,
4666 // because if it is qualified in this context it must be being used as
4667 // a constructor name. However, we do not implement that rule correctly
4668 // currently, so we're somewhat conservative here.
4669 IsConstructor = IsUnqualified;
4674 IsConstructor = true;
4680 return IsConstructor;
4683 /// ParseTypeQualifierListOpt
4684 /// type-qualifier-list: [C99 6.7.5]
4686 /// [vendor] attributes
4687 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4688 /// type-qualifier-list type-qualifier
4689 /// [vendor] type-qualifier-list attributes
4690 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
4691 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
4692 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
4693 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
4694 /// AttrRequirements bitmask values.
4695 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs,
4697 bool IdentifierRequired) {
4698 if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
4699 isCXX11AttributeSpecifier()) {
4700 ParsedAttributesWithRange attrs(AttrFactory);
4701 ParseCXX11Attributes(attrs);
4702 DS.takeAttributesFrom(attrs);
4705 SourceLocation EndLoc;
4708 bool isInvalid = false;
4709 const char *PrevSpec = nullptr;
4710 unsigned DiagID = 0;
4711 SourceLocation Loc = Tok.getLocation();
4713 switch (Tok.getKind()) {
4714 case tok::code_completion:
4715 Actions.CodeCompleteTypeQualifiers(DS);
4716 return cutOffParsing();
4719 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
4722 case tok::kw_volatile:
4723 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4726 case tok::kw_restrict:
4727 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4730 case tok::kw__Atomic:
4732 goto DoneWithTypeQuals;
4733 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4737 // OpenCL qualifiers:
4738 case tok::kw___private:
4739 case tok::kw___global:
4740 case tok::kw___local:
4741 case tok::kw___constant:
4742 case tok::kw___generic:
4743 case tok::kw___read_only:
4744 case tok::kw___write_only:
4745 case tok::kw___read_write:
4746 ParseOpenCLQualifiers(DS.getAttributes());
4749 case tok::kw___uptr:
4750 // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
4751 // with the MS modifier keyword.
4752 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
4753 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
4754 if (TryKeywordIdentFallback(false))
4757 case tok::kw___sptr:
4759 case tok::kw___ptr64:
4760 case tok::kw___ptr32:
4761 case tok::kw___cdecl:
4762 case tok::kw___stdcall:
4763 case tok::kw___fastcall:
4764 case tok::kw___thiscall:
4765 case tok::kw___vectorcall:
4766 case tok::kw___unaligned:
4767 if (AttrReqs & AR_DeclspecAttributesParsed) {
4768 ParseMicrosoftTypeAttributes(DS.getAttributes());
4771 goto DoneWithTypeQuals;
4772 case tok::kw___pascal:
4773 if (AttrReqs & AR_VendorAttributesParsed) {
4774 ParseBorlandTypeAttributes(DS.getAttributes());
4777 goto DoneWithTypeQuals;
4779 // Nullability type specifiers.
4780 case tok::kw__Nonnull:
4781 case tok::kw__Nullable:
4782 case tok::kw__Null_unspecified:
4783 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4786 // Objective-C 'kindof' types.
4787 case tok::kw___kindof:
4788 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4789 nullptr, 0, AttributeList::AS_Keyword);
4790 (void)ConsumeToken();
4793 case tok::kw___attribute:
4794 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
4795 // When GNU attributes are expressly forbidden, diagnose their usage.
4796 Diag(Tok, diag::err_attributes_not_allowed);
4798 // Parse the attributes even if they are rejected to ensure that error
4799 // recovery is graceful.
4800 if (AttrReqs & AR_GNUAttributesParsed ||
4801 AttrReqs & AR_GNUAttributesParsedAndRejected) {
4802 ParseGNUAttributes(DS.getAttributes());
4803 continue; // do *not* consume the next token!
4805 // otherwise, FALL THROUGH!
4808 // If this is not a type-qualifier token, we're done reading type
4809 // qualifiers. First verify that DeclSpec's are consistent.
4810 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
4811 if (EndLoc.isValid())
4812 DS.SetRangeEnd(EndLoc);
4816 // If the specifier combination wasn't legal, issue a diagnostic.
4818 assert(PrevSpec && "Method did not return previous specifier!");
4819 Diag(Tok, DiagID) << PrevSpec;
4821 EndLoc = ConsumeToken();
4826 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
4828 void Parser::ParseDeclarator(Declarator &D) {
4829 /// This implements the 'declarator' production in the C grammar, then checks
4830 /// for well-formedness and issues diagnostics.
4831 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
4834 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
4835 unsigned TheContext) {
4836 if (Kind == tok::star || Kind == tok::caret)
4839 if (!Lang.CPlusPlus)
4842 if (Kind == tok::amp)
4845 // We parse rvalue refs in C++03, because otherwise the errors are scary.
4846 // But we must not parse them in conversion-type-ids and new-type-ids, since
4847 // those can be legitimately followed by a && operator.
4848 // (The same thing can in theory happen after a trailing-return-type, but
4849 // since those are a C++11 feature, there is no rejects-valid issue there.)
4850 if (Kind == tok::ampamp)
4851 return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
4852 TheContext != Declarator::CXXNewContext);
4857 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
4858 /// is parsed by the function passed to it. Pass null, and the direct-declarator
4859 /// isn't parsed at all, making this function effectively parse the C++
4860 /// ptr-operator production.
4862 /// If the grammar of this construct is extended, matching changes must also be
4863 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
4864 /// isConstructorDeclarator.
4866 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
4867 /// [C] pointer[opt] direct-declarator
4868 /// [C++] direct-declarator
4869 /// [C++] ptr-operator declarator
4871 /// pointer: [C99 6.7.5]
4872 /// '*' type-qualifier-list[opt]
4873 /// '*' type-qualifier-list[opt] pointer
4876 /// '*' cv-qualifier-seq[opt]
4879 /// [GNU] '&' restrict[opt] attributes[opt]
4880 /// [GNU?] '&&' restrict[opt] attributes[opt]
4881 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
4882 void Parser::ParseDeclaratorInternal(Declarator &D,
4883 DirectDeclParseFunction DirectDeclParser) {
4884 if (Diags.hasAllExtensionsSilenced())
4887 // C++ member pointers start with a '::' or a nested-name.
4888 // Member pointers get special handling, since there's no place for the
4889 // scope spec in the generic path below.
4890 if (getLangOpts().CPlusPlus &&
4891 (Tok.is(tok::coloncolon) ||
4892 (Tok.is(tok::identifier) &&
4893 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
4894 Tok.is(tok::annot_cxxscope))) {
4895 bool EnteringContext = D.getContext() == Declarator::FileContext ||
4896 D.getContext() == Declarator::MemberContext;
4898 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
4900 if (SS.isNotEmpty()) {
4901 if (Tok.isNot(tok::star)) {
4902 // The scope spec really belongs to the direct-declarator.
4903 if (D.mayHaveIdentifier())
4904 D.getCXXScopeSpec() = SS;
4906 AnnotateScopeToken(SS, true);
4908 if (DirectDeclParser)
4909 (this->*DirectDeclParser)(D);
4913 SourceLocation Loc = ConsumeToken();
4915 DeclSpec DS(AttrFactory);
4916 ParseTypeQualifierListOpt(DS);
4917 D.ExtendWithDeclSpec(DS);
4919 // Recurse to parse whatever is left.
4920 ParseDeclaratorInternal(D, DirectDeclParser);
4922 // Sema will have to catch (syntactically invalid) pointers into global
4923 // scope. It has to catch pointers into namespace scope anyway.
4924 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
4927 /* Don't replace range end. */SourceLocation());
4932 tok::TokenKind Kind = Tok.getKind();
4933 // Not a pointer, C++ reference, or block.
4934 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
4935 if (DirectDeclParser)
4936 (this->*DirectDeclParser)(D);
4940 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
4941 // '&&' -> rvalue reference
4942 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
4945 if (Kind == tok::star || Kind == tok::caret) {
4947 DeclSpec DS(AttrFactory);
4949 // GNU attributes are not allowed here in a new-type-id, but Declspec and
4950 // C++11 attributes are allowed.
4951 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
4952 ((D.getContext() != Declarator::CXXNewContext)
4953 ? AR_GNUAttributesParsed
4954 : AR_GNUAttributesParsedAndRejected);
4955 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
4956 D.ExtendWithDeclSpec(DS);
4958 // Recursively parse the declarator.
4959 ParseDeclaratorInternal(D, DirectDeclParser);
4960 if (Kind == tok::star)
4961 // Remember that we parsed a pointer type, and remember the type-quals.
4962 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
4963 DS.getConstSpecLoc(),
4964 DS.getVolatileSpecLoc(),
4965 DS.getRestrictSpecLoc(),
4966 DS.getAtomicSpecLoc()),
4970 // Remember that we parsed a Block type, and remember the type-quals.
4971 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
4977 DeclSpec DS(AttrFactory);
4979 // Complain about rvalue references in C++03, but then go on and build
4981 if (Kind == tok::ampamp)
4982 Diag(Loc, getLangOpts().CPlusPlus11 ?
4983 diag::warn_cxx98_compat_rvalue_reference :
4984 diag::ext_rvalue_reference);
4986 // GNU-style and C++11 attributes are allowed here, as is restrict.
4987 ParseTypeQualifierListOpt(DS);
4988 D.ExtendWithDeclSpec(DS);
4990 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
4991 // cv-qualifiers are introduced through the use of a typedef or of a
4992 // template type argument, in which case the cv-qualifiers are ignored.
4993 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
4994 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4995 Diag(DS.getConstSpecLoc(),
4996 diag::err_invalid_reference_qualifier_application) << "const";
4997 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4998 Diag(DS.getVolatileSpecLoc(),
4999 diag::err_invalid_reference_qualifier_application) << "volatile";
5000 // 'restrict' is permitted as an extension.
5001 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5002 Diag(DS.getAtomicSpecLoc(),
5003 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5006 // Recursively parse the declarator.
5007 ParseDeclaratorInternal(D, DirectDeclParser);
5009 if (D.getNumTypeObjects() > 0) {
5010 // C++ [dcl.ref]p4: There shall be no references to references.
5011 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5012 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5013 if (const IdentifierInfo *II = D.getIdentifier())
5014 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5017 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5020 // Once we've complained about the reference-to-reference, we
5021 // can go ahead and build the (technically ill-formed)
5022 // declarator: reference collapsing will take care of it.
5026 // Remember that we parsed a reference type.
5027 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5034 // When correcting from misplaced brackets before the identifier, the location
5035 // is saved inside the declarator so that other diagnostic messages can use
5036 // them. This extracts and returns that location, or returns the provided
5037 // location if a stored location does not exist.
5038 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5039 SourceLocation Loc) {
5040 if (D.getName().StartLocation.isInvalid() &&
5041 D.getName().EndLocation.isValid())
5042 return D.getName().EndLocation;
5047 /// ParseDirectDeclarator
5048 /// direct-declarator: [C99 6.7.5]
5049 /// [C99] identifier
5050 /// '(' declarator ')'
5051 /// [GNU] '(' attributes declarator ')'
5052 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5053 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5054 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5055 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5056 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5057 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5058 /// attribute-specifier-seq[opt]
5059 /// direct-declarator '(' parameter-type-list ')'
5060 /// direct-declarator '(' identifier-list[opt] ')'
5061 /// [GNU] direct-declarator '(' parameter-forward-declarations
5062 /// parameter-type-list[opt] ')'
5063 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5064 /// cv-qualifier-seq[opt] exception-specification[opt]
5065 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5066 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5067 /// ref-qualifier[opt] exception-specification[opt]
5068 /// [C++] declarator-id
5069 /// [C++11] declarator-id attribute-specifier-seq[opt]
5071 /// declarator-id: [C++ 8]
5072 /// '...'[opt] id-expression
5073 /// '::'[opt] nested-name-specifier[opt] type-name
5075 /// id-expression: [C++ 5.1]
5079 /// unqualified-id: [C++ 5.1]
5081 /// operator-function-id
5082 /// conversion-function-id
5086 /// Note, any additional constructs added here may need corresponding changes
5087 /// in isConstructorDeclarator.
5088 void Parser::ParseDirectDeclarator(Declarator &D) {
5089 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5091 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5092 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5093 // this context it is a bitfield. Also in range-based for statement colon
5094 // may delimit for-range-declaration.
5095 ColonProtectionRAIIObject X(*this,
5096 D.getContext() == Declarator::MemberContext ||
5097 (D.getContext() == Declarator::ForContext &&
5098 getLangOpts().CPlusPlus11));
5100 // ParseDeclaratorInternal might already have parsed the scope.
5101 if (D.getCXXScopeSpec().isEmpty()) {
5102 bool EnteringContext = D.getContext() == Declarator::FileContext ||
5103 D.getContext() == Declarator::MemberContext;
5104 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
5108 if (D.getCXXScopeSpec().isValid()) {
5109 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5110 D.getCXXScopeSpec()))
5111 // Change the declaration context for name lookup, until this function
5112 // is exited (and the declarator has been parsed).
5113 DeclScopeObj.EnterDeclaratorScope();
5116 // C++0x [dcl.fct]p14:
5117 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5118 // parameter-declaration-clause without a preceding comma. In this case,
5119 // the ellipsis is parsed as part of the abstract-declarator if the type
5120 // of the parameter either names a template parameter pack that has not
5121 // been expanded or contains auto; otherwise, it is parsed as part of the
5122 // parameter-declaration-clause.
5123 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5124 !((D.getContext() == Declarator::PrototypeContext ||
5125 D.getContext() == Declarator::LambdaExprParameterContext ||
5126 D.getContext() == Declarator::BlockLiteralContext) &&
5127 NextToken().is(tok::r_paren) &&
5128 !D.hasGroupingParens() &&
5129 !Actions.containsUnexpandedParameterPacks(D) &&
5130 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5131 SourceLocation EllipsisLoc = ConsumeToken();
5132 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5133 // The ellipsis was put in the wrong place. Recover, and explain to
5134 // the user what they should have done.
5136 if (EllipsisLoc.isValid())
5137 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5140 D.setEllipsisLoc(EllipsisLoc);
5142 // The ellipsis can't be followed by a parenthesized declarator. We
5143 // check for that in ParseParenDeclarator, after we have disambiguated
5144 // the l_paren token.
5147 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5149 // We found something that indicates the start of an unqualified-id.
5150 // Parse that unqualified-id.
5151 bool AllowConstructorName;
5152 if (D.getDeclSpec().hasTypeSpecifier())
5153 AllowConstructorName = false;
5154 else if (D.getCXXScopeSpec().isSet())
5155 AllowConstructorName =
5156 (D.getContext() == Declarator::FileContext ||
5157 D.getContext() == Declarator::MemberContext);
5159 AllowConstructorName = (D.getContext() == Declarator::MemberContext);
5161 SourceLocation TemplateKWLoc;
5162 bool HadScope = D.getCXXScopeSpec().isValid();
5163 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5164 /*EnteringContext=*/true,
5165 /*AllowDestructorName=*/true,
5166 AllowConstructorName,
5170 // Once we're past the identifier, if the scope was bad, mark the
5171 // whole declarator bad.
5172 D.getCXXScopeSpec().isInvalid()) {
5173 D.SetIdentifier(nullptr, Tok.getLocation());
5174 D.setInvalidType(true);
5176 // ParseUnqualifiedId might have parsed a scope specifier during error
5177 // recovery. If it did so, enter that scope.
5178 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5179 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5180 D.getCXXScopeSpec()))
5181 DeclScopeObj.EnterDeclaratorScope();
5183 // Parsed the unqualified-id; update range information and move along.
5184 if (D.getSourceRange().getBegin().isInvalid())
5185 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5186 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5188 goto PastIdentifier;
5190 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5191 assert(!getLangOpts().CPlusPlus &&
5192 "There's a C++-specific check for tok::identifier above");
5193 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5194 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5195 D.SetRangeEnd(Tok.getLocation());
5197 goto PastIdentifier;
5198 } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) {
5199 // A virt-specifier isn't treated as an identifier if it appears after a
5200 // trailing-return-type.
5201 if (D.getContext() != Declarator::TrailingReturnContext ||
5202 !isCXX11VirtSpecifier(Tok)) {
5203 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5204 << FixItHint::CreateRemoval(Tok.getLocation());
5205 D.SetIdentifier(nullptr, Tok.getLocation());
5207 goto PastIdentifier;
5211 if (Tok.is(tok::l_paren)) {
5212 // direct-declarator: '(' declarator ')'
5213 // direct-declarator: '(' attributes declarator ')'
5214 // Example: 'char (*X)' or 'int (*XX)(void)'
5215 ParseParenDeclarator(D);
5217 // If the declarator was parenthesized, we entered the declarator
5218 // scope when parsing the parenthesized declarator, then exited
5219 // the scope already. Re-enter the scope, if we need to.
5220 if (D.getCXXScopeSpec().isSet()) {
5221 // If there was an error parsing parenthesized declarator, declarator
5222 // scope may have been entered before. Don't do it again.
5223 if (!D.isInvalidType() &&
5224 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5225 D.getCXXScopeSpec()))
5226 // Change the declaration context for name lookup, until this function
5227 // is exited (and the declarator has been parsed).
5228 DeclScopeObj.EnterDeclaratorScope();
5230 } else if (D.mayOmitIdentifier()) {
5231 // This could be something simple like "int" (in which case the declarator
5232 // portion is empty), if an abstract-declarator is allowed.
5233 D.SetIdentifier(nullptr, Tok.getLocation());
5235 // The grammar for abstract-pack-declarator does not allow grouping parens.
5236 // FIXME: Revisit this once core issue 1488 is resolved.
5237 if (D.hasEllipsis() && D.hasGroupingParens())
5238 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5239 diag::ext_abstract_pack_declarator_parens);
5241 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5243 if (Tok.is(tok::l_square))
5244 return ParseMisplacedBracketDeclarator(D);
5245 if (D.getContext() == Declarator::MemberContext) {
5246 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5247 diag::err_expected_member_name_or_semi)
5248 << (D.getDeclSpec().isEmpty() ? SourceRange()
5249 : D.getDeclSpec().getSourceRange());
5250 } else if (getLangOpts().CPlusPlus) {
5251 if (Tok.isOneOf(tok::period, tok::arrow))
5252 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5254 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5255 if (Tok.isAtStartOfLine() && Loc.isValid())
5256 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5257 << getLangOpts().CPlusPlus;
5259 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5260 diag::err_expected_unqualified_id)
5261 << getLangOpts().CPlusPlus;
5264 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5265 diag::err_expected_either)
5266 << tok::identifier << tok::l_paren;
5268 D.SetIdentifier(nullptr, Tok.getLocation());
5269 D.setInvalidType(true);
5273 assert(D.isPastIdentifier() &&
5274 "Haven't past the location of the identifier yet?");
5276 // Don't parse attributes unless we have parsed an unparenthesized name.
5277 if (D.hasName() && !D.getNumTypeObjects())
5278 MaybeParseCXX11Attributes(D);
5281 if (Tok.is(tok::l_paren)) {
5282 // Enter function-declaration scope, limiting any declarators to the
5283 // function prototype scope, including parameter declarators.
5284 ParseScope PrototypeScope(this,
5285 Scope::FunctionPrototypeScope|Scope::DeclScope|
5286 (D.isFunctionDeclaratorAFunctionDeclaration()
5287 ? Scope::FunctionDeclarationScope : 0));
5289 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5290 // In such a case, check if we actually have a function declarator; if it
5291 // is not, the declarator has been fully parsed.
5292 bool IsAmbiguous = false;
5293 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5294 // The name of the declarator, if any, is tentatively declared within
5295 // a possible direct initializer.
5296 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5297 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5298 TentativelyDeclaredIdentifiers.pop_back();
5299 if (!IsFunctionDecl)
5302 ParsedAttributes attrs(AttrFactory);
5303 BalancedDelimiterTracker T(*this, tok::l_paren);
5305 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5306 PrototypeScope.Exit();
5307 } else if (Tok.is(tok::l_square)) {
5308 ParseBracketDeclarator(D);
5315 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5316 /// only called before the identifier, so these are most likely just grouping
5317 /// parens for precedence. If we find that these are actually function
5318 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5320 /// direct-declarator:
5321 /// '(' declarator ')'
5322 /// [GNU] '(' attributes declarator ')'
5323 /// direct-declarator '(' parameter-type-list ')'
5324 /// direct-declarator '(' identifier-list[opt] ')'
5325 /// [GNU] direct-declarator '(' parameter-forward-declarations
5326 /// parameter-type-list[opt] ')'
5328 void Parser::ParseParenDeclarator(Declarator &D) {
5329 BalancedDelimiterTracker T(*this, tok::l_paren);
5332 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5334 // Eat any attributes before we look at whether this is a grouping or function
5335 // declarator paren. If this is a grouping paren, the attribute applies to
5336 // the type being built up, for example:
5337 // int (__attribute__(()) *x)(long y)
5338 // If this ends up not being a grouping paren, the attribute applies to the
5339 // first argument, for example:
5340 // int (__attribute__(()) int x)
5341 // In either case, we need to eat any attributes to be able to determine what
5342 // sort of paren this is.
5344 ParsedAttributes attrs(AttrFactory);
5345 bool RequiresArg = false;
5346 if (Tok.is(tok::kw___attribute)) {
5347 ParseGNUAttributes(attrs);
5349 // We require that the argument list (if this is a non-grouping paren) be
5350 // present even if the attribute list was empty.
5354 // Eat any Microsoft extensions.
5355 ParseMicrosoftTypeAttributes(attrs);
5357 // Eat any Borland extensions.
5358 if (Tok.is(tok::kw___pascal))
5359 ParseBorlandTypeAttributes(attrs);
5361 // If we haven't past the identifier yet (or where the identifier would be
5362 // stored, if this is an abstract declarator), then this is probably just
5363 // grouping parens. However, if this could be an abstract-declarator, then
5364 // this could also be the start of function arguments (consider 'void()').
5367 if (!D.mayOmitIdentifier()) {
5368 // If this can't be an abstract-declarator, this *must* be a grouping
5369 // paren, because we haven't seen the identifier yet.
5371 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5372 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5373 NextToken().is(tok::r_paren)) || // C++ int(...)
5374 isDeclarationSpecifier() || // 'int(int)' is a function.
5375 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5376 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5377 // considered to be a type, not a K&R identifier-list.
5380 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5384 // If this is a grouping paren, handle:
5385 // direct-declarator: '(' declarator ')'
5386 // direct-declarator: '(' attributes declarator ')'
5388 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5389 D.setEllipsisLoc(SourceLocation());
5391 bool hadGroupingParens = D.hasGroupingParens();
5392 D.setGroupingParens(true);
5393 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5396 D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
5397 T.getCloseLocation()),
5398 attrs, T.getCloseLocation());
5400 D.setGroupingParens(hadGroupingParens);
5402 // An ellipsis cannot be placed outside parentheses.
5403 if (EllipsisLoc.isValid())
5404 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5409 // Okay, if this wasn't a grouping paren, it must be the start of a function
5410 // argument list. Recognize that this declarator will never have an
5411 // identifier (and remember where it would have been), then call into
5412 // ParseFunctionDeclarator to handle of argument list.
5413 D.SetIdentifier(nullptr, Tok.getLocation());
5415 // Enter function-declaration scope, limiting any declarators to the
5416 // function prototype scope, including parameter declarators.
5417 ParseScope PrototypeScope(this,
5418 Scope::FunctionPrototypeScope | Scope::DeclScope |
5419 (D.isFunctionDeclaratorAFunctionDeclaration()
5420 ? Scope::FunctionDeclarationScope : 0));
5421 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
5422 PrototypeScope.Exit();
5425 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
5426 /// declarator D up to a paren, which indicates that we are parsing function
5429 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
5430 /// immediately after the open paren - they should be considered to be the
5431 /// first argument of a parameter.
5433 /// If RequiresArg is true, then the first argument of the function is required
5434 /// to be present and required to not be an identifier list.
5436 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
5437 /// (C++11) ref-qualifier[opt], exception-specification[opt],
5438 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
5440 /// [C++11] exception-specification:
5441 /// dynamic-exception-specification
5442 /// noexcept-specification
5444 void Parser::ParseFunctionDeclarator(Declarator &D,
5445 ParsedAttributes &FirstArgAttrs,
5446 BalancedDelimiterTracker &Tracker,
5449 assert(getCurScope()->isFunctionPrototypeScope() &&
5450 "Should call from a Function scope");
5451 // lparen is already consumed!
5452 assert(D.isPastIdentifier() && "Should not call before identifier!");
5454 // This should be true when the function has typed arguments.
5455 // Otherwise, it is treated as a K&R-style function.
5456 bool HasProto = false;
5457 // Build up an array of information about the parsed arguments.
5458 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
5459 // Remember where we see an ellipsis, if any.
5460 SourceLocation EllipsisLoc;
5462 DeclSpec DS(AttrFactory);
5463 bool RefQualifierIsLValueRef = true;
5464 SourceLocation RefQualifierLoc;
5465 SourceLocation ConstQualifierLoc;
5466 SourceLocation VolatileQualifierLoc;
5467 SourceLocation RestrictQualifierLoc;
5468 ExceptionSpecificationType ESpecType = EST_None;
5469 SourceRange ESpecRange;
5470 SmallVector<ParsedType, 2> DynamicExceptions;
5471 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5472 ExprResult NoexceptExpr;
5473 CachedTokens *ExceptionSpecTokens = 0;
5474 ParsedAttributes FnAttrs(AttrFactory);
5475 TypeResult TrailingReturnType;
5477 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
5478 EndLoc is the end location for the function declarator.
5479 They differ for trailing return types. */
5480 SourceLocation StartLoc, LocalEndLoc, EndLoc;
5481 SourceLocation LParenLoc, RParenLoc;
5482 LParenLoc = Tracker.getOpenLocation();
5483 StartLoc = LParenLoc;
5485 if (isFunctionDeclaratorIdentifierList()) {
5487 Diag(Tok, diag::err_argument_required_after_attribute);
5489 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
5491 Tracker.consumeClose();
5492 RParenLoc = Tracker.getCloseLocation();
5493 LocalEndLoc = RParenLoc;
5496 if (Tok.isNot(tok::r_paren))
5497 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
5499 else if (RequiresArg)
5500 Diag(Tok, diag::err_argument_required_after_attribute);
5502 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
5504 // If we have the closing ')', eat it.
5505 Tracker.consumeClose();
5506 RParenLoc = Tracker.getCloseLocation();
5507 LocalEndLoc = RParenLoc;
5510 if (getLangOpts().CPlusPlus) {
5511 // FIXME: Accept these components in any order, and produce fixits to
5512 // correct the order if the user gets it wrong. Ideally we should deal
5513 // with the pure-specifier in the same way.
5515 // Parse cv-qualifier-seq[opt].
5516 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
5517 /*AtomicAllowed*/ false);
5518 if (!DS.getSourceRange().getEnd().isInvalid()) {
5519 EndLoc = DS.getSourceRange().getEnd();
5520 ConstQualifierLoc = DS.getConstSpecLoc();
5521 VolatileQualifierLoc = DS.getVolatileSpecLoc();
5522 RestrictQualifierLoc = DS.getRestrictSpecLoc();
5525 // Parse ref-qualifier[opt].
5526 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
5527 EndLoc = RefQualifierLoc;
5529 // C++11 [expr.prim.general]p3:
5530 // If a declaration declares a member function or member function
5531 // template of a class X, the expression this is a prvalue of type
5532 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5533 // and the end of the function-definition, member-declarator, or
5535 // FIXME: currently, "static" case isn't handled correctly.
5536 bool IsCXX11MemberFunction =
5537 getLangOpts().CPlusPlus11 &&
5538 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5539 (D.getContext() == Declarator::MemberContext
5540 ? !D.getDeclSpec().isFriendSpecified()
5541 : D.getContext() == Declarator::FileContext &&
5542 D.getCXXScopeSpec().isValid() &&
5543 Actions.CurContext->isRecord());
5544 Sema::CXXThisScopeRAII ThisScope(Actions,
5545 dyn_cast<CXXRecordDecl>(Actions.CurContext),
5546 DS.getTypeQualifiers() |
5547 (D.getDeclSpec().isConstexprSpecified() &&
5548 !getLangOpts().CPlusPlus14
5549 ? Qualifiers::Const : 0),
5550 IsCXX11MemberFunction);
5552 // Parse exception-specification[opt].
5553 bool Delayed = D.isFirstDeclarationOfMember() &&
5554 D.isFunctionDeclaratorAFunctionDeclaration();
5555 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
5556 GetLookAheadToken(0).is(tok::kw_noexcept) &&
5557 GetLookAheadToken(1).is(tok::l_paren) &&
5558 GetLookAheadToken(2).is(tok::kw_noexcept) &&
5559 GetLookAheadToken(3).is(tok::l_paren) &&
5560 GetLookAheadToken(4).is(tok::identifier) &&
5561 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
5562 // HACK: We've got an exception-specification
5563 // noexcept(noexcept(swap(...)))
5565 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
5566 // on a 'swap' member function. This is a libstdc++ bug; the lookup
5567 // for 'swap' will only find the function we're currently declaring,
5568 // whereas it expects to find a non-member swap through ADL. Turn off
5569 // delayed parsing to give it a chance to find what it expects.
5572 ESpecType = tryParseExceptionSpecification(Delayed,
5575 DynamicExceptionRanges,
5577 ExceptionSpecTokens);
5578 if (ESpecType != EST_None)
5579 EndLoc = ESpecRange.getEnd();
5581 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
5582 // after the exception-specification.
5583 MaybeParseCXX11Attributes(FnAttrs);
5585 // Parse trailing-return-type[opt].
5586 LocalEndLoc = EndLoc;
5587 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
5588 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
5589 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
5590 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5591 LocalEndLoc = Tok.getLocation();
5593 TrailingReturnType = ParseTrailingReturnType(Range);
5594 EndLoc = Range.getEnd();
5599 // Remember that we parsed a function type, and remember the attributes.
5600 D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
5603 ParamInfo.data(), ParamInfo.size(),
5604 EllipsisLoc, RParenLoc,
5605 DS.getTypeQualifiers(),
5606 RefQualifierIsLValueRef,
5607 RefQualifierLoc, ConstQualifierLoc,
5608 VolatileQualifierLoc,
5609 RestrictQualifierLoc,
5610 /*MutableLoc=*/SourceLocation(),
5611 ESpecType, ESpecRange.getBegin(),
5612 DynamicExceptions.data(),
5613 DynamicExceptionRanges.data(),
5614 DynamicExceptions.size(),
5615 NoexceptExpr.isUsable() ?
5616 NoexceptExpr.get() : nullptr,
5617 ExceptionSpecTokens,
5618 StartLoc, LocalEndLoc, D,
5619 TrailingReturnType),
5623 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
5624 /// true if a ref-qualifier is found.
5625 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
5626 SourceLocation &RefQualifierLoc) {
5627 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
5628 Diag(Tok, getLangOpts().CPlusPlus11 ?
5629 diag::warn_cxx98_compat_ref_qualifier :
5630 diag::ext_ref_qualifier);
5632 RefQualifierIsLValueRef = Tok.is(tok::amp);
5633 RefQualifierLoc = ConsumeToken();
5639 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
5640 /// identifier list form for a K&R-style function: void foo(a,b,c)
5642 /// Note that identifier-lists are only allowed for normal declarators, not for
5643 /// abstract-declarators.
5644 bool Parser::isFunctionDeclaratorIdentifierList() {
5645 return !getLangOpts().CPlusPlus
5646 && Tok.is(tok::identifier)
5647 && !TryAltiVecVectorToken()
5648 // K&R identifier lists can't have typedefs as identifiers, per C99
5650 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
5651 // Identifier lists follow a really simple grammar: the identifiers can
5652 // be followed *only* by a ", identifier" or ")". However, K&R
5653 // identifier lists are really rare in the brave new modern world, and
5654 // it is very common for someone to typo a type in a non-K&R style
5655 // list. If we are presented with something like: "void foo(intptr x,
5656 // float y)", we don't want to start parsing the function declarator as
5657 // though it is a K&R style declarator just because intptr is an
5660 // To handle this, we check to see if the token after the first
5661 // identifier is a "," or ")". Only then do we parse it as an
5663 && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
5666 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
5667 /// we found a K&R-style identifier list instead of a typed parameter list.
5669 /// After returning, ParamInfo will hold the parsed parameters.
5671 /// identifier-list: [C99 6.7.5]
5673 /// identifier-list ',' identifier
5675 void Parser::ParseFunctionDeclaratorIdentifierList(
5677 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
5678 // If there was no identifier specified for the declarator, either we are in
5679 // an abstract-declarator, or we are in a parameter declarator which was found
5680 // to be abstract. In abstract-declarators, identifier lists are not valid:
5682 if (!D.getIdentifier())
5683 Diag(Tok, diag::ext_ident_list_in_param);
5685 // Maintain an efficient lookup of params we have seen so far.
5686 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
5689 // If this isn't an identifier, report the error and skip until ')'.
5690 if (Tok.isNot(tok::identifier)) {
5691 Diag(Tok, diag::err_expected) << tok::identifier;
5692 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
5693 // Forget we parsed anything.
5698 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
5700 // Reject 'typedef int y; int test(x, y)', but continue parsing.
5701 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
5702 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
5704 // Verify that the argument identifier has not already been mentioned.
5705 if (!ParamsSoFar.insert(ParmII).second) {
5706 Diag(Tok, diag::err_param_redefinition) << ParmII;
5708 // Remember this identifier in ParamInfo.
5709 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5714 // Eat the identifier.
5716 // The list continues if we see a comma.
5717 } while (TryConsumeToken(tok::comma));
5720 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
5721 /// after the opening parenthesis. This function will not parse a K&R-style
5722 /// identifier list.
5724 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
5725 /// caller parsed those arguments immediately after the open paren - they should
5726 /// be considered to be part of the first parameter.
5728 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
5729 /// be the location of the ellipsis, if any was parsed.
5731 /// parameter-type-list: [C99 6.7.5]
5733 /// parameter-list ',' '...'
5734 /// [C++] parameter-list '...'
5736 /// parameter-list: [C99 6.7.5]
5737 /// parameter-declaration
5738 /// parameter-list ',' parameter-declaration
5740 /// parameter-declaration: [C99 6.7.5]
5741 /// declaration-specifiers declarator
5742 /// [C++] declaration-specifiers declarator '=' assignment-expression
5743 /// [C++11] initializer-clause
5744 /// [GNU] declaration-specifiers declarator attributes
5745 /// declaration-specifiers abstract-declarator[opt]
5746 /// [C++] declaration-specifiers abstract-declarator[opt]
5747 /// '=' assignment-expression
5748 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
5749 /// [C++11] attribute-specifier-seq parameter-declaration
5751 void Parser::ParseParameterDeclarationClause(
5753 ParsedAttributes &FirstArgAttrs,
5754 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
5755 SourceLocation &EllipsisLoc) {
5757 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
5758 // before deciding this was a parameter-declaration-clause.
5759 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
5762 // Parse the declaration-specifiers.
5763 // Just use the ParsingDeclaration "scope" of the declarator.
5764 DeclSpec DS(AttrFactory);
5766 // Parse any C++11 attributes.
5767 MaybeParseCXX11Attributes(DS.getAttributes());
5769 // Skip any Microsoft attributes before a param.
5770 MaybeParseMicrosoftAttributes(DS.getAttributes());
5772 SourceLocation DSStart = Tok.getLocation();
5774 // If the caller parsed attributes for the first argument, add them now.
5775 // Take them so that we only apply the attributes to the first parameter.
5776 // FIXME: If we can leave the attributes in the token stream somehow, we can
5777 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
5779 DS.takeAttributesFrom(FirstArgAttrs);
5781 ParseDeclarationSpecifiers(DS);
5784 // Parse the declarator. This is "PrototypeContext" or
5785 // "LambdaExprParameterContext", because we must accept either
5786 // 'declarator' or 'abstract-declarator' here.
5787 Declarator ParmDeclarator(DS,
5788 D.getContext() == Declarator::LambdaExprContext ?
5789 Declarator::LambdaExprParameterContext :
5790 Declarator::PrototypeContext);
5791 ParseDeclarator(ParmDeclarator);
5793 // Parse GNU attributes, if present.
5794 MaybeParseGNUAttributes(ParmDeclarator);
5796 // Remember this parsed parameter in ParamInfo.
5797 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
5799 // DefArgToks is used when the parsing of default arguments needs
5801 CachedTokens *DefArgToks = nullptr;
5803 // If no parameter was specified, verify that *something* was specified,
5804 // otherwise we have a missing type and identifier.
5805 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
5806 ParmDeclarator.getNumTypeObjects() == 0) {
5807 // Completely missing, emit error.
5808 Diag(DSStart, diag::err_missing_param);
5810 // Otherwise, we have something. Add it and let semantic analysis try
5811 // to grok it and add the result to the ParamInfo we are building.
5813 // Last chance to recover from a misplaced ellipsis in an attempted
5814 // parameter pack declaration.
5815 if (Tok.is(tok::ellipsis) &&
5816 (NextToken().isNot(tok::r_paren) ||
5817 (!ParmDeclarator.getEllipsisLoc().isValid() &&
5818 !Actions.isUnexpandedParameterPackPermitted())) &&
5819 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
5820 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
5822 // Inform the actions module about the parameter declarator, so it gets
5823 // added to the current scope.
5824 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
5825 // Parse the default argument, if any. We parse the default
5826 // arguments in all dialects; the semantic analysis in
5827 // ActOnParamDefaultArgument will reject the default argument in
5829 if (Tok.is(tok::equal)) {
5830 SourceLocation EqualLoc = Tok.getLocation();
5832 // Parse the default argument
5833 if (D.getContext() == Declarator::MemberContext) {
5834 // If we're inside a class definition, cache the tokens
5835 // corresponding to the default argument. We'll actually parse
5836 // them when we see the end of the class definition.
5837 // FIXME: Can we use a smart pointer for Toks?
5838 DefArgToks = new CachedTokens;
5840 SourceLocation ArgStartLoc = NextToken().getLocation();
5841 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
5843 DefArgToks = nullptr;
5844 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5846 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
5853 // The argument isn't actually potentially evaluated unless it is
5855 EnterExpressionEvaluationContext Eval(Actions,
5856 Sema::PotentiallyEvaluatedIfUsed,
5859 ExprResult DefArgResult;
5860 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
5861 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
5862 DefArgResult = ParseBraceInitializer();
5864 DefArgResult = ParseAssignmentExpression();
5865 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
5866 if (DefArgResult.isInvalid()) {
5867 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
5868 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
5870 // Inform the actions module about the default argument
5871 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
5872 DefArgResult.get());
5877 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
5878 ParmDeclarator.getIdentifierLoc(),
5879 Param, DefArgToks));
5882 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
5883 if (!getLangOpts().CPlusPlus) {
5884 // We have ellipsis without a preceding ',', which is ill-formed
5885 // in C. Complain and provide the fix.
5886 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
5887 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5888 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
5889 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
5890 // It looks like this was supposed to be a parameter pack. Warn and
5891 // point out where the ellipsis should have gone.
5892 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
5893 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
5894 << ParmEllipsis.isValid() << ParmEllipsis;
5895 if (ParmEllipsis.isValid()) {
5897 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
5899 Diag(ParmDeclarator.getIdentifierLoc(),
5900 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
5901 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
5903 << !ParmDeclarator.hasName();
5905 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
5906 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
5909 // We can't have any more parameters after an ellipsis.
5913 // If the next token is a comma, consume it and keep reading arguments.
5914 } while (TryConsumeToken(tok::comma));
5917 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5918 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5919 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5920 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5921 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5922 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5923 /// attribute-specifier-seq[opt]
5924 void Parser::ParseBracketDeclarator(Declarator &D) {
5925 if (CheckProhibitedCXX11Attribute())
5928 BalancedDelimiterTracker T(*this, tok::l_square);
5931 // C array syntax has many features, but by-far the most common is [] and [4].
5932 // This code does a fast path to handle some of the most obvious cases.
5933 if (Tok.getKind() == tok::r_square) {
5935 ParsedAttributes attrs(AttrFactory);
5936 MaybeParseCXX11Attributes(attrs);
5938 // Remember that we parsed the empty array type.
5939 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
5940 T.getOpenLocation(),
5941 T.getCloseLocation()),
5942 attrs, T.getCloseLocation());
5944 } else if (Tok.getKind() == tok::numeric_constant &&
5945 GetLookAheadToken(1).is(tok::r_square)) {
5946 // [4] is very common. Parse the numeric constant expression.
5947 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
5951 ParsedAttributes attrs(AttrFactory);
5952 MaybeParseCXX11Attributes(attrs);
5954 // Remember that we parsed a array type, and remember its features.
5955 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
5957 T.getOpenLocation(),
5958 T.getCloseLocation()),
5959 attrs, T.getCloseLocation());
5963 // If valid, this location is the position where we read the 'static' keyword.
5964 SourceLocation StaticLoc;
5965 TryConsumeToken(tok::kw_static, StaticLoc);
5967 // If there is a type-qualifier-list, read it now.
5968 // Type qualifiers in an array subscript are a C99 feature.
5969 DeclSpec DS(AttrFactory);
5970 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
5972 // If we haven't already read 'static', check to see if there is one after the
5973 // type-qualifier-list.
5974 if (!StaticLoc.isValid())
5975 TryConsumeToken(tok::kw_static, StaticLoc);
5977 // Handle "direct-declarator [ type-qual-list[opt] * ]".
5978 bool isStar = false;
5979 ExprResult NumElements;
5981 // Handle the case where we have '[*]' as the array size. However, a leading
5982 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
5983 // the token after the star is a ']'. Since stars in arrays are
5984 // infrequent, use of lookahead is not costly here.
5985 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
5986 ConsumeToken(); // Eat the '*'.
5988 if (StaticLoc.isValid()) {
5989 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
5990 StaticLoc = SourceLocation(); // Drop the static.
5993 } else if (Tok.isNot(tok::r_square)) {
5994 // Note, in C89, this production uses the constant-expr production instead
5995 // of assignment-expr. The only difference is that assignment-expr allows
5996 // things like '=' and '*='. Sema rejects these in C89 mode because they
5997 // are not i-c-e's, so we don't need to distinguish between the two here.
5999 // Parse the constant-expression or assignment-expression now (depending
6001 if (getLangOpts().CPlusPlus) {
6002 NumElements = ParseConstantExpression();
6004 EnterExpressionEvaluationContext Unevaluated(Actions,
6005 Sema::ConstantEvaluated);
6007 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6010 if (StaticLoc.isValid()) {
6011 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6012 StaticLoc = SourceLocation(); // Drop the static.
6016 // If there was an error parsing the assignment-expression, recover.
6017 if (NumElements.isInvalid()) {
6018 D.setInvalidType(true);
6019 // If the expression was invalid, skip it.
6020 SkipUntil(tok::r_square, StopAtSemi);
6026 ParsedAttributes attrs(AttrFactory);
6027 MaybeParseCXX11Attributes(attrs);
6029 // Remember that we parsed a array type, and remember its features.
6030 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
6031 StaticLoc.isValid(), isStar,
6033 T.getOpenLocation(),
6034 T.getCloseLocation()),
6035 attrs, T.getCloseLocation());
6038 /// Diagnose brackets before an identifier.
6039 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6040 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6041 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6043 SourceLocation StartBracketLoc = Tok.getLocation();
6044 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6046 while (Tok.is(tok::l_square)) {
6047 ParseBracketDeclarator(TempDeclarator);
6050 // Stuff the location of the start of the brackets into the Declarator.
6051 // The diagnostics from ParseDirectDeclarator will make more sense if
6052 // they use this location instead.
6053 if (Tok.is(tok::semi))
6054 D.getName().EndLocation = StartBracketLoc;
6056 SourceLocation SuggestParenLoc = Tok.getLocation();
6058 // Now that the brackets are removed, try parsing the declarator again.
6059 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6061 // Something went wrong parsing the brackets, in which case,
6062 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6064 if (TempDeclarator.getNumTypeObjects() == 0)
6067 // Determine if parens will need to be suggested in the diagnostic.
6068 bool NeedParens = false;
6069 if (D.getNumTypeObjects() != 0) {
6070 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6071 case DeclaratorChunk::Pointer:
6072 case DeclaratorChunk::Reference:
6073 case DeclaratorChunk::BlockPointer:
6074 case DeclaratorChunk::MemberPointer:
6077 case DeclaratorChunk::Array:
6078 case DeclaratorChunk::Function:
6079 case DeclaratorChunk::Paren:
6085 // Create a DeclaratorChunk for the inserted parens.
6086 ParsedAttributes attrs(AttrFactory);
6087 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6088 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
6092 // Adding back the bracket info to the end of the Declarator.
6093 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6094 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6095 ParsedAttributes attrs(AttrFactory);
6096 attrs.set(Chunk.Common.AttrList);
6097 D.AddTypeInfo(Chunk, attrs, SourceLocation());
6100 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6101 // If parentheses are required, always suggest them.
6102 if (!D.getIdentifier() && !NeedParens)
6105 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6107 // Generate the move bracket error message.
6108 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6109 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6112 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6113 << getLangOpts().CPlusPlus
6114 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6115 << FixItHint::CreateInsertion(EndLoc, ")")
6116 << FixItHint::CreateInsertionFromRange(
6117 EndLoc, CharSourceRange(BracketRange, true))
6118 << FixItHint::CreateRemoval(BracketRange);
6120 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6121 << getLangOpts().CPlusPlus
6122 << FixItHint::CreateInsertionFromRange(
6123 EndLoc, CharSourceRange(BracketRange, true))
6124 << FixItHint::CreateRemoval(BracketRange);
6128 /// [GNU] typeof-specifier:
6129 /// typeof ( expressions )
6130 /// typeof ( type-name )
6131 /// [GNU/C++] typeof unary-expression
6133 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6134 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6136 SourceLocation StartLoc = ConsumeToken();
6138 const bool hasParens = Tok.is(tok::l_paren);
6140 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
6141 Sema::ReuseLambdaContextDecl);
6145 SourceRange CastRange;
6146 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6147 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6149 DS.setTypeofParensRange(CastRange);
6151 if (CastRange.getEnd().isInvalid())
6152 // FIXME: Not accurate, the range gets one token more than it should.
6153 DS.SetRangeEnd(Tok.getLocation());
6155 DS.SetRangeEnd(CastRange.getEnd());
6159 DS.SetTypeSpecError();
6163 const char *PrevSpec = nullptr;
6165 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6166 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6168 Actions.getASTContext().getPrintingPolicy()))
6169 Diag(StartLoc, DiagID) << PrevSpec;
6173 // If we get here, the operand to the typeof was an expresion.
6174 if (Operand.isInvalid()) {
6175 DS.SetTypeSpecError();
6179 // We might need to transform the operand if it is potentially evaluated.
6180 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6181 if (Operand.isInvalid()) {
6182 DS.SetTypeSpecError();
6186 const char *PrevSpec = nullptr;
6188 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6189 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6190 DiagID, Operand.get(),
6191 Actions.getASTContext().getPrintingPolicy()))
6192 Diag(StartLoc, DiagID) << PrevSpec;
6195 /// [C11] atomic-specifier:
6196 /// _Atomic ( type-name )
6198 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6199 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6200 "Not an atomic specifier");
6202 SourceLocation StartLoc = ConsumeToken();
6203 BalancedDelimiterTracker T(*this, tok::l_paren);
6204 if (T.consumeOpen())
6207 TypeResult Result = ParseTypeName();
6208 if (Result.isInvalid()) {
6209 SkipUntil(tok::r_paren, StopAtSemi);
6216 if (T.getCloseLocation().isInvalid())
6219 DS.setTypeofParensRange(T.getRange());
6220 DS.SetRangeEnd(T.getCloseLocation());
6222 const char *PrevSpec = nullptr;
6224 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6225 DiagID, Result.get(),
6226 Actions.getASTContext().getPrintingPolicy()))
6227 Diag(StartLoc, DiagID) << PrevSpec;
6231 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6232 /// from TryAltiVecVectorToken.
6233 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6234 Token Next = NextToken();
6235 switch (Next.getKind()) {
6236 default: return false;
6239 case tok::kw_signed:
6240 case tok::kw_unsigned:
6245 case tok::kw_double:
6247 case tok::kw___bool:
6248 case tok::kw___pixel:
6249 Tok.setKind(tok::kw___vector);
6251 case tok::identifier:
6252 if (Next.getIdentifierInfo() == Ident_pixel) {
6253 Tok.setKind(tok::kw___vector);
6256 if (Next.getIdentifierInfo() == Ident_bool) {
6257 Tok.setKind(tok::kw___vector);
6264 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6265 const char *&PrevSpec, unsigned &DiagID,
6267 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6268 if (Tok.getIdentifierInfo() == Ident_vector) {
6269 Token Next = NextToken();
6270 switch (Next.getKind()) {
6273 case tok::kw_signed:
6274 case tok::kw_unsigned:
6279 case tok::kw_double:
6281 case tok::kw___bool:
6282 case tok::kw___pixel:
6283 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6285 case tok::identifier:
6286 if (Next.getIdentifierInfo() == Ident_pixel) {
6287 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6290 if (Next.getIdentifierInfo() == Ident_bool) {
6291 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6298 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6299 DS.isTypeAltiVecVector()) {
6300 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6302 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6303 DS.isTypeAltiVecVector()) {
6304 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);