1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/PrettyDeclStackTrace.h"
19 #include "clang/Basic/AddressSpaces.h"
20 #include "clang/Basic/Attributes.h"
21 #include "clang/Basic/CharInfo.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Parse/ParseDiagnostic.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/Scope.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringSwitch.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
35 // C99 6.7: Declarations.
36 //===----------------------------------------------------------------------===//
39 /// type-name: [C99 6.7.6]
40 /// specifier-qualifier-list abstract-declarator[opt]
42 /// Called type-id in C++.
43 TypeResult Parser::ParseTypeName(SourceRange *Range,
44 DeclaratorContext Context,
47 ParsedAttributes *Attrs) {
48 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49 if (DSC == DeclSpecContext::DSC_normal)
50 DSC = DeclSpecContext::DSC_type_specifier;
52 // Parse the common declaration-specifiers piece.
53 DeclSpec DS(AttrFactory);
55 DS.addAttributes(*Attrs);
56 ParseSpecifierQualifierList(DS, AS, DSC);
58 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
60 // Parse the abstract-declarator, if present.
61 Declarator DeclaratorInfo(DS, Context);
62 ParseDeclarator(DeclaratorInfo);
64 *Range = DeclaratorInfo.getSourceRange();
66 if (DeclaratorInfo.isInvalidType())
69 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
72 /// Normalizes an attribute name by dropping prefixed and suffixed __.
73 static StringRef normalizeAttrName(StringRef Name) {
74 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
75 return Name.drop_front(2).drop_back(2);
79 /// isAttributeLateParsed - Return true if the attribute has arguments that
80 /// require late parsing.
81 static bool isAttributeLateParsed(const IdentifierInfo &II) {
82 #define CLANG_ATTR_LATE_PARSED_LIST
83 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
84 #include "clang/Parse/AttrParserStringSwitches.inc"
86 #undef CLANG_ATTR_LATE_PARSED_LIST
89 /// ParseGNUAttributes - Parse a non-empty attributes list.
93 /// attributes attribute
96 /// '__attribute__' '(' '(' attribute-list ')' ')'
98 /// [GNU] attribute-list:
100 /// attribute_list ',' attrib
105 /// attrib-name '(' identifier ')'
106 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
107 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
109 /// [GNU] attrib-name:
115 /// Whether an attribute takes an 'identifier' is determined by the
116 /// attrib-name. GCC's behavior here is not worth imitating:
118 /// * In C mode, if the attribute argument list starts with an identifier
119 /// followed by a ',' or an ')', and the identifier doesn't resolve to
120 /// a type, it is parsed as an identifier. If the attribute actually
121 /// wanted an expression, it's out of luck (but it turns out that no
122 /// attributes work that way, because C constant expressions are very
124 /// * In C++ mode, if the attribute argument list starts with an identifier,
125 /// and the attribute *wants* an identifier, it is parsed as an identifier.
126 /// At block scope, any additional tokens between the identifier and the
127 /// ',' or ')' are ignored, otherwise they produce a parse error.
129 /// We follow the C++ model, but don't allow junk after the identifier.
130 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
131 SourceLocation *endLoc,
132 LateParsedAttrList *LateAttrs,
134 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
136 while (Tok.is(tok::kw___attribute)) {
138 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
140 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
143 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
144 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
147 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
149 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
150 if (TryConsumeToken(tok::comma))
153 // Expect an identifier or declaration specifier (const, int, etc.)
154 if (Tok.isAnnotation())
156 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
160 SourceLocation AttrNameLoc = ConsumeToken();
162 if (Tok.isNot(tok::l_paren)) {
163 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
168 // Handle "parameterized" attributes
169 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
170 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
171 SourceLocation(), ParsedAttr::AS_GNU, D);
175 // Handle attributes with arguments that require late parsing.
176 LateParsedAttribute *LA =
177 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
178 LateAttrs->push_back(LA);
180 // Attributes in a class are parsed at the end of the class, along
181 // with other late-parsed declarations.
182 if (!ClassStack.empty() && !LateAttrs->parseSoon())
183 getCurrentClass().LateParsedDeclarations.push_back(LA);
185 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
186 // recursively consumes balanced parens.
187 LA->Toks.push_back(Tok);
189 // Consume everything up to and including the matching right parens.
190 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
194 Eof.setLocation(Tok.getLocation());
195 LA->Toks.push_back(Eof);
198 if (ExpectAndConsume(tok::r_paren))
199 SkipUntil(tok::r_paren, StopAtSemi);
200 SourceLocation Loc = Tok.getLocation();
201 if (ExpectAndConsume(tok::r_paren))
202 SkipUntil(tok::r_paren, StopAtSemi);
208 /// Determine whether the given attribute has an identifier argument.
209 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
210 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
211 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
212 #include "clang/Parse/AttrParserStringSwitches.inc"
214 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
217 /// Determine whether the given attribute has a variadic identifier argument.
218 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
219 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
220 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
221 #include "clang/Parse/AttrParserStringSwitches.inc"
223 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
226 /// Determine whether the given attribute parses a type argument.
227 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
228 #define CLANG_ATTR_TYPE_ARG_LIST
229 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
230 #include "clang/Parse/AttrParserStringSwitches.inc"
232 #undef CLANG_ATTR_TYPE_ARG_LIST
235 /// Determine whether the given attribute requires parsing its arguments
236 /// in an unevaluated context or not.
237 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
238 #define CLANG_ATTR_ARG_CONTEXT_LIST
239 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
240 #include "clang/Parse/AttrParserStringSwitches.inc"
242 #undef CLANG_ATTR_ARG_CONTEXT_LIST
245 IdentifierLoc *Parser::ParseIdentifierLoc() {
246 assert(Tok.is(tok::identifier) && "expected an identifier");
247 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
249 Tok.getIdentifierInfo());
254 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
255 SourceLocation AttrNameLoc,
256 ParsedAttributes &Attrs,
257 SourceLocation *EndLoc,
258 IdentifierInfo *ScopeName,
259 SourceLocation ScopeLoc,
260 ParsedAttr::Syntax Syntax) {
261 BalancedDelimiterTracker Parens(*this, tok::l_paren);
262 Parens.consumeOpen();
265 if (Tok.isNot(tok::r_paren))
268 if (Parens.consumeClose())
275 Attrs.addNewTypeAttr(&AttrName,
276 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
277 ScopeName, ScopeLoc, T.get(), Syntax);
279 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
280 ScopeName, ScopeLoc, nullptr, 0, Syntax);
283 unsigned Parser::ParseAttributeArgsCommon(
284 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
285 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
286 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
287 // Ignore the left paren location for now.
291 if (Tok.is(tok::identifier)) {
292 // If this attribute wants an 'identifier' argument, make it so.
293 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
294 attributeHasVariadicIdentifierArg(*AttrName);
295 ParsedAttr::Kind AttrKind =
296 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
298 // If we don't know how to parse this attribute, but this is the only
299 // token in this argument, assume it's meant to be an identifier.
300 if (AttrKind == ParsedAttr::UnknownAttribute ||
301 AttrKind == ParsedAttr::IgnoredAttribute) {
302 const Token &Next = NextToken();
303 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
307 ArgExprs.push_back(ParseIdentifierLoc());
310 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
312 if (!ArgExprs.empty())
315 // Parse the non-empty comma-separated list of expressions.
318 if (Tok.is(tok::identifier) &&
319 attributeHasVariadicIdentifierArg(*AttrName)) {
320 ArgExprs.push_back(ParseIdentifierLoc());
322 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
323 EnterExpressionEvaluationContext Unevaluated(
325 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
326 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
329 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
330 if (ArgExpr.isInvalid()) {
331 SkipUntil(tok::r_paren, StopAtSemi);
334 ArgExprs.push_back(ArgExpr.get());
336 // Eat the comma, move to the next argument
337 } while (TryConsumeToken(tok::comma));
340 SourceLocation RParen = Tok.getLocation();
341 if (!ExpectAndConsume(tok::r_paren)) {
342 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
343 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
344 ArgExprs.data(), ArgExprs.size(), Syntax);
350 return static_cast<unsigned>(ArgExprs.size());
353 /// Parse the arguments to a parameterized GNU attribute or
354 /// a C++11 attribute in "gnu" namespace.
355 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
356 SourceLocation AttrNameLoc,
357 ParsedAttributes &Attrs,
358 SourceLocation *EndLoc,
359 IdentifierInfo *ScopeName,
360 SourceLocation ScopeLoc,
361 ParsedAttr::Syntax Syntax,
364 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
366 ParsedAttr::Kind AttrKind =
367 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
369 if (AttrKind == ParsedAttr::AT_Availability) {
370 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
373 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
374 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
375 ScopeName, ScopeLoc, Syntax);
377 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
378 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
379 ScopeName, ScopeLoc, Syntax);
381 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
382 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
383 ScopeName, ScopeLoc, Syntax);
385 } else if (attributeIsTypeArgAttr(*AttrName)) {
386 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
391 // These may refer to the function arguments, but need to be parsed early to
392 // participate in determining whether it's a redeclaration.
393 llvm::Optional<ParseScope> PrototypeScope;
394 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
395 D && D->isFunctionDeclarator()) {
396 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
397 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
398 Scope::FunctionDeclarationScope |
400 for (unsigned i = 0; i != FTI.NumParams; ++i) {
401 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
402 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
406 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
410 unsigned Parser::ParseClangAttributeArgs(
411 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
412 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
413 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
414 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
416 ParsedAttr::Kind AttrKind =
417 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
421 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
422 ScopeName, ScopeLoc, Syntax);
423 case ParsedAttr::AT_ExternalSourceSymbol:
424 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
425 ScopeName, ScopeLoc, Syntax);
427 case ParsedAttr::AT_Availability:
428 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
431 case ParsedAttr::AT_ObjCBridgeRelated:
432 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
433 ScopeName, ScopeLoc, Syntax);
435 case ParsedAttr::AT_TypeTagForDatatype:
436 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
437 ScopeName, ScopeLoc, Syntax);
440 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
443 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
444 SourceLocation AttrNameLoc,
445 ParsedAttributes &Attrs) {
446 // If the attribute isn't known, we will not attempt to parse any
448 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
449 getTargetInfo(), getLangOpts())) {
450 // Eat the left paren, then skip to the ending right paren.
452 SkipUntil(tok::r_paren);
456 SourceLocation OpenParenLoc = Tok.getLocation();
458 if (AttrName->getName() == "property") {
459 // The property declspec is more complex in that it can take one or two
460 // assignment expressions as a parameter, but the lhs of the assignment
461 // must be named get or put.
463 BalancedDelimiterTracker T(*this, tok::l_paren);
464 T.expectAndConsume(diag::err_expected_lparen_after,
465 AttrName->getNameStart(), tok::r_paren);
470 AK_Get = 1 // indices into AccessorNames
472 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
473 bool HasInvalidAccessor = false;
475 // Parse the accessor specifications.
477 // Stop if this doesn't look like an accessor spec.
478 if (!Tok.is(tok::identifier)) {
479 // If the user wrote a completely empty list, use a special diagnostic.
480 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
481 AccessorNames[AK_Put] == nullptr &&
482 AccessorNames[AK_Get] == nullptr) {
483 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
487 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
492 SourceLocation KindLoc = Tok.getLocation();
493 StringRef KindStr = Tok.getIdentifierInfo()->getName();
494 if (KindStr == "get") {
496 } else if (KindStr == "put") {
499 // Recover from the common mistake of using 'set' instead of 'put'.
500 } else if (KindStr == "set") {
501 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
502 << FixItHint::CreateReplacement(KindLoc, "put");
505 // Handle the mistake of forgetting the accessor kind by skipping
507 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
508 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
510 HasInvalidAccessor = true;
511 goto next_property_accessor;
513 // Otherwise, complain about the unknown accessor kind.
515 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
516 HasInvalidAccessor = true;
519 // Try to keep parsing unless it doesn't look like an accessor spec.
520 if (!NextToken().is(tok::equal))
524 // Consume the identifier.
528 if (!TryConsumeToken(tok::equal)) {
529 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
534 // Expect the method name.
535 if (!Tok.is(tok::identifier)) {
536 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
540 if (Kind == AK_Invalid) {
541 // Just drop invalid accessors.
542 } else if (AccessorNames[Kind] != nullptr) {
543 // Complain about the repeated accessor, ignore it, and keep parsing.
544 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
546 AccessorNames[Kind] = Tok.getIdentifierInfo();
550 next_property_accessor:
551 // Keep processing accessors until we run out.
552 if (TryConsumeToken(tok::comma))
555 // If we run into the ')', stop without consuming it.
556 if (Tok.is(tok::r_paren))
559 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
563 // Only add the property attribute if it was well-formed.
564 if (!HasInvalidAccessor)
565 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
566 AccessorNames[AK_Get], AccessorNames[AK_Put],
567 ParsedAttr::AS_Declspec);
569 return !HasInvalidAccessor;
573 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
574 SourceLocation(), ParsedAttr::AS_Declspec);
576 // If this attribute's args were parsed, and it was expected to have
577 // arguments but none were provided, emit a diagnostic.
578 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
579 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
585 /// [MS] decl-specifier:
586 /// __declspec ( extended-decl-modifier-seq )
588 /// [MS] extended-decl-modifier-seq:
589 /// extended-decl-modifier[opt]
590 /// extended-decl-modifier extended-decl-modifier-seq
591 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
592 SourceLocation *End) {
593 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
594 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
596 while (Tok.is(tok::kw___declspec)) {
598 BalancedDelimiterTracker T(*this, tok::l_paren);
599 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
603 // An empty declspec is perfectly legal and should not warn. Additionally,
604 // you can specify multiple attributes per declspec.
605 while (Tok.isNot(tok::r_paren)) {
606 // Attribute not present.
607 if (TryConsumeToken(tok::comma))
610 // We expect either a well-known identifier or a generic string. Anything
611 // else is a malformed declspec.
612 bool IsString = Tok.getKind() == tok::string_literal;
613 if (!IsString && Tok.getKind() != tok::identifier &&
614 Tok.getKind() != tok::kw_restrict) {
615 Diag(Tok, diag::err_ms_declspec_type);
620 IdentifierInfo *AttrName;
621 SourceLocation AttrNameLoc;
623 SmallString<8> StrBuffer;
624 bool Invalid = false;
625 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
630 AttrName = PP.getIdentifierInfo(Str);
631 AttrNameLoc = ConsumeStringToken();
633 AttrName = Tok.getIdentifierInfo();
634 AttrNameLoc = ConsumeToken();
637 bool AttrHandled = false;
639 // Parse attribute arguments.
640 if (Tok.is(tok::l_paren))
641 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
642 else if (AttrName->getName() == "property")
643 // The property attribute must have an argument list.
644 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
645 << AttrName->getName();
648 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
649 ParsedAttr::AS_Declspec);
653 *End = T.getCloseLocation();
657 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
658 // Treat these like attributes
660 switch (Tok.getKind()) {
661 case tok::kw___fastcall:
662 case tok::kw___stdcall:
663 case tok::kw___thiscall:
664 case tok::kw___regcall:
665 case tok::kw___cdecl:
666 case tok::kw___vectorcall:
667 case tok::kw___ptr64:
669 case tok::kw___ptr32:
671 case tok::kw___uptr: {
672 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
673 SourceLocation AttrNameLoc = ConsumeToken();
674 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
675 ParsedAttr::AS_Keyword);
684 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
685 SourceLocation StartLoc = Tok.getLocation();
686 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
688 if (EndLoc.isValid()) {
689 SourceRange Range(StartLoc, EndLoc);
690 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
694 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
695 SourceLocation EndLoc;
698 switch (Tok.getKind()) {
700 case tok::kw_volatile:
701 case tok::kw___fastcall:
702 case tok::kw___stdcall:
703 case tok::kw___thiscall:
704 case tok::kw___cdecl:
705 case tok::kw___vectorcall:
706 case tok::kw___ptr32:
707 case tok::kw___ptr64:
709 case tok::kw___unaligned:
712 EndLoc = ConsumeToken();
720 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
721 // Treat these like attributes
722 while (Tok.is(tok::kw___pascal)) {
723 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
724 SourceLocation AttrNameLoc = ConsumeToken();
725 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
726 ParsedAttr::AS_Keyword);
730 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
731 // Treat these like attributes
732 while (Tok.is(tok::kw___kernel)) {
733 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
734 SourceLocation AttrNameLoc = ConsumeToken();
735 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
736 ParsedAttr::AS_Keyword);
740 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
741 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
742 SourceLocation AttrNameLoc = Tok.getLocation();
743 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
744 ParsedAttr::AS_Keyword);
747 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
748 // Treat these like attributes, even though they're type specifiers.
750 switch (Tok.getKind()) {
751 case tok::kw__Nonnull:
752 case tok::kw__Nullable:
753 case tok::kw__Null_unspecified: {
754 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
755 SourceLocation AttrNameLoc = ConsumeToken();
756 if (!getLangOpts().ObjC)
757 Diag(AttrNameLoc, diag::ext_nullability)
759 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
760 ParsedAttr::AS_Keyword);
769 static bool VersionNumberSeparator(const char Separator) {
770 return (Separator == '.' || Separator == '_');
773 /// Parse a version number.
777 /// simple-integer '.' simple-integer
778 /// simple-integer '_' simple-integer
779 /// simple-integer '.' simple-integer '.' simple-integer
780 /// simple-integer '_' simple-integer '_' simple-integer
781 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
782 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
784 if (!Tok.is(tok::numeric_constant)) {
785 Diag(Tok, diag::err_expected_version);
786 SkipUntil(tok::comma, tok::r_paren,
787 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
788 return VersionTuple();
791 // Parse the major (and possibly minor and subminor) versions, which
792 // are stored in the numeric constant. We utilize a quirk of the
793 // lexer, which is that it handles something like 1.2.3 as a single
794 // numeric constant, rather than two separate tokens.
795 SmallString<512> Buffer;
796 Buffer.resize(Tok.getLength()+1);
797 const char *ThisTokBegin = &Buffer[0];
799 // Get the spelling of the token, which eliminates trigraphs, etc.
800 bool Invalid = false;
801 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
803 return VersionTuple();
805 // Parse the major version.
806 unsigned AfterMajor = 0;
808 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
809 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
813 if (AfterMajor == 0) {
814 Diag(Tok, diag::err_expected_version);
815 SkipUntil(tok::comma, tok::r_paren,
816 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
817 return VersionTuple();
820 if (AfterMajor == ActualLength) {
823 // We only had a single version component.
825 Diag(Tok, diag::err_zero_version);
826 return VersionTuple();
829 return VersionTuple(Major);
832 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
833 if (!VersionNumberSeparator(AfterMajorSeparator)
834 || (AfterMajor + 1 == ActualLength)) {
835 Diag(Tok, diag::err_expected_version);
836 SkipUntil(tok::comma, tok::r_paren,
837 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
838 return VersionTuple();
841 // Parse the minor version.
842 unsigned AfterMinor = AfterMajor + 1;
844 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
845 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
849 if (AfterMinor == ActualLength) {
852 // We had major.minor.
853 if (Major == 0 && Minor == 0) {
854 Diag(Tok, diag::err_zero_version);
855 return VersionTuple();
858 return VersionTuple(Major, Minor);
861 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
862 // If what follows is not a '.' or '_', we have a problem.
863 if (!VersionNumberSeparator(AfterMinorSeparator)) {
864 Diag(Tok, diag::err_expected_version);
865 SkipUntil(tok::comma, tok::r_paren,
866 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
867 return VersionTuple();
870 // Warn if separators, be it '.' or '_', do not match.
871 if (AfterMajorSeparator != AfterMinorSeparator)
872 Diag(Tok, diag::warn_expected_consistent_version_separator);
874 // Parse the subminor version.
875 unsigned AfterSubminor = AfterMinor + 1;
876 unsigned Subminor = 0;
877 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
878 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
882 if (AfterSubminor != ActualLength) {
883 Diag(Tok, diag::err_expected_version);
884 SkipUntil(tok::comma, tok::r_paren,
885 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
886 return VersionTuple();
889 return VersionTuple(Major, Minor, Subminor);
892 /// Parse the contents of the "availability" attribute.
894 /// availability-attribute:
895 /// 'availability' '(' platform ',' opt-strict version-arg-list,
896 /// opt-replacement, opt-message')'
904 /// version-arg-list:
906 /// version-arg ',' version-arg-list
909 /// 'introduced' '=' version
910 /// 'deprecated' '=' version
911 /// 'obsoleted' = version
914 /// 'replacement' '=' <string>
916 /// 'message' '=' <string>
917 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
918 SourceLocation AvailabilityLoc,
919 ParsedAttributes &attrs,
920 SourceLocation *endLoc,
921 IdentifierInfo *ScopeName,
922 SourceLocation ScopeLoc,
923 ParsedAttr::Syntax Syntax) {
924 enum { Introduced, Deprecated, Obsoleted, Unknown };
925 AvailabilityChange Changes[Unknown];
926 ExprResult MessageExpr, ReplacementExpr;
929 BalancedDelimiterTracker T(*this, tok::l_paren);
930 if (T.consumeOpen()) {
931 Diag(Tok, diag::err_expected) << tok::l_paren;
935 // Parse the platform name.
936 if (Tok.isNot(tok::identifier)) {
937 Diag(Tok, diag::err_availability_expected_platform);
938 SkipUntil(tok::r_paren, StopAtSemi);
941 IdentifierLoc *Platform = ParseIdentifierLoc();
942 if (const IdentifierInfo *const Ident = Platform->Ident) {
943 // Canonicalize platform name from "macosx" to "macos".
944 if (Ident->getName() == "macosx")
945 Platform->Ident = PP.getIdentifierInfo("macos");
946 // Canonicalize platform name from "macosx_app_extension" to
947 // "macos_app_extension".
948 else if (Ident->getName() == "macosx_app_extension")
949 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
951 Platform->Ident = PP.getIdentifierInfo(
952 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
955 // Parse the ',' following the platform name.
956 if (ExpectAndConsume(tok::comma)) {
957 SkipUntil(tok::r_paren, StopAtSemi);
961 // If we haven't grabbed the pointers for the identifiers
962 // "introduced", "deprecated", and "obsoleted", do so now.
963 if (!Ident_introduced) {
964 Ident_introduced = PP.getIdentifierInfo("introduced");
965 Ident_deprecated = PP.getIdentifierInfo("deprecated");
966 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
967 Ident_unavailable = PP.getIdentifierInfo("unavailable");
968 Ident_message = PP.getIdentifierInfo("message");
969 Ident_strict = PP.getIdentifierInfo("strict");
970 Ident_replacement = PP.getIdentifierInfo("replacement");
973 // Parse the optional "strict", the optional "replacement" and the set of
974 // introductions/deprecations/removals.
975 SourceLocation UnavailableLoc, StrictLoc;
977 if (Tok.isNot(tok::identifier)) {
978 Diag(Tok, diag::err_availability_expected_change);
979 SkipUntil(tok::r_paren, StopAtSemi);
982 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
983 SourceLocation KeywordLoc = ConsumeToken();
985 if (Keyword == Ident_strict) {
986 if (StrictLoc.isValid()) {
987 Diag(KeywordLoc, diag::err_availability_redundant)
988 << Keyword << SourceRange(StrictLoc);
990 StrictLoc = KeywordLoc;
994 if (Keyword == Ident_unavailable) {
995 if (UnavailableLoc.isValid()) {
996 Diag(KeywordLoc, diag::err_availability_redundant)
997 << Keyword << SourceRange(UnavailableLoc);
999 UnavailableLoc = KeywordLoc;
1003 if (Keyword == Ident_deprecated && Platform->Ident &&
1004 Platform->Ident->isStr("swift")) {
1005 // For swift, we deprecate for all versions.
1006 if (Changes[Deprecated].KeywordLoc.isValid()) {
1007 Diag(KeywordLoc, diag::err_availability_redundant)
1009 << SourceRange(Changes[Deprecated].KeywordLoc);
1012 Changes[Deprecated].KeywordLoc = KeywordLoc;
1013 // Use a fake version here.
1014 Changes[Deprecated].Version = VersionTuple(1);
1018 if (Tok.isNot(tok::equal)) {
1019 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1020 SkipUntil(tok::r_paren, StopAtSemi);
1024 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1025 if (Tok.isNot(tok::string_literal)) {
1026 Diag(Tok, diag::err_expected_string_literal)
1027 << /*Source='availability attribute'*/2;
1028 SkipUntil(tok::r_paren, StopAtSemi);
1031 if (Keyword == Ident_message)
1032 MessageExpr = ParseStringLiteralExpression();
1034 ReplacementExpr = ParseStringLiteralExpression();
1035 // Also reject wide string literals.
1036 if (StringLiteral *MessageStringLiteral =
1037 cast_or_null<StringLiteral>(MessageExpr.get())) {
1038 if (MessageStringLiteral->getCharByteWidth() != 1) {
1039 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1040 diag::err_expected_string_literal)
1041 << /*Source='availability attribute'*/ 2;
1042 SkipUntil(tok::r_paren, StopAtSemi);
1046 if (Keyword == Ident_message)
1052 // Special handling of 'NA' only when applied to introduced or
1054 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1055 Tok.is(tok::identifier)) {
1056 IdentifierInfo *NA = Tok.getIdentifierInfo();
1057 if (NA->getName() == "NA") {
1059 if (Keyword == Ident_introduced)
1060 UnavailableLoc = KeywordLoc;
1065 SourceRange VersionRange;
1066 VersionTuple Version = ParseVersionTuple(VersionRange);
1068 if (Version.empty()) {
1069 SkipUntil(tok::r_paren, StopAtSemi);
1074 if (Keyword == Ident_introduced)
1076 else if (Keyword == Ident_deprecated)
1078 else if (Keyword == Ident_obsoleted)
1083 if (Index < Unknown) {
1084 if (!Changes[Index].KeywordLoc.isInvalid()) {
1085 Diag(KeywordLoc, diag::err_availability_redundant)
1087 << SourceRange(Changes[Index].KeywordLoc,
1088 Changes[Index].VersionRange.getEnd());
1091 Changes[Index].KeywordLoc = KeywordLoc;
1092 Changes[Index].Version = Version;
1093 Changes[Index].VersionRange = VersionRange;
1095 Diag(KeywordLoc, diag::err_availability_unknown_change)
1096 << Keyword << VersionRange;
1099 } while (TryConsumeToken(tok::comma));
1102 if (T.consumeClose())
1106 *endLoc = T.getCloseLocation();
1108 // The 'unavailable' availability cannot be combined with any other
1109 // availability changes. Make sure that hasn't happened.
1110 if (UnavailableLoc.isValid()) {
1111 bool Complained = false;
1112 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1113 if (Changes[Index].KeywordLoc.isValid()) {
1115 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1116 << SourceRange(Changes[Index].KeywordLoc,
1117 Changes[Index].VersionRange.getEnd());
1121 // Clear out the availability.
1122 Changes[Index] = AvailabilityChange();
1127 // Record this attribute
1128 attrs.addNew(&Availability,
1129 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1130 ScopeName, ScopeLoc,
1132 Changes[Introduced],
1133 Changes[Deprecated],
1135 UnavailableLoc, MessageExpr.get(),
1136 Syntax, StrictLoc, ReplacementExpr.get());
1139 /// Parse the contents of the "external_source_symbol" attribute.
1141 /// external-source-symbol-attribute:
1142 /// 'external_source_symbol' '(' keyword-arg-list ')'
1144 /// keyword-arg-list:
1146 /// keyword-arg ',' keyword-arg-list
1149 /// 'language' '=' <string>
1150 /// 'defined_in' '=' <string>
1151 /// 'generated_declaration'
1152 void Parser::ParseExternalSourceSymbolAttribute(
1153 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1154 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1155 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1157 BalancedDelimiterTracker T(*this, tok::l_paren);
1158 if (T.expectAndConsume())
1161 // Initialize the pointers for the keyword identifiers when required.
1162 if (!Ident_language) {
1163 Ident_language = PP.getIdentifierInfo("language");
1164 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1165 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1168 ExprResult Language;
1169 bool HasLanguage = false;
1170 ExprResult DefinedInExpr;
1171 bool HasDefinedIn = false;
1172 IdentifierLoc *GeneratedDeclaration = nullptr;
1174 // Parse the language/defined_in/generated_declaration keywords
1176 if (Tok.isNot(tok::identifier)) {
1177 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1178 SkipUntil(tok::r_paren, StopAtSemi);
1182 SourceLocation KeywordLoc = Tok.getLocation();
1183 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1184 if (Keyword == Ident_generated_declaration) {
1185 if (GeneratedDeclaration) {
1186 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1187 SkipUntil(tok::r_paren, StopAtSemi);
1190 GeneratedDeclaration = ParseIdentifierLoc();
1194 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1195 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1196 SkipUntil(tok::r_paren, StopAtSemi);
1201 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1202 Keyword->getName())) {
1203 SkipUntil(tok::r_paren, StopAtSemi);
1207 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1208 if (Keyword == Ident_language)
1211 HasDefinedIn = true;
1213 if (Tok.isNot(tok::string_literal)) {
1214 Diag(Tok, diag::err_expected_string_literal)
1215 << /*Source='external_source_symbol attribute'*/ 3
1216 << /*language | source container*/ (Keyword != Ident_language);
1217 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1220 if (Keyword == Ident_language) {
1222 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1224 ParseStringLiteralExpression();
1227 Language = ParseStringLiteralExpression();
1229 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1231 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1233 ParseStringLiteralExpression();
1236 DefinedInExpr = ParseStringLiteralExpression();
1238 } while (TryConsumeToken(tok::comma));
1241 if (T.consumeClose())
1244 *EndLoc = T.getCloseLocation();
1246 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1247 GeneratedDeclaration};
1248 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1249 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1252 /// Parse the contents of the "objc_bridge_related" attribute.
1253 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1257 /// opt-class_method:
1258 /// Identifier: | <empty>
1260 /// opt-instance_method:
1261 /// Identifier | <empty>
1263 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1264 SourceLocation ObjCBridgeRelatedLoc,
1265 ParsedAttributes &attrs,
1266 SourceLocation *endLoc,
1267 IdentifierInfo *ScopeName,
1268 SourceLocation ScopeLoc,
1269 ParsedAttr::Syntax Syntax) {
1271 BalancedDelimiterTracker T(*this, tok::l_paren);
1272 if (T.consumeOpen()) {
1273 Diag(Tok, diag::err_expected) << tok::l_paren;
1277 // Parse the related class name.
1278 if (Tok.isNot(tok::identifier)) {
1279 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1280 SkipUntil(tok::r_paren, StopAtSemi);
1283 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1284 if (ExpectAndConsume(tok::comma)) {
1285 SkipUntil(tok::r_paren, StopAtSemi);
1289 // Parse class method name. It's non-optional in the sense that a trailing
1290 // comma is required, but it can be the empty string, and then we record a
1292 IdentifierLoc *ClassMethod = nullptr;
1293 if (Tok.is(tok::identifier)) {
1294 ClassMethod = ParseIdentifierLoc();
1295 if (!TryConsumeToken(tok::colon)) {
1296 Diag(Tok, diag::err_objcbridge_related_selector_name);
1297 SkipUntil(tok::r_paren, StopAtSemi);
1301 if (!TryConsumeToken(tok::comma)) {
1302 if (Tok.is(tok::colon))
1303 Diag(Tok, diag::err_objcbridge_related_selector_name);
1305 Diag(Tok, diag::err_expected) << tok::comma;
1306 SkipUntil(tok::r_paren, StopAtSemi);
1310 // Parse instance method name. Also non-optional but empty string is
1312 IdentifierLoc *InstanceMethod = nullptr;
1313 if (Tok.is(tok::identifier))
1314 InstanceMethod = ParseIdentifierLoc();
1315 else if (Tok.isNot(tok::r_paren)) {
1316 Diag(Tok, diag::err_expected) << tok::r_paren;
1317 SkipUntil(tok::r_paren, StopAtSemi);
1322 if (T.consumeClose())
1326 *endLoc = T.getCloseLocation();
1328 // Record this attribute
1329 attrs.addNew(&ObjCBridgeRelated,
1330 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1331 ScopeName, ScopeLoc,
1338 // Late Parsed Attributes:
1339 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1341 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1343 void Parser::LateParsedClass::ParseLexedAttributes() {
1344 Self->ParseLexedAttributes(*Class);
1347 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1348 Self->ParseLexedAttribute(*this, true, false);
1351 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1352 /// scope appropriately.
1353 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1354 // Deal with templates
1355 // FIXME: Test cases to make sure this does the right thing for templates.
1356 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1357 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1359 if (HasTemplateScope)
1360 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1362 // Set or update the scope flags.
1363 bool AlreadyHasClassScope = Class.TopLevelClass;
1364 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1365 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1366 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1368 // Enter the scope of nested classes
1369 if (!AlreadyHasClassScope)
1370 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1371 Class.TagOrTemplate);
1372 if (!Class.LateParsedDeclarations.empty()) {
1373 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1374 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1378 if (!AlreadyHasClassScope)
1379 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1380 Class.TagOrTemplate);
1383 /// Parse all attributes in LAs, and attach them to Decl D.
1384 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1385 bool EnterScope, bool OnDefinition) {
1386 assert(LAs.parseSoon() &&
1387 "Attribute list should be marked for immediate parsing.");
1388 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1391 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1397 /// Finish parsing an attribute for which parsing was delayed.
1398 /// This will be called at the end of parsing a class declaration
1399 /// for each LateParsedAttribute. We consume the saved tokens and
1400 /// create an attribute with the arguments filled in. We add this
1401 /// to the Attribute list for the decl.
1402 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1403 bool EnterScope, bool OnDefinition) {
1404 // Create a fake EOF so that attribute parsing won't go off the end of the
1407 AttrEnd.startToken();
1408 AttrEnd.setKind(tok::eof);
1409 AttrEnd.setLocation(Tok.getLocation());
1410 AttrEnd.setEofData(LA.Toks.data());
1411 LA.Toks.push_back(AttrEnd);
1413 // Append the current token at the end of the new token stream so that it
1414 // doesn't get lost.
1415 LA.Toks.push_back(Tok);
1416 PP.EnterTokenStream(LA.Toks, true);
1417 // Consume the previously pushed token.
1418 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1420 ParsedAttributes Attrs(AttrFactory);
1421 SourceLocation endLoc;
1423 if (LA.Decls.size() > 0) {
1424 Decl *D = LA.Decls[0];
1425 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1426 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1428 // Allow 'this' within late-parsed attributes.
1429 Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1430 ND && ND->isCXXInstanceMember());
1432 if (LA.Decls.size() == 1) {
1433 // If the Decl is templatized, add template parameters to scope.
1434 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1435 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1436 if (HasTemplateScope)
1437 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1439 // If the Decl is on a function, add function parameters to the scope.
1440 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1442 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1445 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1447 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1448 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1452 Actions.ActOnExitFunctionContext();
1453 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1455 if (HasTemplateScope) {
1459 // If there are multiple decls, then the decl cannot be within the
1461 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1462 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1466 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1469 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1470 Attrs.begin()->isKnownToGCC())
1471 Diag(Tok, diag::warn_attribute_on_function_definition)
1474 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1475 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1477 // Due to a parsing error, we either went over the cached tokens or
1478 // there are still cached tokens left, so we skip the leftover tokens.
1479 while (Tok.isNot(tok::eof))
1482 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1486 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1487 SourceLocation AttrNameLoc,
1488 ParsedAttributes &Attrs,
1489 SourceLocation *EndLoc,
1490 IdentifierInfo *ScopeName,
1491 SourceLocation ScopeLoc,
1492 ParsedAttr::Syntax Syntax) {
1493 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1495 BalancedDelimiterTracker T(*this, tok::l_paren);
1498 if (Tok.isNot(tok::identifier)) {
1499 Diag(Tok, diag::err_expected) << tok::identifier;
1503 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1505 if (ExpectAndConsume(tok::comma)) {
1510 SourceRange MatchingCTypeRange;
1511 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1512 if (MatchingCType.isInvalid()) {
1517 bool LayoutCompatible = false;
1518 bool MustBeNull = false;
1519 while (TryConsumeToken(tok::comma)) {
1520 if (Tok.isNot(tok::identifier)) {
1521 Diag(Tok, diag::err_expected) << tok::identifier;
1525 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1526 if (Flag->isStr("layout_compatible"))
1527 LayoutCompatible = true;
1528 else if (Flag->isStr("must_be_null"))
1531 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1535 ConsumeToken(); // consume flag
1538 if (!T.consumeClose()) {
1539 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1540 ArgumentKind, MatchingCType.get(),
1541 LayoutCompatible, MustBeNull, Syntax);
1545 *EndLoc = T.getCloseLocation();
1548 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1549 /// of a C++11 attribute-specifier in a location where an attribute is not
1550 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1553 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1554 /// this doesn't appear to actually be an attribute-specifier, and the caller
1555 /// should try to parse it.
1556 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1557 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1559 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1560 case CAK_NotAttributeSpecifier:
1561 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1564 case CAK_InvalidAttributeSpecifier:
1565 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1568 case CAK_AttributeSpecifier:
1569 // Parse and discard the attributes.
1570 SourceLocation BeginLoc = ConsumeBracket();
1572 SkipUntil(tok::r_square);
1573 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1574 SourceLocation EndLoc = ConsumeBracket();
1575 Diag(BeginLoc, diag::err_attributes_not_allowed)
1576 << SourceRange(BeginLoc, EndLoc);
1579 llvm_unreachable("All cases handled above.");
1582 /// We have found the opening square brackets of a C++11
1583 /// attribute-specifier in a location where an attribute is not permitted, but
1584 /// we know where the attributes ought to be written. Parse them anyway, and
1585 /// provide a fixit moving them to the right place.
1586 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1587 SourceLocation CorrectLocation) {
1588 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1589 Tok.is(tok::kw_alignas));
1591 // Consume the attributes.
1592 SourceLocation Loc = Tok.getLocation();
1593 ParseCXX11Attributes(Attrs);
1594 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1595 // FIXME: use err_attributes_misplaced
1596 Diag(Loc, diag::err_attributes_not_allowed)
1597 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1598 << FixItHint::CreateRemoval(AttrRange);
1601 void Parser::DiagnoseProhibitedAttributes(
1602 const SourceRange &Range, const SourceLocation CorrectLocation) {
1603 if (CorrectLocation.isValid()) {
1604 CharSourceRange AttrRange(Range, true);
1605 Diag(CorrectLocation, diag::err_attributes_misplaced)
1606 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1607 << FixItHint::CreateRemoval(AttrRange);
1609 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1612 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1614 for (const ParsedAttr &AL : Attrs) {
1615 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1617 if (AL.getKind() == ParsedAttr::UnknownAttribute)
1618 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
1620 Diag(AL.getLoc(), DiagID) << AL.getName();
1626 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1627 // applies to var, not the type Foo.
1628 // As an exception to the rule, __declspec(align(...)) before the
1629 // class-key affects the type instead of the variable.
1630 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1632 // This function moves attributes that should apply to the type off DS to Attrs.
1633 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1635 Sema::TagUseKind TUK) {
1636 if (TUK == Sema::TUK_Reference)
1639 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1641 for (ParsedAttr &AL : DS.getAttributes()) {
1642 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1643 AL.isDeclspecAttribute()) ||
1644 AL.isMicrosoftAttribute())
1645 ToBeMoved.push_back(&AL);
1648 for (ParsedAttr *AL : ToBeMoved) {
1649 DS.getAttributes().remove(AL);
1654 /// ParseDeclaration - Parse a full 'declaration', which consists of
1655 /// declaration-specifiers, some number of declarators, and a semicolon.
1656 /// 'Context' should be a DeclaratorContext value. This returns the
1657 /// location of the semicolon in DeclEnd.
1659 /// declaration: [C99 6.7]
1660 /// block-declaration ->
1661 /// simple-declaration
1663 /// [C++] template-declaration
1664 /// [C++] namespace-definition
1665 /// [C++] using-directive
1666 /// [C++] using-declaration
1667 /// [C++11/C11] static_assert-declaration
1668 /// others... [FIXME]
1670 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1671 SourceLocation &DeclEnd,
1672 ParsedAttributesWithRange &attrs) {
1673 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1674 // Must temporarily exit the objective-c container scope for
1675 // parsing c none objective-c decls.
1676 ObjCDeclContextSwitch ObjCDC(*this);
1678 Decl *SingleDecl = nullptr;
1679 switch (Tok.getKind()) {
1680 case tok::kw_template:
1681 case tok::kw_export:
1682 ProhibitAttributes(attrs);
1683 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1685 case tok::kw_inline:
1686 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1687 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1688 ProhibitAttributes(attrs);
1689 SourceLocation InlineLoc = ConsumeToken();
1690 return ParseNamespace(Context, DeclEnd, InlineLoc);
1692 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1694 case tok::kw_namespace:
1695 ProhibitAttributes(attrs);
1696 return ParseNamespace(Context, DeclEnd);
1698 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1700 case tok::kw_static_assert:
1701 case tok::kw__Static_assert:
1702 ProhibitAttributes(attrs);
1703 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1706 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1709 // This routine returns a DeclGroup, if the thing we parsed only contains a
1710 // single decl, convert it now.
1711 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1714 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1715 /// declaration-specifiers init-declarator-list[opt] ';'
1716 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1717 /// init-declarator-list ';'
1718 ///[C90/C++]init-declarator-list ';' [TODO]
1719 /// [OMP] threadprivate-directive [TODO]
1721 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1722 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1724 /// If RequireSemi is false, this does not check for a ';' at the end of the
1725 /// declaration. If it is true, it checks for and eats it.
1727 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1728 /// of a simple-declaration. If we find that we are, we also parse the
1729 /// for-range-initializer, and place it here.
1730 Parser::DeclGroupPtrTy
1731 Parser::ParseSimpleDeclaration(DeclaratorContext Context,
1732 SourceLocation &DeclEnd,
1733 ParsedAttributesWithRange &Attrs,
1734 bool RequireSemi, ForRangeInit *FRI) {
1735 // Parse the common declaration-specifiers piece.
1736 ParsingDeclSpec DS(*this);
1738 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1739 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1741 // If we had a free-standing type definition with a missing semicolon, we
1742 // may get this far before the problem becomes obvious.
1743 if (DS.hasTagDefinition() &&
1744 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1747 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1748 // declaration-specifiers init-declarator-list[opt] ';'
1749 if (Tok.is(tok::semi)) {
1750 ProhibitAttributes(Attrs);
1751 DeclEnd = Tok.getLocation();
1752 if (RequireSemi) ConsumeToken();
1753 RecordDecl *AnonRecord = nullptr;
1754 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1756 DS.complete(TheDecl);
1758 Decl* decls[] = {AnonRecord, TheDecl};
1759 return Actions.BuildDeclaratorGroup(decls);
1761 return Actions.ConvertDeclToDeclGroup(TheDecl);
1764 DS.takeAttributesFrom(Attrs);
1765 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1768 /// Returns true if this might be the start of a declarator, or a common typo
1769 /// for a declarator.
1770 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1771 switch (Tok.getKind()) {
1772 case tok::annot_cxxscope:
1773 case tok::annot_template_id:
1775 case tok::code_completion:
1776 case tok::coloncolon:
1778 case tok::kw___attribute:
1779 case tok::kw_operator:
1786 return getLangOpts().CPlusPlus;
1788 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1789 return Context == DeclaratorContext::MemberContext &&
1790 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1792 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1793 return Context == DeclaratorContext::MemberContext ||
1794 getLangOpts().CPlusPlus;
1796 case tok::identifier:
1797 switch (NextToken().getKind()) {
1798 case tok::code_completion:
1799 case tok::coloncolon:
1802 case tok::equalequal: // Might be a typo for '='.
1803 case tok::kw_alignas:
1805 case tok::kw___attribute:
1817 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1818 // and in block scope it's probably a label. Inside a class definition,
1819 // this is a bit-field.
1820 return Context == DeclaratorContext::MemberContext ||
1821 (getLangOpts().CPlusPlus &&
1822 Context == DeclaratorContext::FileContext);
1824 case tok::identifier: // Possible virt-specifier.
1825 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1836 /// Skip until we reach something which seems like a sensible place to pick
1837 /// up parsing after a malformed declaration. This will sometimes stop sooner
1838 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1839 void Parser::SkipMalformedDecl() {
1841 switch (Tok.getKind()) {
1843 // Skip until matching }, then stop. We've probably skipped over
1844 // a malformed class or function definition or similar.
1846 SkipUntil(tok::r_brace);
1847 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1848 // This declaration isn't over yet. Keep skipping.
1851 TryConsumeToken(tok::semi);
1856 SkipUntil(tok::r_square);
1861 SkipUntil(tok::r_paren);
1871 case tok::kw_inline:
1872 // 'inline namespace' at the start of a line is almost certainly
1873 // a good place to pick back up parsing, except in an Objective-C
1874 // @interface context.
1875 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1876 (!ParsingInObjCContainer || CurParsedObjCImpl))
1880 case tok::kw_namespace:
1881 // 'namespace' at the start of a line is almost certainly a good
1882 // place to pick back up parsing, except in an Objective-C
1883 // @interface context.
1884 if (Tok.isAtStartOfLine() &&
1885 (!ParsingInObjCContainer || CurParsedObjCImpl))
1890 // @end is very much like } in Objective-C contexts.
1891 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1892 ParsingInObjCContainer)
1898 // - and + probably start new method declarations in Objective-C contexts.
1899 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1904 case tok::annot_module_begin:
1905 case tok::annot_module_end:
1906 case tok::annot_module_include:
1917 /// ParseDeclGroup - Having concluded that this is either a function
1918 /// definition or a group of object declarations, actually parse the
1920 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1921 DeclaratorContext Context,
1922 SourceLocation *DeclEnd,
1923 ForRangeInit *FRI) {
1924 // Parse the first declarator.
1925 ParsingDeclarator D(*this, DS, Context);
1928 // Bail out if the first declarator didn't seem well-formed.
1929 if (!D.hasName() && !D.mayOmitIdentifier()) {
1930 SkipMalformedDecl();
1934 // Save late-parsed attributes for now; they need to be parsed in the
1935 // appropriate function scope after the function Decl has been constructed.
1936 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1937 LateParsedAttrList LateParsedAttrs(true);
1938 if (D.isFunctionDeclarator()) {
1939 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1941 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1942 // attribute. If we find the keyword here, tell the user to put it
1943 // at the start instead.
1944 if (Tok.is(tok::kw__Noreturn)) {
1945 SourceLocation Loc = ConsumeToken();
1946 const char *PrevSpec;
1949 // We can offer a fixit if it's valid to mark this function as _Noreturn
1950 // and we don't have any other declarators in this declaration.
1951 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1952 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1953 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1955 Diag(Loc, diag::err_c11_noreturn_misplaced)
1956 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1957 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
1962 // Check to see if we have a function *definition* which must have a body.
1963 if (D.isFunctionDeclarator() &&
1964 // Look at the next token to make sure that this isn't a function
1965 // declaration. We have to check this because __attribute__ might be the
1966 // start of a function definition in GCC-extended K&R C.
1967 !isDeclarationAfterDeclarator()) {
1969 // Function definitions are only allowed at file scope and in C++ classes.
1970 // The C++ inline method definition case is handled elsewhere, so we only
1971 // need to handle the file scope definition case.
1972 if (Context == DeclaratorContext::FileContext) {
1973 if (isStartOfFunctionDefinition(D)) {
1974 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1975 Diag(Tok, diag::err_function_declared_typedef);
1977 // Recover by treating the 'typedef' as spurious.
1978 DS.ClearStorageClassSpecs();
1982 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1983 return Actions.ConvertDeclToDeclGroup(TheDecl);
1986 if (isDeclarationSpecifier()) {
1987 // If there is an invalid declaration specifier right after the
1988 // function prototype, then we must be in a missing semicolon case
1989 // where this isn't actually a body. Just fall through into the code
1990 // that handles it as a prototype, and let the top-level code handle
1991 // the erroneous declspec where it would otherwise expect a comma or
1994 Diag(Tok, diag::err_expected_fn_body);
1995 SkipUntil(tok::semi);
1999 if (Tok.is(tok::l_brace)) {
2000 Diag(Tok, diag::err_function_definition_not_allowed);
2001 SkipMalformedDecl();
2007 if (ParseAsmAttributesAfterDeclarator(D))
2010 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2011 // must parse and analyze the for-range-initializer before the declaration is
2014 // Handle the Objective-C for-in loop variable similarly, although we
2015 // don't need to parse the container in advance.
2016 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2017 bool IsForRangeLoop = false;
2018 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2019 IsForRangeLoop = true;
2020 if (Tok.is(tok::l_brace))
2021 FRI->RangeExpr = ParseBraceInitializer();
2023 FRI->RangeExpr = ParseExpression();
2026 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2027 if (IsForRangeLoop) {
2028 Actions.ActOnCXXForRangeDecl(ThisDecl);
2031 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2032 VD->setObjCForDecl(true);
2034 Actions.FinalizeDeclaration(ThisDecl);
2035 D.complete(ThisDecl);
2036 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2039 SmallVector<Decl *, 8> DeclsInGroup;
2040 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2041 D, ParsedTemplateInfo(), FRI);
2042 if (LateParsedAttrs.size() > 0)
2043 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2044 D.complete(FirstDecl);
2046 DeclsInGroup.push_back(FirstDecl);
2048 bool ExpectSemi = Context != DeclaratorContext::ForContext;
2050 // If we don't have a comma, it is either the end of the list (a ';') or an
2052 SourceLocation CommaLoc;
2053 while (TryConsumeToken(tok::comma, CommaLoc)) {
2054 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2055 // This comma was followed by a line-break and something which can't be
2056 // the start of a declarator. The comma was probably a typo for a
2058 Diag(CommaLoc, diag::err_expected_semi_declaration)
2059 << FixItHint::CreateReplacement(CommaLoc, ";");
2064 // Parse the next declarator.
2066 D.setCommaLoc(CommaLoc);
2068 // Accept attributes in an init-declarator. In the first declarator in a
2069 // declaration, these would be part of the declspec. In subsequent
2070 // declarators, they become part of the declarator itself, so that they
2071 // don't apply to declarators after *this* one. Examples:
2072 // short __attribute__((common)) var; -> declspec
2073 // short var __attribute__((common)); -> declarator
2074 // short x, __attribute__((common)) var; -> declarator
2075 MaybeParseGNUAttributes(D);
2077 // MSVC parses but ignores qualifiers after the comma as an extension.
2078 if (getLangOpts().MicrosoftExt)
2079 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2082 if (!D.isInvalidType()) {
2083 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2084 D.complete(ThisDecl);
2086 DeclsInGroup.push_back(ThisDecl);
2091 *DeclEnd = Tok.getLocation();
2094 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2095 ? diag::err_invalid_token_after_toplevel_declarator
2096 : diag::err_expected_semi_declaration)) {
2097 // Okay, there was no semicolon and one was expected. If we see a
2098 // declaration specifier, just assume it was missing and continue parsing.
2099 // Otherwise things are very confused and we skip to recover.
2100 if (!isDeclarationSpecifier()) {
2101 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2102 TryConsumeToken(tok::semi);
2106 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2109 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2110 /// declarator. Returns true on an error.
2111 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2112 // If a simple-asm-expr is present, parse it.
2113 if (Tok.is(tok::kw_asm)) {
2115 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2116 if (AsmLabel.isInvalid()) {
2117 SkipUntil(tok::semi, StopBeforeMatch);
2121 D.setAsmLabel(AsmLabel.get());
2125 MaybeParseGNUAttributes(D);
2129 /// Parse 'declaration' after parsing 'declaration-specifiers
2130 /// declarator'. This method parses the remainder of the declaration
2131 /// (including any attributes or initializer, among other things) and
2132 /// finalizes the declaration.
2134 /// init-declarator: [C99 6.7]
2136 /// declarator '=' initializer
2137 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2138 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2139 /// [C++] declarator initializer[opt]
2141 /// [C++] initializer:
2142 /// [C++] '=' initializer-clause
2143 /// [C++] '(' expression-list ')'
2144 /// [C++0x] '=' 'default' [TODO]
2145 /// [C++0x] '=' 'delete'
2146 /// [C++0x] braced-init-list
2148 /// According to the standard grammar, =default and =delete are function
2149 /// definitions, but that definitely doesn't fit with the parser here.
2151 Decl *Parser::ParseDeclarationAfterDeclarator(
2152 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2153 if (ParseAsmAttributesAfterDeclarator(D))
2156 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2159 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2160 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2161 // RAII type used to track whether we're inside an initializer.
2162 struct InitializerScopeRAII {
2167 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2168 : P(P), D(D), ThisDecl(ThisDecl) {
2169 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2171 if (D.getCXXScopeSpec().isSet()) {
2173 S = P.getCurScope();
2175 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2178 ~InitializerScopeRAII() { pop(); }
2180 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2182 if (D.getCXXScopeSpec().isSet())
2183 S = P.getCurScope();
2184 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2192 // Inform the current actions module that we just parsed this declarator.
2193 Decl *ThisDecl = nullptr;
2194 switch (TemplateInfo.Kind) {
2195 case ParsedTemplateInfo::NonTemplate:
2196 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2199 case ParsedTemplateInfo::Template:
2200 case ParsedTemplateInfo::ExplicitSpecialization: {
2201 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2202 *TemplateInfo.TemplateParams,
2204 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2205 // Re-direct this decl to refer to the templated decl so that we can
2207 ThisDecl = VT->getTemplatedDecl();
2210 case ParsedTemplateInfo::ExplicitInstantiation: {
2211 if (Tok.is(tok::semi)) {
2212 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2213 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2214 if (ThisRes.isInvalid()) {
2215 SkipUntil(tok::semi, StopBeforeMatch);
2218 ThisDecl = ThisRes.get();
2220 // FIXME: This check should be for a variable template instantiation only.
2222 // Check that this is a valid instantiation
2223 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2224 // If the declarator-id is not a template-id, issue a diagnostic and
2225 // recover by ignoring the 'template' keyword.
2226 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2227 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2228 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2230 SourceLocation LAngleLoc =
2231 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2232 Diag(D.getIdentifierLoc(),
2233 diag::err_explicit_instantiation_with_definition)
2234 << SourceRange(TemplateInfo.TemplateLoc)
2235 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2237 // Recover as if it were an explicit specialization.
2238 TemplateParameterLists FakedParamLists;
2239 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2240 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2241 LAngleLoc, nullptr));
2244 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2251 // Parse declarator '=' initializer.
2252 // If a '==' or '+=' is found, suggest a fixit to '='.
2253 if (isTokenEqualOrEqualTypo()) {
2254 SourceLocation EqualLoc = ConsumeToken();
2256 if (Tok.is(tok::kw_delete)) {
2257 if (D.isFunctionDeclarator())
2258 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2261 Diag(ConsumeToken(), diag::err_deleted_non_function);
2262 } else if (Tok.is(tok::kw_default)) {
2263 if (D.isFunctionDeclarator())
2264 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2267 Diag(ConsumeToken(), diag::err_default_special_members);
2269 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2271 if (Tok.is(tok::code_completion)) {
2272 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2273 Actions.FinalizeDeclaration(ThisDecl);
2278 ExprResult Init(ParseInitializer());
2280 // If this is the only decl in (possibly) range based for statement,
2281 // our best guess is that the user meant ':' instead of '='.
2282 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2283 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2284 << FixItHint::CreateReplacement(EqualLoc, ":");
2285 // We are trying to stop parser from looking for ';' in this for
2286 // statement, therefore preventing spurious errors to be issued.
2287 FRI->ColonLoc = EqualLoc;
2289 FRI->RangeExpr = Init;
2294 if (Init.isInvalid()) {
2295 SmallVector<tok::TokenKind, 2> StopTokens;
2296 StopTokens.push_back(tok::comma);
2297 if (D.getContext() == DeclaratorContext::ForContext ||
2298 D.getContext() == DeclaratorContext::InitStmtContext)
2299 StopTokens.push_back(tok::r_paren);
2300 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2301 Actions.ActOnInitializerError(ThisDecl);
2303 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2304 /*DirectInit=*/false);
2306 } else if (Tok.is(tok::l_paren)) {
2307 // Parse C++ direct initializer: '(' expression-list ')'
2308 BalancedDelimiterTracker T(*this, tok::l_paren);
2312 CommaLocsTy CommaLocs;
2314 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2316 llvm::function_ref<void()> ExprListCompleter;
2317 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2318 auto ConstructorCompleter = [&, ThisVarDecl] {
2319 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2320 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2321 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2322 CalledSignatureHelp = true;
2323 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
2326 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2327 // VarDecl. This is an error and it is reported in a call to
2328 // Actions.ActOnInitializerError(). However, we call
2329 // ProduceConstructorSignatureHelp only on VarDecls, falling back to
2330 // default completer in other cases.
2331 ExprListCompleter = ConstructorCompleter;
2334 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
2335 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2336 Actions.ProduceConstructorSignatureHelp(
2337 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2338 ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2339 CalledSignatureHelp = true;
2341 Actions.ActOnInitializerError(ThisDecl);
2342 SkipUntil(tok::r_paren, StopAtSemi);
2347 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2348 "Unexpected number of commas!");
2352 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2353 T.getCloseLocation(),
2355 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2356 /*DirectInit=*/true);
2358 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2359 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2360 // Parse C++0x braced-init-list.
2361 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2363 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2365 ExprResult Init(ParseBraceInitializer());
2369 if (Init.isInvalid()) {
2370 Actions.ActOnInitializerError(ThisDecl);
2372 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2375 Actions.ActOnUninitializedDecl(ThisDecl);
2378 Actions.FinalizeDeclaration(ThisDecl);
2383 /// ParseSpecifierQualifierList
2384 /// specifier-qualifier-list:
2385 /// type-specifier specifier-qualifier-list[opt]
2386 /// type-qualifier specifier-qualifier-list[opt]
2387 /// [GNU] attributes specifier-qualifier-list[opt]
2389 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2390 DeclSpecContext DSC) {
2391 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2392 /// parse declaration-specifiers and complain about extra stuff.
2393 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2394 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2396 // Validate declspec for type-name.
2397 unsigned Specs = DS.getParsedSpecifiers();
2398 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2399 Diag(Tok, diag::err_expected_type);
2400 DS.SetTypeSpecError();
2401 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2402 Diag(Tok, diag::err_typename_requires_specqual);
2403 if (!DS.hasTypeSpecifier())
2404 DS.SetTypeSpecError();
2407 // Issue diagnostic and remove storage class if present.
2408 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2409 if (DS.getStorageClassSpecLoc().isValid())
2410 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2412 Diag(DS.getThreadStorageClassSpecLoc(),
2413 diag::err_typename_invalid_storageclass);
2414 DS.ClearStorageClassSpecs();
2417 // Issue diagnostic and remove function specifier if present.
2418 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2419 if (DS.isInlineSpecified())
2420 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2421 if (DS.isVirtualSpecified())
2422 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2423 if (DS.isExplicitSpecified())
2424 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2425 DS.ClearFunctionSpecs();
2428 // Issue diagnostic and remove constexpr specfier if present.
2429 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
2430 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2431 DS.ClearConstexprSpec();
2435 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2436 /// specified token is valid after the identifier in a declarator which
2437 /// immediately follows the declspec. For example, these things are valid:
2439 /// int x [ 4]; // direct-declarator
2440 /// int x ( int y); // direct-declarator
2441 /// int(int x ) // direct-declarator
2442 /// int x ; // simple-declaration
2443 /// int x = 17; // init-declarator-list
2444 /// int x , y; // init-declarator-list
2445 /// int x __asm__ ("foo"); // init-declarator-list
2446 /// int x : 4; // struct-declarator
2447 /// int x { 5}; // C++'0x unified initializers
2449 /// This is not, because 'x' does not immediately follow the declspec (though
2450 /// ')' happens to be valid anyway).
2453 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2454 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2455 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2459 /// ParseImplicitInt - This method is called when we have an non-typename
2460 /// identifier in a declspec (which normally terminates the decl spec) when
2461 /// the declspec has no type specifier. In this case, the declspec is either
2462 /// malformed or is "implicit int" (in K&R and C89).
2464 /// This method handles diagnosing this prettily and returns false if the
2465 /// declspec is done being processed. If it recovers and thinks there may be
2466 /// other pieces of declspec after it, it returns true.
2468 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2469 const ParsedTemplateInfo &TemplateInfo,
2470 AccessSpecifier AS, DeclSpecContext DSC,
2471 ParsedAttributesWithRange &Attrs) {
2472 assert(Tok.is(tok::identifier) && "should have identifier");
2474 SourceLocation Loc = Tok.getLocation();
2475 // If we see an identifier that is not a type name, we normally would
2476 // parse it as the identifier being declared. However, when a typename
2477 // is typo'd or the definition is not included, this will incorrectly
2478 // parse the typename as the identifier name and fall over misparsing
2479 // later parts of the diagnostic.
2481 // As such, we try to do some look-ahead in cases where this would
2482 // otherwise be an "implicit-int" case to see if this is invalid. For
2483 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2484 // an identifier with implicit int, we'd get a parse error because the
2485 // next token is obviously invalid for a type. Parse these as a case
2486 // with an invalid type specifier.
2487 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2489 // Since we know that this either implicit int (which is rare) or an
2490 // error, do lookahead to try to do better recovery. This never applies
2491 // within a type specifier. Outside of C++, we allow this even if the
2492 // language doesn't "officially" support implicit int -- we support
2493 // implicit int as an extension in C99 and C11.
2494 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2495 isValidAfterIdentifierInDeclarator(NextToken())) {
2496 // If this token is valid for implicit int, e.g. "static x = 4", then
2497 // we just avoid eating the identifier, so it will be parsed as the
2498 // identifier in the declarator.
2502 if (getLangOpts().CPlusPlus &&
2503 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2504 // Don't require a type specifier if we have the 'auto' storage class
2505 // specifier in C++98 -- we'll promote it to a type specifier.
2507 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2511 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2512 getLangOpts().MSVCCompat) {
2513 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2514 // Give Sema a chance to recover if we are in a template with dependent base
2516 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2517 *Tok.getIdentifierInfo(), Tok.getLocation(),
2518 DSC == DeclSpecContext::DSC_template_type_arg)) {
2519 const char *PrevSpec;
2521 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2522 Actions.getASTContext().getPrintingPolicy());
2523 DS.SetRangeEnd(Tok.getLocation());
2529 // Otherwise, if we don't consume this token, we are going to emit an
2530 // error anyway. Try to recover from various common problems. Check
2531 // to see if this was a reference to a tag name without a tag specified.
2532 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2534 // C++ doesn't need this, and isTagName doesn't take SS.
2535 if (SS == nullptr) {
2536 const char *TagName = nullptr, *FixitTagName = nullptr;
2537 tok::TokenKind TagKind = tok::unknown;
2539 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2541 case DeclSpec::TST_enum:
2542 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2543 case DeclSpec::TST_union:
2544 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2545 case DeclSpec::TST_struct:
2546 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2547 case DeclSpec::TST_interface:
2548 TagName="__interface"; FixitTagName = "__interface ";
2549 TagKind=tok::kw___interface;break;
2550 case DeclSpec::TST_class:
2551 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2555 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2556 LookupResult R(Actions, TokenName, SourceLocation(),
2557 Sema::LookupOrdinaryName);
2559 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2560 << TokenName << TagName << getLangOpts().CPlusPlus
2561 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2563 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2564 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2566 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2567 << TokenName << TagName;
2570 // Parse this as a tag as if the missing tag were present.
2571 if (TagKind == tok::kw_enum)
2572 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2573 DeclSpecContext::DSC_normal);
2575 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2576 /*EnteringContext*/ false,
2577 DeclSpecContext::DSC_normal, Attrs);
2582 // Determine whether this identifier could plausibly be the name of something
2583 // being declared (with a missing type).
2584 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2585 DSC == DeclSpecContext::DSC_class)) {
2586 // Look ahead to the next token to try to figure out what this declaration
2587 // was supposed to be.
2588 switch (NextToken().getKind()) {
2589 case tok::l_paren: {
2590 // static x(4); // 'x' is not a type
2591 // x(int n); // 'x' is not a type
2592 // x (*p)[]; // 'x' is a type
2594 // Since we're in an error case, we can afford to perform a tentative
2595 // parse to determine which case we're in.
2596 TentativeParsingAction PA(*this);
2598 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2601 if (TPR != TPResult::False) {
2602 // The identifier is followed by a parenthesized declarator.
2603 // It's supposed to be a type.
2607 // If we're in a context where we could be declaring a constructor,
2608 // check whether this is a constructor declaration with a bogus name.
2609 if (DSC == DeclSpecContext::DSC_class ||
2610 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2611 IdentifierInfo *II = Tok.getIdentifierInfo();
2612 if (Actions.isCurrentClassNameTypo(II, SS)) {
2613 Diag(Loc, diag::err_constructor_bad_name)
2614 << Tok.getIdentifierInfo() << II
2615 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2616 Tok.setIdentifierInfo(II);
2628 // This looks like a variable or function declaration. The type is
2629 // probably missing. We're done parsing decl-specifiers.
2631 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2635 // This is probably supposed to be a type. This includes cases like:
2637 // struct S { unsinged : 4; };
2642 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2643 // and attempt to recover.
2645 IdentifierInfo *II = Tok.getIdentifierInfo();
2646 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2647 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2650 // The action has suggested that the type T could be used. Set that as
2651 // the type in the declaration specifiers, consume the would-be type
2652 // name token, and we're done.
2653 const char *PrevSpec;
2655 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2656 Actions.getASTContext().getPrintingPolicy());
2657 DS.SetRangeEnd(Tok.getLocation());
2659 // There may be other declaration specifiers after this.
2661 } else if (II != Tok.getIdentifierInfo()) {
2662 // If no type was suggested, the correction is to a keyword
2663 Tok.setKind(II->getTokenID());
2664 // There may be other declaration specifiers after this.
2668 // Otherwise, the action had no suggestion for us. Mark this as an error.
2669 DS.SetTypeSpecError();
2670 DS.SetRangeEnd(Tok.getLocation());
2673 // Eat any following template arguments.
2674 if (IsTemplateName) {
2675 SourceLocation LAngle, RAngle;
2676 TemplateArgList Args;
2677 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2680 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2681 // avoid rippling error messages on subsequent uses of the same type,
2682 // could be useful if #include was forgotten.
2686 /// Determine the declaration specifier context from the declarator
2689 /// \param Context the declarator context, which is one of the
2690 /// DeclaratorContext enumerator values.
2691 Parser::DeclSpecContext
2692 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2693 if (Context == DeclaratorContext::MemberContext)
2694 return DeclSpecContext::DSC_class;
2695 if (Context == DeclaratorContext::FileContext)
2696 return DeclSpecContext::DSC_top_level;
2697 if (Context == DeclaratorContext::TemplateParamContext)
2698 return DeclSpecContext::DSC_template_param;
2699 if (Context == DeclaratorContext::TemplateArgContext ||
2700 Context == DeclaratorContext::TemplateTypeArgContext)
2701 return DeclSpecContext::DSC_template_type_arg;
2702 if (Context == DeclaratorContext::TrailingReturnContext ||
2703 Context == DeclaratorContext::TrailingReturnVarContext)
2704 return DeclSpecContext::DSC_trailing;
2705 if (Context == DeclaratorContext::AliasDeclContext ||
2706 Context == DeclaratorContext::AliasTemplateContext)
2707 return DeclSpecContext::DSC_alias_declaration;
2708 return DeclSpecContext::DSC_normal;
2711 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2713 /// FIXME: Simply returns an alignof() expression if the argument is a
2714 /// type. Ideally, the type should be propagated directly into Sema.
2717 /// [C11] constant-expression
2718 /// [C++0x] type-id ...[opt]
2719 /// [C++0x] assignment-expression ...[opt]
2720 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2721 SourceLocation &EllipsisLoc) {
2723 if (isTypeIdInParens()) {
2724 SourceLocation TypeLoc = Tok.getLocation();
2725 ParsedType Ty = ParseTypeName().get();
2726 SourceRange TypeRange(Start, Tok.getLocation());
2727 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2728 Ty.getAsOpaquePtr(), TypeRange);
2730 ER = ParseConstantExpression();
2732 if (getLangOpts().CPlusPlus11)
2733 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2738 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2739 /// attribute to Attrs.
2741 /// alignment-specifier:
2742 /// [C11] '_Alignas' '(' type-id ')'
2743 /// [C11] '_Alignas' '(' constant-expression ')'
2744 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2745 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2746 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2747 SourceLocation *EndLoc) {
2748 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2749 "Not an alignment-specifier!");
2751 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2752 SourceLocation KWLoc = ConsumeToken();
2754 BalancedDelimiterTracker T(*this, tok::l_paren);
2755 if (T.expectAndConsume())
2758 SourceLocation EllipsisLoc;
2759 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2760 if (ArgExpr.isInvalid()) {
2767 *EndLoc = T.getCloseLocation();
2769 ArgsVector ArgExprs;
2770 ArgExprs.push_back(ArgExpr.get());
2771 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2772 ParsedAttr::AS_Keyword, EllipsisLoc);
2775 /// Determine whether we're looking at something that might be a declarator
2776 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2777 /// diagnose a missing semicolon after a prior tag definition in the decl
2780 /// \return \c true if an error occurred and this can't be any kind of
2783 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2784 DeclSpecContext DSContext,
2785 LateParsedAttrList *LateAttrs) {
2786 assert(DS.hasTagDefinition() && "shouldn't call this");
2788 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2789 DSContext == DeclSpecContext::DSC_top_level);
2791 if (getLangOpts().CPlusPlus &&
2792 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2793 tok::annot_template_id) &&
2794 TryAnnotateCXXScopeToken(EnteringContext)) {
2795 SkipMalformedDecl();
2799 bool HasScope = Tok.is(tok::annot_cxxscope);
2800 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2801 Token AfterScope = HasScope ? NextToken() : Tok;
2803 // Determine whether the following tokens could possibly be a
2805 bool MightBeDeclarator = true;
2806 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2807 // A declarator-id can't start with 'typename'.
2808 MightBeDeclarator = false;
2809 } else if (AfterScope.is(tok::annot_template_id)) {
2810 // If we have a type expressed as a template-id, this cannot be a
2811 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2812 TemplateIdAnnotation *Annot =
2813 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2814 if (Annot->Kind == TNK_Type_template)
2815 MightBeDeclarator = false;
2816 } else if (AfterScope.is(tok::identifier)) {
2817 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2819 // These tokens cannot come after the declarator-id in a
2820 // simple-declaration, and are likely to come after a type-specifier.
2821 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2822 tok::annot_cxxscope, tok::coloncolon)) {
2823 // Missing a semicolon.
2824 MightBeDeclarator = false;
2825 } else if (HasScope) {
2826 // If the declarator-id has a scope specifier, it must redeclare a
2827 // previously-declared entity. If that's a type (and this is not a
2828 // typedef), that's an error.
2830 Actions.RestoreNestedNameSpecifierAnnotation(
2831 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2832 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2833 Sema::NameClassification Classification = Actions.ClassifyName(
2834 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2835 /*IsAddressOfOperand*/false);
2836 switch (Classification.getKind()) {
2837 case Sema::NC_Error:
2838 SkipMalformedDecl();
2841 case Sema::NC_Keyword:
2842 case Sema::NC_NestedNameSpecifier:
2843 llvm_unreachable("typo correction and nested name specifiers not "
2847 case Sema::NC_TypeTemplate:
2848 // Not a previously-declared non-type entity.
2849 MightBeDeclarator = false;
2852 case Sema::NC_Unknown:
2853 case Sema::NC_Expression:
2854 case Sema::NC_VarTemplate:
2855 case Sema::NC_FunctionTemplate:
2856 // Might be a redeclaration of a prior entity.
2862 if (MightBeDeclarator)
2865 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2866 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2867 diag::err_expected_after)
2868 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2870 // Try to recover from the typo, by dropping the tag definition and parsing
2871 // the problematic tokens as a type.
2873 // FIXME: Split the DeclSpec into pieces for the standalone
2874 // declaration and pieces for the following declaration, instead
2875 // of assuming that all the other pieces attach to new declaration,
2876 // and call ParsedFreeStandingDeclSpec as appropriate.
2877 DS.ClearTypeSpecType();
2878 ParsedTemplateInfo NotATemplate;
2879 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2883 // Choose the apprpriate diagnostic error for why fixed point types are
2884 // disabled, set the previous specifier, and mark as invalid.
2885 static void SetupFixedPointError(const LangOptions &LangOpts,
2886 const char *&PrevSpec, unsigned &DiagID,
2888 assert(!LangOpts.FixedPoint);
2889 DiagID = diag::err_fixed_point_not_enabled;
2890 PrevSpec = ""; // Not used by diagnostic
2894 /// ParseDeclarationSpecifiers
2895 /// declaration-specifiers: [C99 6.7]
2896 /// storage-class-specifier declaration-specifiers[opt]
2897 /// type-specifier declaration-specifiers[opt]
2898 /// [C99] function-specifier declaration-specifiers[opt]
2899 /// [C11] alignment-specifier declaration-specifiers[opt]
2900 /// [GNU] attributes declaration-specifiers[opt]
2901 /// [Clang] '__module_private__' declaration-specifiers[opt]
2902 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2904 /// storage-class-specifier: [C99 6.7.1]
2911 /// [C++11] 'thread_local'
2912 /// [C11] '_Thread_local'
2913 /// [GNU] '__thread'
2914 /// function-specifier: [C99 6.7.4]
2917 /// [C++] 'explicit'
2918 /// [OpenCL] '__kernel'
2919 /// 'friend': [C++ dcl.friend]
2920 /// 'constexpr': [C++0x dcl.constexpr]
2921 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2922 const ParsedTemplateInfo &TemplateInfo,
2924 DeclSpecContext DSContext,
2925 LateParsedAttrList *LateAttrs) {
2926 if (DS.getSourceRange().isInvalid()) {
2927 // Start the range at the current token but make the end of the range
2928 // invalid. This will make the entire range invalid unless we successfully
2930 DS.SetRangeStart(Tok.getLocation());
2931 DS.SetRangeEnd(SourceLocation());
2934 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2935 DSContext == DeclSpecContext::DSC_top_level);
2936 bool AttrsLastTime = false;
2937 ParsedAttributesWithRange attrs(AttrFactory);
2938 // We use Sema's policy to get bool macros right.
2939 PrintingPolicy Policy = Actions.getPrintingPolicy();
2941 bool isInvalid = false;
2942 bool isStorageClass = false;
2943 const char *PrevSpec = nullptr;
2944 unsigned DiagID = 0;
2946 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2947 // implementation for VS2013 uses _Atomic as an identifier for one of the
2948 // classes in <atomic>.
2950 // A typedef declaration containing _Atomic<...> is among the places where
2951 // the class is used. If we are currently parsing such a declaration, treat
2952 // the token as an identifier.
2953 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2954 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2955 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2956 Tok.setKind(tok::identifier);
2958 SourceLocation Loc = Tok.getLocation();
2960 switch (Tok.getKind()) {
2964 ProhibitAttributes(attrs);
2966 // Reject C++11 attributes that appertain to decl specifiers as
2967 // we don't support any C++11 attributes that appertain to decl
2968 // specifiers. This also conforms to what g++ 4.8 is doing.
2969 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2971 DS.takeAttributesFrom(attrs);
2974 // If this is not a declaration specifier token, we're done reading decl
2975 // specifiers. First verify that DeclSpec's are consistent.
2976 DS.Finish(Actions, Policy);
2980 case tok::kw_alignas:
2981 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
2982 goto DoneWithDeclSpec;
2984 ProhibitAttributes(attrs);
2985 // FIXME: It would be good to recover by accepting the attributes,
2986 // but attempting to do that now would cause serious
2987 // madness in terms of diagnostics.
2989 attrs.Range = SourceRange();
2991 ParseCXX11Attributes(attrs);
2992 AttrsLastTime = true;
2995 case tok::code_completion: {
2996 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2997 if (DS.hasTypeSpecifier()) {
2998 bool AllowNonIdentifiers
2999 = (getCurScope()->getFlags() & (Scope::ControlScope |
3001 Scope::TemplateParamScope |
3002 Scope::FunctionPrototypeScope |
3003 Scope::AtCatchScope)) == 0;
3004 bool AllowNestedNameSpecifiers
3005 = DSContext == DeclSpecContext::DSC_top_level ||
3006 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3008 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3009 AllowNonIdentifiers,
3010 AllowNestedNameSpecifiers);
3011 return cutOffParsing();
3014 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3015 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3016 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3017 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3018 : Sema::PCC_Template;
3019 else if (DSContext == DeclSpecContext::DSC_class)
3020 CCC = Sema::PCC_Class;
3021 else if (CurParsedObjCImpl)
3022 CCC = Sema::PCC_ObjCImplementation;
3024 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3025 return cutOffParsing();
3028 case tok::coloncolon: // ::foo::bar
3029 // C++ scope specifier. Annotate and loop, or bail out on error.
3030 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3031 if (!DS.hasTypeSpecifier())
3032 DS.SetTypeSpecError();
3033 goto DoneWithDeclSpec;
3035 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3036 goto DoneWithDeclSpec;
3039 case tok::annot_cxxscope: {
3040 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3041 goto DoneWithDeclSpec;
3044 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3045 Tok.getAnnotationRange(),
3048 // We are looking for a qualified typename.
3049 Token Next = NextToken();
3050 if (Next.is(tok::annot_template_id) &&
3051 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3052 ->Kind == TNK_Type_template) {
3053 // We have a qualified template-id, e.g., N::A<int>
3055 // If this would be a valid constructor declaration with template
3056 // arguments, we will reject the attempt to form an invalid type-id
3057 // referring to the injected-class-name when we annotate the token,
3058 // per C++ [class.qual]p2.
3060 // To improve diagnostics for this case, parse the declaration as a
3061 // constructor (and reject the extra template arguments later).
3062 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3063 if ((DSContext == DeclSpecContext::DSC_top_level ||
3064 DSContext == DeclSpecContext::DSC_class) &&
3066 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3067 isConstructorDeclarator(/*Unqualified*/ false)) {
3068 // The user meant this to be an out-of-line constructor
3069 // definition, but template arguments are not allowed
3070 // there. Just allow this as a constructor; we'll
3071 // complain about it later.
3072 goto DoneWithDeclSpec;
3075 DS.getTypeSpecScope() = SS;
3076 ConsumeAnnotationToken(); // The C++ scope.
3077 assert(Tok.is(tok::annot_template_id) &&
3078 "ParseOptionalCXXScopeSpecifier not working");
3079 AnnotateTemplateIdTokenAsType();
3083 if (Next.is(tok::annot_typename)) {
3084 DS.getTypeSpecScope() = SS;
3085 ConsumeAnnotationToken(); // The C++ scope.
3086 if (Tok.getAnnotationValue()) {
3087 ParsedType T = getTypeAnnotation(Tok);
3088 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3089 Tok.getAnnotationEndLoc(),
3090 PrevSpec, DiagID, T, Policy);
3095 DS.SetTypeSpecError();
3096 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3097 ConsumeAnnotationToken(); // The typename
3100 if (Next.isNot(tok::identifier))
3101 goto DoneWithDeclSpec;
3103 // Check whether this is a constructor declaration. If we're in a
3104 // context where the identifier could be a class name, and it has the
3105 // shape of a constructor declaration, process it as one.
3106 if ((DSContext == DeclSpecContext::DSC_top_level ||
3107 DSContext == DeclSpecContext::DSC_class) &&
3108 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3110 isConstructorDeclarator(/*Unqualified*/ false))
3111 goto DoneWithDeclSpec;
3113 ParsedType TypeRep =
3114 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3115 getCurScope(), &SS, false, false, nullptr,
3116 /*IsCtorOrDtorName=*/false,
3117 /*WantNonTrivialSourceInfo=*/true,
3118 isClassTemplateDeductionContext(DSContext));
3120 // If the referenced identifier is not a type, then this declspec is
3121 // erroneous: We already checked about that it has no type specifier, and
3122 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3125 // Eat the scope spec so the identifier is current.
3126 ConsumeAnnotationToken();
3127 ParsedAttributesWithRange Attrs(AttrFactory);
3128 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3129 if (!Attrs.empty()) {
3130 AttrsLastTime = true;
3131 attrs.takeAllFrom(Attrs);
3135 goto DoneWithDeclSpec;
3138 DS.getTypeSpecScope() = SS;
3139 ConsumeAnnotationToken(); // The C++ scope.
3141 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3142 DiagID, TypeRep, Policy);
3146 DS.SetRangeEnd(Tok.getLocation());
3147 ConsumeToken(); // The typename.
3152 case tok::annot_typename: {
3153 // If we've previously seen a tag definition, we were almost surely
3154 // missing a semicolon after it.
3155 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3156 goto DoneWithDeclSpec;
3158 if (Tok.getAnnotationValue()) {
3159 ParsedType T = getTypeAnnotation(Tok);
3160 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3163 DS.SetTypeSpecError();
3168 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3169 ConsumeAnnotationToken(); // The typename
3174 case tok::kw___is_signed:
3175 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3176 // typically treats it as a trait. If we see __is_signed as it appears
3177 // in libstdc++, e.g.,
3179 // static const bool __is_signed;
3181 // then treat __is_signed as an identifier rather than as a keyword.
3182 if (DS.getTypeSpecType() == TST_bool &&
3183 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3184 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3185 TryKeywordIdentFallback(true);
3187 // We're done with the declaration-specifiers.
3188 goto DoneWithDeclSpec;
3191 case tok::kw___super:
3192 case tok::kw_decltype:
3193 case tok::identifier: {
3194 // This identifier can only be a typedef name if we haven't already seen
3195 // a type-specifier. Without this check we misparse:
3196 // typedef int X; struct Y { short X; }; as 'short int'.
3197 if (DS.hasTypeSpecifier())
3198 goto DoneWithDeclSpec;
3200 // If the token is an identifier named "__declspec" and Microsoft
3201 // extensions are not enabled, it is likely that there will be cascading
3202 // parse errors if this really is a __declspec attribute. Attempt to
3203 // recognize that scenario and recover gracefully.
3204 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3205 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3206 Diag(Loc, diag::err_ms_attributes_not_enabled);
3208 // The next token should be an open paren. If it is, eat the entire
3209 // attribute declaration and continue.
3210 if (NextToken().is(tok::l_paren)) {
3211 // Consume the __declspec identifier.
3214 // Eat the parens and everything between them.
3215 BalancedDelimiterTracker T(*this, tok::l_paren);
3216 if (T.consumeOpen()) {
3217 assert(false && "Not a left paren?");
3225 // In C++, check to see if this is a scope specifier like foo::bar::, if
3226 // so handle it as such. This is important for ctor parsing.
3227 if (getLangOpts().CPlusPlus) {
3228 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3229 DS.SetTypeSpecError();
3230 goto DoneWithDeclSpec;
3232 if (!Tok.is(tok::identifier))
3236 // Check for need to substitute AltiVec keyword tokens.
3237 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3240 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3241 // allow the use of a typedef name as a type specifier.
3242 if (DS.isTypeAltiVecVector())
3243 goto DoneWithDeclSpec;
3245 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3246 isObjCInstancetype()) {
3247 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3249 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3250 DiagID, TypeRep, Policy);
3254 DS.SetRangeEnd(Loc);
3259 // If we're in a context where the identifier could be a class name,
3260 // check whether this is a constructor declaration.
3261 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3262 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3263 isConstructorDeclarator(/*Unqualified*/true))
3264 goto DoneWithDeclSpec;
3266 ParsedType TypeRep = Actions.getTypeName(
3267 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3268 false, false, nullptr, false, false,
3269 isClassTemplateDeductionContext(DSContext));
3271 // If this is not a typedef name, don't parse it as part of the declspec,
3272 // it must be an implicit int or an error.
3274 ParsedAttributesWithRange Attrs(AttrFactory);
3275 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3276 if (!Attrs.empty()) {
3277 AttrsLastTime = true;
3278 attrs.takeAllFrom(Attrs);
3282 goto DoneWithDeclSpec;
3285 // Likewise, if this is a context where the identifier could be a template
3286 // name, check whether this is a deduction guide declaration.
3287 if (getLangOpts().CPlusPlus17 &&
3288 (DSContext == DeclSpecContext::DSC_class ||
3289 DSContext == DeclSpecContext::DSC_top_level) &&
3290 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3291 Tok.getLocation()) &&
3292 isConstructorDeclarator(/*Unqualified*/ true,
3293 /*DeductionGuide*/ true))
3294 goto DoneWithDeclSpec;
3296 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3297 DiagID, TypeRep, Policy);
3301 DS.SetRangeEnd(Tok.getLocation());
3302 ConsumeToken(); // The identifier
3304 // Objective-C supports type arguments and protocol references
3305 // following an Objective-C object or object pointer
3306 // type. Handle either one of them.
3307 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3308 SourceLocation NewEndLoc;
3309 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3310 Loc, TypeRep, /*consumeLastToken=*/true,
3312 if (NewTypeRep.isUsable()) {
3313 DS.UpdateTypeRep(NewTypeRep.get());
3314 DS.SetRangeEnd(NewEndLoc);
3318 // Need to support trailing type qualifiers (e.g. "id<p> const").
3319 // If a type specifier follows, it will be diagnosed elsewhere.
3324 case tok::annot_template_id: {
3325 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3326 if (TemplateId->Kind != TNK_Type_template) {
3327 // This template-id does not refer to a type name, so we're
3328 // done with the type-specifiers.
3329 goto DoneWithDeclSpec;
3332 // If we're in a context where the template-id could be a
3333 // constructor name or specialization, check whether this is a
3334 // constructor declaration.
3335 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3336 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3337 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3338 goto DoneWithDeclSpec;
3340 // Turn the template-id annotation token into a type annotation
3341 // token, then try again to parse it as a type-specifier.
3342 AnnotateTemplateIdTokenAsType();
3346 // GNU attributes support.
3347 case tok::kw___attribute:
3348 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3351 // Microsoft declspec support.
3352 case tok::kw___declspec:
3353 ParseMicrosoftDeclSpecs(DS.getAttributes());
3356 // Microsoft single token adornments.
3357 case tok::kw___forceinline: {
3358 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3359 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3360 SourceLocation AttrNameLoc = Tok.getLocation();
3361 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3362 nullptr, 0, ParsedAttr::AS_Keyword);
3366 case tok::kw___unaligned:
3367 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3371 case tok::kw___sptr:
3372 case tok::kw___uptr:
3373 case tok::kw___ptr64:
3374 case tok::kw___ptr32:
3376 case tok::kw___cdecl:
3377 case tok::kw___stdcall:
3378 case tok::kw___fastcall:
3379 case tok::kw___thiscall:
3380 case tok::kw___regcall:
3381 case tok::kw___vectorcall:
3382 ParseMicrosoftTypeAttributes(DS.getAttributes());
3385 // Borland single token adornments.
3386 case tok::kw___pascal:
3387 ParseBorlandTypeAttributes(DS.getAttributes());
3390 // OpenCL single token adornments.
3391 case tok::kw___kernel:
3392 ParseOpenCLKernelAttributes(DS.getAttributes());
3395 // Nullability type specifiers.
3396 case tok::kw__Nonnull:
3397 case tok::kw__Nullable:
3398 case tok::kw__Null_unspecified:
3399 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3402 // Objective-C 'kindof' types.
3403 case tok::kw___kindof:
3404 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3405 nullptr, 0, ParsedAttr::AS_Keyword);
3406 (void)ConsumeToken();
3409 // storage-class-specifier
3410 case tok::kw_typedef:
3411 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3412 PrevSpec, DiagID, Policy);
3413 isStorageClass = true;
3415 case tok::kw_extern:
3416 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3417 Diag(Tok, diag::ext_thread_before) << "extern";
3418 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3419 PrevSpec, DiagID, Policy);
3420 isStorageClass = true;
3422 case tok::kw___private_extern__:
3423 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3424 Loc, PrevSpec, DiagID, Policy);
3425 isStorageClass = true;
3427 case tok::kw_static:
3428 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3429 Diag(Tok, diag::ext_thread_before) << "static";
3430 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3431 PrevSpec, DiagID, Policy);
3432 isStorageClass = true;
3435 if (getLangOpts().CPlusPlus11) {
3436 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3437 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3438 PrevSpec, DiagID, Policy);
3440 Diag(Tok, diag::ext_auto_storage_class)
3441 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3443 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3446 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3447 PrevSpec, DiagID, Policy);
3448 isStorageClass = true;
3450 case tok::kw___auto_type:
3451 Diag(Tok, diag::ext_auto_type);
3452 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3455 case tok::kw_register:
3456 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3457 PrevSpec, DiagID, Policy);
3458 isStorageClass = true;
3460 case tok::kw_mutable:
3461 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3462 PrevSpec, DiagID, Policy);
3463 isStorageClass = true;
3465 case tok::kw___thread:
3466 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3468 isStorageClass = true;
3470 case tok::kw_thread_local:
3471 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3473 isStorageClass = true;
3475 case tok::kw__Thread_local:
3476 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3477 Loc, PrevSpec, DiagID);
3478 isStorageClass = true;
3481 // function-specifier
3482 case tok::kw_inline:
3483 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3485 case tok::kw_virtual:
3486 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3487 if (getLangOpts().OpenCLCPlusPlus) {
3488 DiagID = diag::err_openclcxx_virtual_function;
3489 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3493 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3496 case tok::kw_explicit:
3497 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3499 case tok::kw__Noreturn:
3500 if (!getLangOpts().C11)
3501 Diag(Loc, diag::ext_c11_noreturn);
3502 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3505 // alignment-specifier
3506 case tok::kw__Alignas:
3507 if (!getLangOpts().C11)
3508 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3509 ParseAlignmentSpecifier(DS.getAttributes());
3513 case tok::kw_friend:
3514 if (DSContext == DeclSpecContext::DSC_class)
3515 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3517 PrevSpec = ""; // not actually used by the diagnostic
3518 DiagID = diag::err_friend_invalid_in_context;
3524 case tok::kw___module_private__:
3525 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3529 case tok::kw_constexpr:
3530 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3535 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3539 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3540 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3543 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3546 case tok::kw___int64:
3547 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3550 case tok::kw_signed:
3551 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3554 case tok::kw_unsigned:
3555 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3558 case tok::kw__Complex:
3559 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3562 case tok::kw__Imaginary:
3563 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3567 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3571 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3575 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3578 case tok::kw___int128:
3579 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3583 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3587 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3590 case tok::kw_double:
3591 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3594 case tok::kw__Float16:
3595 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3598 case tok::kw__Accum:
3599 if (!getLangOpts().FixedPoint) {
3600 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3602 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3606 case tok::kw__Fract:
3607 if (!getLangOpts().FixedPoint) {
3608 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3610 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3615 if (!getLangOpts().FixedPoint) {
3616 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3618 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3621 case tok::kw___float128:
3622 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3625 case tok::kw_wchar_t:
3626 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3629 case tok::kw_char8_t:
3630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3633 case tok::kw_char16_t:
3634 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3637 case tok::kw_char32_t:
3638 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3643 if (Tok.is(tok::kw_bool) &&
3644 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3645 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3646 PrevSpec = ""; // Not used by the diagnostic.
3647 DiagID = diag::err_bool_redeclaration;
3648 // For better error recovery.
3649 Tok.setKind(tok::identifier);
3652 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3656 case tok::kw__Decimal32:
3657 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3660 case tok::kw__Decimal64:
3661 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3664 case tok::kw__Decimal128:
3665 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3668 case tok::kw___vector:
3669 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3671 case tok::kw___pixel:
3672 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3674 case tok::kw___bool:
3675 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3678 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3679 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3680 // support the "pipe" word as identifier.
3681 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3682 goto DoneWithDeclSpec;
3684 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3686 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3687 case tok::kw_##ImgType##_t: \
3688 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3691 #include "clang/Basic/OpenCLImageTypes.def"
3692 case tok::kw___unknown_anytype:
3693 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3694 PrevSpec, DiagID, Policy);
3699 case tok::kw_struct:
3700 case tok::kw___interface:
3701 case tok::kw_union: {
3702 tok::TokenKind Kind = Tok.getKind();
3705 // These are attributes following class specifiers.
3706 // To produce better diagnostic, we parse them when
3707 // parsing class specifier.
3708 ParsedAttributesWithRange Attributes(AttrFactory);
3709 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3710 EnteringContext, DSContext, Attributes);
3712 // If there are attributes following class specifier,
3713 // take them over and handle them here.
3714 if (!Attributes.empty()) {
3715 AttrsLastTime = true;
3716 attrs.takeAllFrom(Attributes);
3724 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3729 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3732 case tok::kw_volatile:
3733 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3736 case tok::kw_restrict:
3737 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3741 // C++ typename-specifier:
3742 case tok::kw_typename:
3743 if (TryAnnotateTypeOrScopeToken()) {
3744 DS.SetTypeSpecError();
3745 goto DoneWithDeclSpec;
3747 if (!Tok.is(tok::kw_typename))
3751 // GNU typeof support.
3752 case tok::kw_typeof:
3753 ParseTypeofSpecifier(DS);
3756 case tok::annot_decltype:
3757 ParseDecltypeSpecifier(DS);
3760 case tok::annot_pragma_pack:
3764 case tok::annot_pragma_ms_pragma:
3765 HandlePragmaMSPragma();
3768 case tok::annot_pragma_ms_vtordisp:
3769 HandlePragmaMSVtorDisp();
3772 case tok::annot_pragma_ms_pointers_to_members:
3773 HandlePragmaMSPointersToMembers();
3776 case tok::kw___underlying_type:
3777 ParseUnderlyingTypeSpecifier(DS);
3780 case tok::kw__Atomic:
3782 // If the _Atomic keyword is immediately followed by a left parenthesis,
3783 // it is interpreted as a type specifier (with a type name), not as a
3785 if (NextToken().is(tok::l_paren)) {
3786 ParseAtomicSpecifier(DS);
3789 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3793 // OpenCL access qualifiers:
3794 case tok::kw___read_only:
3795 case tok::kw___write_only:
3796 case tok::kw___read_write:
3797 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3798 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3799 DiagID = diag::err_openclcxx_reserved;
3800 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3803 ParseOpenCLQualifiers(DS.getAttributes());
3806 // OpenCL address space qualifiers:
3807 case tok::kw___generic:
3808 // generic address space is introduced only in OpenCL v2.0
3809 // see OpenCL C Spec v2.0 s6.5.5
3810 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3811 !Actions.getLangOpts().OpenCLCPlusPlus) {
3812 DiagID = diag::err_opencl_unknown_type_specifier;
3813 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3818 case tok::kw___private:
3819 case tok::kw___global:
3820 case tok::kw___local:
3821 case tok::kw___constant:
3822 ParseOpenCLQualifiers(DS.getAttributes());
3826 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3827 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3828 // but we support it.
3829 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
3830 goto DoneWithDeclSpec;
3832 SourceLocation StartLoc = Tok.getLocation();
3833 SourceLocation EndLoc;
3834 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3835 if (Type.isUsable()) {
3836 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3837 PrevSpec, DiagID, Type.get(),
3838 Actions.getASTContext().getPrintingPolicy()))
3839 Diag(StartLoc, DiagID) << PrevSpec;
3841 DS.SetRangeEnd(EndLoc);
3843 DS.SetTypeSpecError();
3846 // Need to support trailing type qualifiers (e.g. "id<p> const").
3847 // If a type specifier follows, it will be diagnosed elsewhere.
3850 // If the specifier wasn't legal, issue a diagnostic.
3852 assert(PrevSpec && "Method did not return previous specifier!");
3855 if (DiagID == diag::ext_duplicate_declspec ||
3856 DiagID == diag::ext_warn_duplicate_declspec)
3858 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3859 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3860 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3861 << getLangOpts().getOpenCLVersionTuple().getAsString()
3862 << PrevSpec << isStorageClass;
3864 Diag(Tok, DiagID) << PrevSpec;
3867 DS.SetRangeEnd(Tok.getLocation());
3868 if (DiagID != diag::err_bool_redeclaration)
3869 // After an error the next token can be an annotation token.
3872 AttrsLastTime = false;
3876 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3879 /// struct-declaration:
3880 /// [C2x] attributes-specifier-seq[opt]
3881 /// specifier-qualifier-list struct-declarator-list
3882 /// [GNU] __extension__ struct-declaration
3883 /// [GNU] specifier-qualifier-list
3884 /// struct-declarator-list:
3885 /// struct-declarator
3886 /// struct-declarator-list ',' struct-declarator
3887 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3888 /// struct-declarator:
3890 /// [GNU] declarator attributes[opt]
3891 /// declarator[opt] ':' constant-expression
3892 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3894 void Parser::ParseStructDeclaration(
3895 ParsingDeclSpec &DS,
3896 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3898 if (Tok.is(tok::kw___extension__)) {
3899 // __extension__ silences extension warnings in the subexpression.
3900 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3902 return ParseStructDeclaration(DS, FieldsCallback);
3905 // Parse leading attributes.
3906 ParsedAttributesWithRange Attrs(AttrFactory);
3907 MaybeParseCXX11Attributes(Attrs);
3908 DS.takeAttributesFrom(Attrs);
3910 // Parse the common specifier-qualifiers-list piece.
3911 ParseSpecifierQualifierList(DS);
3913 // If there are no declarators, this is a free-standing declaration
3914 // specifier. Let the actions module cope with it.
3915 if (Tok.is(tok::semi)) {
3916 RecordDecl *AnonRecord = nullptr;
3917 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3919 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3920 DS.complete(TheDecl);
3924 // Read struct-declarators until we find the semicolon.
3925 bool FirstDeclarator = true;
3926 SourceLocation CommaLoc;
3928 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3929 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3931 // Attributes are only allowed here on successive declarators.
3932 if (!FirstDeclarator)
3933 MaybeParseGNUAttributes(DeclaratorInfo.D);
3935 /// struct-declarator: declarator
3936 /// struct-declarator: declarator[opt] ':' constant-expression
3937 if (Tok.isNot(tok::colon)) {
3938 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3939 ColonProtectionRAIIObject X(*this);
3940 ParseDeclarator(DeclaratorInfo.D);
3942 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3944 if (TryConsumeToken(tok::colon)) {
3945 ExprResult Res(ParseConstantExpression());
3946 if (Res.isInvalid())
3947 SkipUntil(tok::semi, StopBeforeMatch);
3949 DeclaratorInfo.BitfieldSize = Res.get();
3952 // If attributes exist after the declarator, parse them.
3953 MaybeParseGNUAttributes(DeclaratorInfo.D);
3955 // We're done with this declarator; invoke the callback.
3956 FieldsCallback(DeclaratorInfo);
3958 // If we don't have a comma, it is either the end of the list (a ';')
3959 // or an error, bail out.
3960 if (!TryConsumeToken(tok::comma, CommaLoc))
3963 FirstDeclarator = false;
3967 /// ParseStructUnionBody
3968 /// struct-contents:
3969 /// struct-declaration-list
3971 /// [GNU] "struct-declaration-list" without terminatoring ';'
3972 /// struct-declaration-list:
3973 /// struct-declaration
3974 /// struct-declaration-list struct-declaration
3975 /// [OBC] '@' 'defs' '(' class-name ')'
3977 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3978 unsigned TagType, Decl *TagDecl) {
3979 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3980 "parsing struct/union body");
3981 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3983 BalancedDelimiterTracker T(*this, tok::l_brace);
3984 if (T.consumeOpen())
3987 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3988 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3990 SmallVector<Decl *, 32> FieldDecls;
3992 // While we still have something to read, read the declarations in the struct.
3993 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3994 Tok.isNot(tok::eof)) {
3995 // Each iteration of this loop reads one struct-declaration.
3997 // Check for extraneous top-level semicolon.
3998 if (Tok.is(tok::semi)) {
3999 ConsumeExtraSemi(InsideStruct, TagType);
4003 // Parse _Static_assert declaration.
4004 if (Tok.is(tok::kw__Static_assert)) {
4005 SourceLocation DeclEnd;
4006 ParseStaticAssertDeclaration(DeclEnd);
4010 if (Tok.is(tok::annot_pragma_pack)) {
4015 if (Tok.is(tok::annot_pragma_align)) {
4016 HandlePragmaAlign();
4020 if (Tok.is(tok::annot_pragma_openmp)) {
4021 // Result can be ignored, because it must be always empty.
4022 AccessSpecifier AS = AS_none;
4023 ParsedAttributesWithRange Attrs(AttrFactory);
4024 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4028 if (!Tok.is(tok::at)) {
4029 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4030 // Install the declarator into the current TagDecl.
4032 Actions.ActOnField(getCurScope(), TagDecl,
4033 FD.D.getDeclSpec().getSourceRange().getBegin(),
4034 FD.D, FD.BitfieldSize);
4035 FieldDecls.push_back(Field);
4039 // Parse all the comma separated declarators.
4040 ParsingDeclSpec DS(*this);
4041 ParseStructDeclaration(DS, CFieldCallback);
4042 } else { // Handle @defs
4044 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4045 Diag(Tok, diag::err_unexpected_at);
4046 SkipUntil(tok::semi);
4050 ExpectAndConsume(tok::l_paren);
4051 if (!Tok.is(tok::identifier)) {
4052 Diag(Tok, diag::err_expected) << tok::identifier;
4053 SkipUntil(tok::semi);
4056 SmallVector<Decl *, 16> Fields;
4057 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4058 Tok.getIdentifierInfo(), Fields);
4059 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4061 ExpectAndConsume(tok::r_paren);
4064 if (TryConsumeToken(tok::semi))
4067 if (Tok.is(tok::r_brace)) {
4068 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4072 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4073 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4074 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4075 // If we stopped at a ';', eat it.
4076 TryConsumeToken(tok::semi);
4081 ParsedAttributes attrs(AttrFactory);
4082 // If attributes exist after struct contents, parse them.
4083 MaybeParseGNUAttributes(attrs);
4085 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4086 T.getOpenLocation(), T.getCloseLocation(), attrs);
4088 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4091 /// ParseEnumSpecifier
4092 /// enum-specifier: [C99 6.7.2.2]
4093 /// 'enum' identifier[opt] '{' enumerator-list '}'
4094 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4095 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4096 /// '}' attributes[opt]
4097 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4099 /// 'enum' identifier
4100 /// [GNU] 'enum' attributes[opt] identifier
4102 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4103 /// [C++11] enum-head '{' enumerator-list ',' '}'
4105 /// enum-head: [C++11]
4106 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4107 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4108 /// identifier enum-base[opt]
4110 /// enum-key: [C++11]
4115 /// enum-base: [C++11]
4116 /// ':' type-specifier-seq
4118 /// [C++] elaborated-type-specifier:
4119 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4121 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4122 const ParsedTemplateInfo &TemplateInfo,
4123 AccessSpecifier AS, DeclSpecContext DSC) {
4124 // Parse the tag portion of this.
4125 if (Tok.is(tok::code_completion)) {
4126 // Code completion for an enum name.
4127 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4128 return cutOffParsing();
4131 // If attributes exist after tag, parse them.
4132 ParsedAttributesWithRange attrs(AttrFactory);
4133 MaybeParseGNUAttributes(attrs);
4134 MaybeParseCXX11Attributes(attrs);
4135 MaybeParseMicrosoftDeclSpecs(attrs);
4137 SourceLocation ScopedEnumKWLoc;
4138 bool IsScopedUsingClassTag = false;
4140 // In C++11, recognize 'enum class' and 'enum struct'.
4141 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4142 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4143 : diag::ext_scoped_enum);
4144 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4145 ScopedEnumKWLoc = ConsumeToken();
4147 // Attributes are not allowed between these keywords. Diagnose,
4148 // but then just treat them like they appeared in the right place.
4149 ProhibitAttributes(attrs);
4151 // They are allowed afterwards, though.
4152 MaybeParseGNUAttributes(attrs);
4153 MaybeParseCXX11Attributes(attrs);
4154 MaybeParseMicrosoftDeclSpecs(attrs);
4157 // C++11 [temp.explicit]p12:
4158 // The usual access controls do not apply to names used to specify
4159 // explicit instantiations.
4160 // We extend this to also cover explicit specializations. Note that
4161 // we don't suppress if this turns out to be an elaborated type
4163 bool shouldDelayDiagsInTag =
4164 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4165 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4166 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4168 // Enum definitions should not be parsed in a trailing-return-type.
4169 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4171 CXXScopeSpec &SS = DS.getTypeSpecScope();
4172 if (getLangOpts().CPlusPlus) {
4173 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4174 // if a fixed underlying type is allowed.
4175 ColonProtectionRAIIObject X(*this, AllowDeclaration);
4178 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4179 /*EnteringContext=*/true))
4182 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4183 Diag(Tok, diag::err_expected) << tok::identifier;
4184 if (Tok.isNot(tok::l_brace)) {
4185 // Has no name and is not a definition.
4186 // Skip the rest of this declarator, up until the comma or semicolon.
4187 SkipUntil(tok::comma, StopAtSemi);
4195 // Must have either 'enum name' or 'enum {...}'.
4196 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4197 !(AllowDeclaration && Tok.is(tok::colon))) {
4198 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4200 // Skip the rest of this declarator, up until the comma or semicolon.
4201 SkipUntil(tok::comma, StopAtSemi);
4205 // If an identifier is present, consume and remember it.
4206 IdentifierInfo *Name = nullptr;
4207 SourceLocation NameLoc;
4208 if (Tok.is(tok::identifier)) {
4209 Name = Tok.getIdentifierInfo();
4210 NameLoc = ConsumeToken();
4213 if (!Name && ScopedEnumKWLoc.isValid()) {
4214 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4215 // declaration of a scoped enumeration.
4216 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4217 ScopedEnumKWLoc = SourceLocation();
4218 IsScopedUsingClassTag = false;
4221 // Okay, end the suppression area. We'll decide whether to emit the
4222 // diagnostics in a second.
4223 if (shouldDelayDiagsInTag)
4224 diagsFromTag.done();
4226 TypeResult BaseType;
4228 // Parse the fixed underlying type.
4229 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4230 if (AllowDeclaration && Tok.is(tok::colon)) {
4231 bool PossibleBitfield = false;
4232 if (CanBeBitfield) {
4233 // If we're in class scope, this can either be an enum declaration with
4234 // an underlying type, or a declaration of a bitfield member. We try to
4235 // use a simple disambiguation scheme first to catch the common cases
4236 // (integer literal, sizeof); if it's still ambiguous, we then consider
4237 // anything that's a simple-type-specifier followed by '(' as an
4238 // expression. This suffices because function types are not valid
4239 // underlying types anyway.
4240 EnterExpressionEvaluationContext Unevaluated(
4241 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4242 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4243 // If the next token starts an expression, we know we're parsing a
4244 // bit-field. This is the common case.
4245 if (TPR == TPResult::True)
4246 PossibleBitfield = true;
4247 // If the next token starts a type-specifier-seq, it may be either a
4248 // a fixed underlying type or the start of a function-style cast in C++;
4249 // lookahead one more token to see if it's obvious that we have a
4250 // fixed underlying type.
4251 else if (TPR == TPResult::False &&
4252 GetLookAheadToken(2).getKind() == tok::semi) {
4256 // We have the start of a type-specifier-seq, so we have to perform
4257 // tentative parsing to determine whether we have an expression or a
4259 TentativeParsingAction TPA(*this);
4264 // If we see a type specifier followed by an open-brace, we have an
4265 // ambiguity between an underlying type and a C++11 braced
4266 // function-style cast. Resolve this by always treating it as an
4268 // FIXME: The standard is not entirely clear on how to disambiguate in
4270 if ((getLangOpts().CPlusPlus &&
4271 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4272 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4273 // We'll parse this as a bitfield later.
4274 PossibleBitfield = true;
4277 // We have a type-specifier-seq.
4286 if (!PossibleBitfield) {
4288 BaseType = ParseTypeName(&Range);
4290 if (!getLangOpts().ObjC) {
4291 if (getLangOpts().CPlusPlus11)
4292 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4293 else if (getLangOpts().CPlusPlus)
4294 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4295 else if (getLangOpts().MicrosoftExt)
4296 Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4298 Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4303 // There are four options here. If we have 'friend enum foo;' then this is a
4304 // friend declaration, and cannot have an accompanying definition. If we have
4305 // 'enum foo;', then this is a forward declaration. If we have
4306 // 'enum foo {...' then this is a definition. Otherwise we have something
4307 // like 'enum foo xyz', a reference.
4309 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4310 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4311 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4313 Sema::TagUseKind TUK;
4314 if (!AllowDeclaration) {
4315 TUK = Sema::TUK_Reference;
4316 } else if (Tok.is(tok::l_brace)) {
4317 if (DS.isFriendSpecified()) {
4318 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4319 << SourceRange(DS.getFriendSpecLoc());
4321 SkipUntil(tok::r_brace, StopAtSemi);
4322 TUK = Sema::TUK_Friend;
4324 TUK = Sema::TUK_Definition;
4326 } else if (!isTypeSpecifier(DSC) &&
4327 (Tok.is(tok::semi) ||
4328 (Tok.isAtStartOfLine() &&
4329 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4330 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4331 if (Tok.isNot(tok::semi)) {
4332 // A semicolon was missing after this declaration. Diagnose and recover.
4333 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4335 Tok.setKind(tok::semi);
4338 TUK = Sema::TUK_Reference;
4341 // If this is an elaborated type specifier, and we delayed
4342 // diagnostics before, just merge them into the current pool.
4343 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4344 diagsFromTag.redelay();
4347 MultiTemplateParamsArg TParams;
4348 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4349 TUK != Sema::TUK_Reference) {
4350 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4351 // Skip the rest of this declarator, up until the comma or semicolon.
4352 Diag(Tok, diag::err_enum_template);
4353 SkipUntil(tok::comma, StopAtSemi);
4357 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4358 // Enumerations can't be explicitly instantiated.
4359 DS.SetTypeSpecError();
4360 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4364 assert(TemplateInfo.TemplateParams && "no template parameters");
4365 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4366 TemplateInfo.TemplateParams->size());
4369 if (TUK == Sema::TUK_Reference)
4370 ProhibitAttributes(attrs);
4372 if (!Name && TUK != Sema::TUK_Definition) {
4373 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4375 // Skip the rest of this declarator, up until the comma or semicolon.
4376 SkipUntil(tok::comma, StopAtSemi);
4380 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4382 Sema::SkipBodyInfo SkipBody;
4383 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4384 NextToken().is(tok::identifier))
4385 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4386 NextToken().getIdentifierInfo(),
4387 NextToken().getLocation());
4390 bool IsDependent = false;
4391 const char *PrevSpec = nullptr;
4393 Decl *TagDecl = Actions.ActOnTag(
4394 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4395 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4396 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4397 DSC == DeclSpecContext::DSC_type_specifier,
4398 DSC == DeclSpecContext::DSC_template_param ||
4399 DSC == DeclSpecContext::DSC_template_type_arg,
4402 if (SkipBody.ShouldSkip) {
4403 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4405 BalancedDelimiterTracker T(*this, tok::l_brace);
4409 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4410 NameLoc.isValid() ? NameLoc : StartLoc,
4411 PrevSpec, DiagID, TagDecl, Owned,
4412 Actions.getASTContext().getPrintingPolicy()))
4413 Diag(StartLoc, DiagID) << PrevSpec;
4418 // This enum has a dependent nested-name-specifier. Handle it as a
4421 DS.SetTypeSpecError();
4422 Diag(Tok, diag::err_expected_type_name_after_typename);
4426 TypeResult Type = Actions.ActOnDependentTag(
4427 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4428 if (Type.isInvalid()) {
4429 DS.SetTypeSpecError();
4433 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4434 NameLoc.isValid() ? NameLoc : StartLoc,
4435 PrevSpec, DiagID, Type.get(),
4436 Actions.getASTContext().getPrintingPolicy()))
4437 Diag(StartLoc, DiagID) << PrevSpec;
4443 // The action failed to produce an enumeration tag. If this is a
4444 // definition, consume the entire definition.
4445 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4447 SkipUntil(tok::r_brace, StopAtSemi);
4450 DS.SetTypeSpecError();
4454 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4455 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4456 ParseEnumBody(StartLoc, D);
4457 if (SkipBody.CheckSameAsPrevious &&
4458 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4459 DS.SetTypeSpecError();
4464 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4465 NameLoc.isValid() ? NameLoc : StartLoc,
4466 PrevSpec, DiagID, TagDecl, Owned,
4467 Actions.getASTContext().getPrintingPolicy()))
4468 Diag(StartLoc, DiagID) << PrevSpec;
4471 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4472 /// enumerator-list:
4474 /// enumerator-list ',' enumerator
4476 /// enumeration-constant attributes[opt]
4477 /// enumeration-constant attributes[opt] '=' constant-expression
4478 /// enumeration-constant:
4481 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4482 // Enter the scope of the enum body and start the definition.
4483 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4484 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4486 BalancedDelimiterTracker T(*this, tok::l_brace);
4489 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4490 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4491 Diag(Tok, diag::err_empty_enum);
4493 SmallVector<Decl *, 32> EnumConstantDecls;
4494 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4496 Decl *LastEnumConstDecl = nullptr;
4498 // Parse the enumerator-list.
4499 while (Tok.isNot(tok::r_brace)) {
4500 // Parse enumerator. If failed, try skipping till the start of the next
4501 // enumerator definition.
4502 if (Tok.isNot(tok::identifier)) {
4503 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4504 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4505 TryConsumeToken(tok::comma))
4509 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4510 SourceLocation IdentLoc = ConsumeToken();
4512 // If attributes exist after the enumerator, parse them.
4513 ParsedAttributesWithRange attrs(AttrFactory);
4514 MaybeParseGNUAttributes(attrs);
4515 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4516 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4517 if (getLangOpts().CPlusPlus)
4518 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4519 ? diag::warn_cxx14_compat_ns_enum_attribute
4520 : diag::ext_ns_enum_attribute)
4521 << 1 /*enumerator*/;
4522 ParseCXX11Attributes(attrs);
4525 SourceLocation EqualLoc;
4526 ExprResult AssignedVal;
4527 EnumAvailabilityDiags.emplace_back(*this);
4529 if (TryConsumeToken(tok::equal, EqualLoc)) {
4530 AssignedVal = ParseConstantExpression();
4531 if (AssignedVal.isInvalid())
4532 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4535 // Install the enumerator constant into EnumDecl.
4536 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4537 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4538 EqualLoc, AssignedVal.get());
4539 EnumAvailabilityDiags.back().done();
4541 EnumConstantDecls.push_back(EnumConstDecl);
4542 LastEnumConstDecl = EnumConstDecl;
4544 if (Tok.is(tok::identifier)) {
4545 // We're missing a comma between enumerators.
4546 SourceLocation Loc = getEndOfPreviousToken();
4547 Diag(Loc, diag::err_enumerator_list_missing_comma)
4548 << FixItHint::CreateInsertion(Loc, ", ");
4552 // Emumerator definition must be finished, only comma or r_brace are
4554 SourceLocation CommaLoc;
4555 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4556 if (EqualLoc.isValid())
4557 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4560 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4561 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4562 if (TryConsumeToken(tok::comma, CommaLoc))
4569 // If comma is followed by r_brace, emit appropriate warning.
4570 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4571 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4572 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4573 diag::ext_enumerator_list_comma_cxx :
4574 diag::ext_enumerator_list_comma_c)
4575 << FixItHint::CreateRemoval(CommaLoc);
4576 else if (getLangOpts().CPlusPlus11)
4577 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4578 << FixItHint::CreateRemoval(CommaLoc);
4586 // If attributes exist after the identifier list, parse them.
4587 ParsedAttributes attrs(AttrFactory);
4588 MaybeParseGNUAttributes(attrs);
4590 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4591 getCurScope(), attrs);
4593 // Now handle enum constant availability diagnostics.
4594 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4595 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4596 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4597 EnumAvailabilityDiags[i].redelay();
4598 PD.complete(EnumConstantDecls[i]);
4602 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4604 // The next token must be valid after an enum definition. If not, a ';'
4605 // was probably forgotten.
4606 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4607 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4608 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4609 // Push this token back into the preprocessor and change our current token
4610 // to ';' so that the rest of the code recovers as though there were an
4611 // ';' after the definition.
4613 Tok.setKind(tok::semi);
4617 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4618 /// is definitely a type-specifier. Return false if it isn't part of a type
4619 /// specifier or if we're not sure.
4620 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4621 switch (Tok.getKind()) {
4622 default: return false;
4626 case tok::kw___int64:
4627 case tok::kw___int128:
4628 case tok::kw_signed:
4629 case tok::kw_unsigned:
4630 case tok::kw__Complex:
4631 case tok::kw__Imaginary:
4634 case tok::kw_wchar_t:
4635 case tok::kw_char8_t:
4636 case tok::kw_char16_t:
4637 case tok::kw_char32_t:
4641 case tok::kw_double:
4642 case tok::kw__Accum:
4643 case tok::kw__Fract:
4644 case tok::kw__Float16:
4645 case tok::kw___float128:
4648 case tok::kw__Decimal32:
4649 case tok::kw__Decimal64:
4650 case tok::kw__Decimal128:
4651 case tok::kw___vector:
4652 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4653 #include "clang/Basic/OpenCLImageTypes.def"
4655 // struct-or-union-specifier (C99) or class-specifier (C++)
4657 case tok::kw_struct:
4658 case tok::kw___interface:
4664 case tok::annot_typename:
4669 /// isTypeSpecifierQualifier - Return true if the current token could be the
4670 /// start of a specifier-qualifier-list.
4671 bool Parser::isTypeSpecifierQualifier() {
4672 switch (Tok.getKind()) {
4673 default: return false;
4675 case tok::identifier: // foo::bar
4676 if (TryAltiVecVectorToken())
4679 case tok::kw_typename: // typename T::type
4680 // Annotate typenames and C++ scope specifiers. If we get one, just
4681 // recurse to handle whatever we get.
4682 if (TryAnnotateTypeOrScopeToken())
4684 if (Tok.is(tok::identifier))
4686 return isTypeSpecifierQualifier();
4688 case tok::coloncolon: // ::foo::bar
4689 if (NextToken().is(tok::kw_new) || // ::new
4690 NextToken().is(tok::kw_delete)) // ::delete
4693 if (TryAnnotateTypeOrScopeToken())
4695 return isTypeSpecifierQualifier();
4697 // GNU attributes support.
4698 case tok::kw___attribute:
4699 // GNU typeof support.
4700 case tok::kw_typeof:
4705 case tok::kw___int64:
4706 case tok::kw___int128:
4707 case tok::kw_signed:
4708 case tok::kw_unsigned:
4709 case tok::kw__Complex:
4710 case tok::kw__Imaginary:
4713 case tok::kw_wchar_t:
4714 case tok::kw_char8_t:
4715 case tok::kw_char16_t:
4716 case tok::kw_char32_t:
4720 case tok::kw_double:
4721 case tok::kw__Accum:
4722 case tok::kw__Fract:
4723 case tok::kw__Float16:
4724 case tok::kw___float128:
4727 case tok::kw__Decimal32:
4728 case tok::kw__Decimal64:
4729 case tok::kw__Decimal128:
4730 case tok::kw___vector:
4731 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4732 #include "clang/Basic/OpenCLImageTypes.def"
4734 // struct-or-union-specifier (C99) or class-specifier (C++)
4736 case tok::kw_struct:
4737 case tok::kw___interface:
4744 case tok::kw_volatile:
4745 case tok::kw_restrict:
4748 // Debugger support.
4749 case tok::kw___unknown_anytype:
4752 case tok::annot_typename:
4755 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4757 return getLangOpts().ObjC;
4759 case tok::kw___cdecl:
4760 case tok::kw___stdcall:
4761 case tok::kw___fastcall:
4762 case tok::kw___thiscall:
4763 case tok::kw___regcall:
4764 case tok::kw___vectorcall:
4766 case tok::kw___ptr64:
4767 case tok::kw___ptr32:
4768 case tok::kw___pascal:
4769 case tok::kw___unaligned:
4771 case tok::kw__Nonnull:
4772 case tok::kw__Nullable:
4773 case tok::kw__Null_unspecified:
4775 case tok::kw___kindof:
4777 case tok::kw___private:
4778 case tok::kw___local:
4779 case tok::kw___global:
4780 case tok::kw___constant:
4781 case tok::kw___generic:
4782 case tok::kw___read_only:
4783 case tok::kw___read_write:
4784 case tok::kw___write_only:
4789 case tok::kw__Atomic:
4794 /// isDeclarationSpecifier() - Return true if the current token is part of a
4795 /// declaration specifier.
4797 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4798 /// this check is to disambiguate between an expression and a declaration.
4799 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4800 switch (Tok.getKind()) {
4801 default: return false;
4804 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4806 case tok::identifier: // foo::bar
4807 // Unfortunate hack to support "Class.factoryMethod" notation.
4808 if (getLangOpts().ObjC && NextToken().is(tok::period))
4810 if (TryAltiVecVectorToken())
4813 case tok::kw_decltype: // decltype(T())::type
4814 case tok::kw_typename: // typename T::type
4815 // Annotate typenames and C++ scope specifiers. If we get one, just
4816 // recurse to handle whatever we get.
4817 if (TryAnnotateTypeOrScopeToken())
4819 if (Tok.is(tok::identifier))
4822 // If we're in Objective-C and we have an Objective-C class type followed
4823 // by an identifier and then either ':' or ']', in a place where an
4824 // expression is permitted, then this is probably a class message send
4825 // missing the initial '['. In this case, we won't consider this to be
4826 // the start of a declaration.
4827 if (DisambiguatingWithExpression &&
4828 isStartOfObjCClassMessageMissingOpenBracket())
4831 return isDeclarationSpecifier();
4833 case tok::coloncolon: // ::foo::bar
4834 if (NextToken().is(tok::kw_new) || // ::new
4835 NextToken().is(tok::kw_delete)) // ::delete
4838 // Annotate typenames and C++ scope specifiers. If we get one, just
4839 // recurse to handle whatever we get.
4840 if (TryAnnotateTypeOrScopeToken())
4842 return isDeclarationSpecifier();
4844 // storage-class-specifier
4845 case tok::kw_typedef:
4846 case tok::kw_extern:
4847 case tok::kw___private_extern__:
4848 case tok::kw_static:
4850 case tok::kw___auto_type:
4851 case tok::kw_register:
4852 case tok::kw___thread:
4853 case tok::kw_thread_local:
4854 case tok::kw__Thread_local:
4857 case tok::kw___module_private__:
4860 case tok::kw___unknown_anytype:
4865 case tok::kw___int64:
4866 case tok::kw___int128:
4867 case tok::kw_signed:
4868 case tok::kw_unsigned:
4869 case tok::kw__Complex:
4870 case tok::kw__Imaginary:
4873 case tok::kw_wchar_t:
4874 case tok::kw_char8_t:
4875 case tok::kw_char16_t:
4876 case tok::kw_char32_t:
4881 case tok::kw_double:
4882 case tok::kw__Accum:
4883 case tok::kw__Fract:
4884 case tok::kw__Float16:
4885 case tok::kw___float128:
4888 case tok::kw__Decimal32:
4889 case tok::kw__Decimal64:
4890 case tok::kw__Decimal128:
4891 case tok::kw___vector:
4893 // struct-or-union-specifier (C99) or class-specifier (C++)
4895 case tok::kw_struct:
4897 case tok::kw___interface:
4903 case tok::kw_volatile:
4904 case tok::kw_restrict:
4907 // function-specifier
4908 case tok::kw_inline:
4909 case tok::kw_virtual:
4910 case tok::kw_explicit:
4911 case tok::kw__Noreturn:
4913 // alignment-specifier
4914 case tok::kw__Alignas:
4917 case tok::kw_friend:
4919 // static_assert-declaration
4920 case tok::kw__Static_assert:
4922 // GNU typeof support.
4923 case tok::kw_typeof:
4926 case tok::kw___attribute:
4928 // C++11 decltype and constexpr.
4929 case tok::annot_decltype:
4930 case tok::kw_constexpr:
4933 case tok::kw__Atomic:
4936 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4938 return getLangOpts().ObjC;
4941 case tok::annot_typename:
4942 return !DisambiguatingWithExpression ||
4943 !isStartOfObjCClassMessageMissingOpenBracket();
4945 case tok::kw___declspec:
4946 case tok::kw___cdecl:
4947 case tok::kw___stdcall:
4948 case tok::kw___fastcall:
4949 case tok::kw___thiscall:
4950 case tok::kw___regcall:
4951 case tok::kw___vectorcall:
4953 case tok::kw___sptr:
4954 case tok::kw___uptr:
4955 case tok::kw___ptr64:
4956 case tok::kw___ptr32:
4957 case tok::kw___forceinline:
4958 case tok::kw___pascal:
4959 case tok::kw___unaligned:
4961 case tok::kw__Nonnull:
4962 case tok::kw__Nullable:
4963 case tok::kw__Null_unspecified:
4965 case tok::kw___kindof:
4967 case tok::kw___private:
4968 case tok::kw___local:
4969 case tok::kw___global:
4970 case tok::kw___constant:
4971 case tok::kw___generic:
4972 case tok::kw___read_only:
4973 case tok::kw___read_write:
4974 case tok::kw___write_only:
4975 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4976 #include "clang/Basic/OpenCLImageTypes.def"
4982 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4983 TentativeParsingAction TPA(*this);
4985 // Parse the C++ scope specifier.
4987 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4988 /*EnteringContext=*/true)) {
4993 // Parse the constructor name.
4994 if (Tok.is(tok::identifier)) {
4995 // We already know that we have a constructor name; just consume
4998 } else if (Tok.is(tok::annot_template_id)) {
4999 ConsumeAnnotationToken();
5005 // There may be attributes here, appertaining to the constructor name or type
5006 // we just stepped past.
5007 SkipCXX11Attributes();
5009 // Current class name must be followed by a left parenthesis.
5010 if (Tok.isNot(tok::l_paren)) {
5016 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5017 // that we have a constructor.
5018 if (Tok.is(tok::r_paren) ||
5019 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5024 // A C++11 attribute here signals that we have a constructor, and is an
5025 // attribute on the first constructor parameter.
5026 if (getLangOpts().CPlusPlus11 &&
5027 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5028 /*OuterMightBeMessageSend*/ true)) {
5033 // If we need to, enter the specified scope.
5034 DeclaratorScopeObj DeclScopeObj(*this, SS);
5035 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5036 DeclScopeObj.EnterDeclaratorScope();
5038 // Optionally skip Microsoft attributes.
5039 ParsedAttributes Attrs(AttrFactory);
5040 MaybeParseMicrosoftAttributes(Attrs);
5042 // Check whether the next token(s) are part of a declaration
5043 // specifier, in which case we have the start of a parameter and,
5044 // therefore, we know that this is a constructor.
5045 bool IsConstructor = false;
5046 if (isDeclarationSpecifier())
5047 IsConstructor = true;
5048 else if (Tok.is(tok::identifier) ||
5049 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5050 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5051 // This might be a parenthesized member name, but is more likely to
5052 // be a constructor declaration with an invalid argument type. Keep
5054 if (Tok.is(tok::annot_cxxscope))
5055 ConsumeAnnotationToken();
5058 // If this is not a constructor, we must be parsing a declarator,
5059 // which must have one of the following syntactic forms (see the
5060 // grammar extract at the start of ParseDirectDeclarator):
5061 switch (Tok.getKind()) {
5066 // C(X [ [attribute]]);
5067 case tok::coloncolon:
5070 // Assume this isn't a constructor, rather than assuming it's a
5071 // constructor with an unnamed parameter of an ill-formed type.
5077 // Skip past the right-paren and any following attributes to get to
5078 // the function body or trailing-return-type.
5080 SkipCXX11Attributes();
5082 if (DeductionGuide) {
5083 // C(X) -> ... is a deduction guide.
5084 IsConstructor = Tok.is(tok::arrow);
5087 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5088 // Assume these were meant to be constructors:
5089 // C(X) : (the name of a bit-field cannot be parenthesized).
5090 // C(X) try (this is otherwise ill-formed).
5091 IsConstructor = true;
5093 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5094 // If we have a constructor name within the class definition,
5095 // assume these were meant to be constructors:
5098 // ... because otherwise we would be declaring a non-static data
5099 // member that is ill-formed because it's of the same type as its
5100 // surrounding class.
5102 // FIXME: We can actually do this whether or not the name is qualified,
5103 // because if it is qualified in this context it must be being used as
5104 // a constructor name.
5105 // currently, so we're somewhat conservative here.
5106 IsConstructor = IsUnqualified;
5111 IsConstructor = true;
5117 return IsConstructor;
5120 /// ParseTypeQualifierListOpt
5121 /// type-qualifier-list: [C99 6.7.5]
5123 /// [vendor] attributes
5124 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5125 /// type-qualifier-list type-qualifier
5126 /// [vendor] type-qualifier-list attributes
5127 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5128 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5129 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5130 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5131 /// AttrRequirements bitmask values.
5132 void Parser::ParseTypeQualifierListOpt(
5133 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5134 bool IdentifierRequired,
5135 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5136 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5137 isCXX11AttributeSpecifier()) {
5138 ParsedAttributesWithRange attrs(AttrFactory);
5139 ParseCXX11Attributes(attrs);
5140 DS.takeAttributesFrom(attrs);
5143 SourceLocation EndLoc;
5146 bool isInvalid = false;
5147 const char *PrevSpec = nullptr;
5148 unsigned DiagID = 0;
5149 SourceLocation Loc = Tok.getLocation();
5151 switch (Tok.getKind()) {
5152 case tok::code_completion:
5153 if (CodeCompletionHandler)
5154 (*CodeCompletionHandler)();
5156 Actions.CodeCompleteTypeQualifiers(DS);
5157 return cutOffParsing();
5160 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5163 case tok::kw_volatile:
5164 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5167 case tok::kw_restrict:
5168 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5171 case tok::kw__Atomic:
5173 goto DoneWithTypeQuals;
5174 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5178 // OpenCL qualifiers:
5179 case tok::kw___private:
5180 case tok::kw___global:
5181 case tok::kw___local:
5182 case tok::kw___constant:
5183 case tok::kw___generic:
5184 case tok::kw___read_only:
5185 case tok::kw___write_only:
5186 case tok::kw___read_write:
5187 ParseOpenCLQualifiers(DS.getAttributes());
5190 case tok::kw___unaligned:
5191 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5194 case tok::kw___uptr:
5195 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5196 // with the MS modifier keyword.
5197 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5198 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5199 if (TryKeywordIdentFallback(false))
5203 case tok::kw___sptr:
5205 case tok::kw___ptr64:
5206 case tok::kw___ptr32:
5207 case tok::kw___cdecl:
5208 case tok::kw___stdcall:
5209 case tok::kw___fastcall:
5210 case tok::kw___thiscall:
5211 case tok::kw___regcall:
5212 case tok::kw___vectorcall:
5213 if (AttrReqs & AR_DeclspecAttributesParsed) {
5214 ParseMicrosoftTypeAttributes(DS.getAttributes());
5217 goto DoneWithTypeQuals;
5218 case tok::kw___pascal:
5219 if (AttrReqs & AR_VendorAttributesParsed) {
5220 ParseBorlandTypeAttributes(DS.getAttributes());
5223 goto DoneWithTypeQuals;
5225 // Nullability type specifiers.
5226 case tok::kw__Nonnull:
5227 case tok::kw__Nullable:
5228 case tok::kw__Null_unspecified:
5229 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5232 // Objective-C 'kindof' types.
5233 case tok::kw___kindof:
5234 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5235 nullptr, 0, ParsedAttr::AS_Keyword);
5236 (void)ConsumeToken();
5239 case tok::kw___attribute:
5240 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5241 // When GNU attributes are expressly forbidden, diagnose their usage.
5242 Diag(Tok, diag::err_attributes_not_allowed);
5244 // Parse the attributes even if they are rejected to ensure that error
5245 // recovery is graceful.
5246 if (AttrReqs & AR_GNUAttributesParsed ||
5247 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5248 ParseGNUAttributes(DS.getAttributes());
5249 continue; // do *not* consume the next token!
5251 // otherwise, FALL THROUGH!
5255 // If this is not a type-qualifier token, we're done reading type
5256 // qualifiers. First verify that DeclSpec's are consistent.
5257 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5258 if (EndLoc.isValid())
5259 DS.SetRangeEnd(EndLoc);
5263 // If the specifier combination wasn't legal, issue a diagnostic.
5265 assert(PrevSpec && "Method did not return previous specifier!");
5266 Diag(Tok, DiagID) << PrevSpec;
5268 EndLoc = ConsumeToken();
5272 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5274 void Parser::ParseDeclarator(Declarator &D) {
5275 /// This implements the 'declarator' production in the C grammar, then checks
5276 /// for well-formedness and issues diagnostics.
5277 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5280 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5281 DeclaratorContext TheContext) {
5282 if (Kind == tok::star || Kind == tok::caret)
5285 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5288 if (!Lang.CPlusPlus)
5291 if (Kind == tok::amp)
5294 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5295 // But we must not parse them in conversion-type-ids and new-type-ids, since
5296 // those can be legitimately followed by a && operator.
5297 // (The same thing can in theory happen after a trailing-return-type, but
5298 // since those are a C++11 feature, there is no rejects-valid issue there.)
5299 if (Kind == tok::ampamp)
5300 return Lang.CPlusPlus11 ||
5301 (TheContext != DeclaratorContext::ConversionIdContext &&
5302 TheContext != DeclaratorContext::CXXNewContext);
5307 // Indicates whether the given declarator is a pipe declarator.
5308 static bool isPipeDeclerator(const Declarator &D) {
5309 const unsigned NumTypes = D.getNumTypeObjects();
5311 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5312 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5318 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5319 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5320 /// isn't parsed at all, making this function effectively parse the C++
5321 /// ptr-operator production.
5323 /// If the grammar of this construct is extended, matching changes must also be
5324 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5325 /// isConstructorDeclarator.
5327 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5328 /// [C] pointer[opt] direct-declarator
5329 /// [C++] direct-declarator
5330 /// [C++] ptr-operator declarator
5332 /// pointer: [C99 6.7.5]
5333 /// '*' type-qualifier-list[opt]
5334 /// '*' type-qualifier-list[opt] pointer
5337 /// '*' cv-qualifier-seq[opt]
5340 /// [GNU] '&' restrict[opt] attributes[opt]
5341 /// [GNU?] '&&' restrict[opt] attributes[opt]
5342 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5343 void Parser::ParseDeclaratorInternal(Declarator &D,
5344 DirectDeclParseFunction DirectDeclParser) {
5345 if (Diags.hasAllExtensionsSilenced())
5348 // C++ member pointers start with a '::' or a nested-name.
5349 // Member pointers get special handling, since there's no place for the
5350 // scope spec in the generic path below.
5351 if (getLangOpts().CPlusPlus &&
5352 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5353 (Tok.is(tok::identifier) &&
5354 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5355 Tok.is(tok::annot_cxxscope))) {
5356 bool EnteringContext =
5357 D.getContext() == DeclaratorContext::FileContext ||
5358 D.getContext() == DeclaratorContext::MemberContext;
5360 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5362 if (SS.isNotEmpty()) {
5363 if (Tok.isNot(tok::star)) {
5364 // The scope spec really belongs to the direct-declarator.
5365 if (D.mayHaveIdentifier())
5366 D.getCXXScopeSpec() = SS;
5368 AnnotateScopeToken(SS, true);
5370 if (DirectDeclParser)
5371 (this->*DirectDeclParser)(D);
5375 SourceLocation Loc = ConsumeToken();
5377 DeclSpec DS(AttrFactory);
5378 ParseTypeQualifierListOpt(DS);
5379 D.ExtendWithDeclSpec(DS);
5381 // Recurse to parse whatever is left.
5382 ParseDeclaratorInternal(D, DirectDeclParser);
5384 // Sema will have to catch (syntactically invalid) pointers into global
5385 // scope. It has to catch pointers into namespace scope anyway.
5386 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5387 SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5388 std::move(DS.getAttributes()),
5389 /* Don't replace range end. */ SourceLocation());
5394 tok::TokenKind Kind = Tok.getKind();
5396 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5397 DeclSpec DS(AttrFactory);
5398 ParseTypeQualifierListOpt(DS);
5401 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5402 std::move(DS.getAttributes()), SourceLocation());
5405 // Not a pointer, C++ reference, or block.
5406 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5407 if (DirectDeclParser)
5408 (this->*DirectDeclParser)(D);
5412 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5413 // '&&' -> rvalue reference
5414 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5417 if (Kind == tok::star || Kind == tok::caret) {
5419 DeclSpec DS(AttrFactory);
5421 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5422 // C++11 attributes are allowed.
5423 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5424 ((D.getContext() != DeclaratorContext::CXXNewContext)
5425 ? AR_GNUAttributesParsed
5426 : AR_GNUAttributesParsedAndRejected);
5427 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5428 D.ExtendWithDeclSpec(DS);
5430 // Recursively parse the declarator.
5431 ParseDeclaratorInternal(D, DirectDeclParser);
5432 if (Kind == tok::star)
5433 // Remember that we parsed a pointer type, and remember the type-quals.
5434 D.AddTypeInfo(DeclaratorChunk::getPointer(
5435 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5436 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5437 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5438 std::move(DS.getAttributes()), SourceLocation());
5440 // Remember that we parsed a Block type, and remember the type-quals.
5442 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5443 std::move(DS.getAttributes()), SourceLocation());
5446 DeclSpec DS(AttrFactory);
5448 // Complain about rvalue references in C++03, but then go on and build
5450 if (Kind == tok::ampamp)
5451 Diag(Loc, getLangOpts().CPlusPlus11 ?
5452 diag::warn_cxx98_compat_rvalue_reference :
5453 diag::ext_rvalue_reference);
5455 // GNU-style and C++11 attributes are allowed here, as is restrict.
5456 ParseTypeQualifierListOpt(DS);
5457 D.ExtendWithDeclSpec(DS);
5459 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5460 // cv-qualifiers are introduced through the use of a typedef or of a
5461 // template type argument, in which case the cv-qualifiers are ignored.
5462 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5463 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5464 Diag(DS.getConstSpecLoc(),
5465 diag::err_invalid_reference_qualifier_application) << "const";
5466 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5467 Diag(DS.getVolatileSpecLoc(),
5468 diag::err_invalid_reference_qualifier_application) << "volatile";
5469 // 'restrict' is permitted as an extension.
5470 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5471 Diag(DS.getAtomicSpecLoc(),
5472 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5475 // Recursively parse the declarator.
5476 ParseDeclaratorInternal(D, DirectDeclParser);
5478 if (D.getNumTypeObjects() > 0) {
5479 // C++ [dcl.ref]p4: There shall be no references to references.
5480 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5481 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5482 if (const IdentifierInfo *II = D.getIdentifier())
5483 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5486 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5489 // Once we've complained about the reference-to-reference, we
5490 // can go ahead and build the (technically ill-formed)
5491 // declarator: reference collapsing will take care of it.
5495 // Remember that we parsed a reference type.
5496 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5498 std::move(DS.getAttributes()), SourceLocation());
5502 // When correcting from misplaced brackets before the identifier, the location
5503 // is saved inside the declarator so that other diagnostic messages can use
5504 // them. This extracts and returns that location, or returns the provided
5505 // location if a stored location does not exist.
5506 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5507 SourceLocation Loc) {
5508 if (D.getName().StartLocation.isInvalid() &&
5509 D.getName().EndLocation.isValid())
5510 return D.getName().EndLocation;
5515 /// ParseDirectDeclarator
5516 /// direct-declarator: [C99 6.7.5]
5517 /// [C99] identifier
5518 /// '(' declarator ')'
5519 /// [GNU] '(' attributes declarator ')'
5520 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5521 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5522 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5523 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5524 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5525 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5526 /// attribute-specifier-seq[opt]
5527 /// direct-declarator '(' parameter-type-list ')'
5528 /// direct-declarator '(' identifier-list[opt] ')'
5529 /// [GNU] direct-declarator '(' parameter-forward-declarations
5530 /// parameter-type-list[opt] ')'
5531 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5532 /// cv-qualifier-seq[opt] exception-specification[opt]
5533 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5534 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5535 /// ref-qualifier[opt] exception-specification[opt]
5536 /// [C++] declarator-id
5537 /// [C++11] declarator-id attribute-specifier-seq[opt]
5539 /// declarator-id: [C++ 8]
5540 /// '...'[opt] id-expression
5541 /// '::'[opt] nested-name-specifier[opt] type-name
5543 /// id-expression: [C++ 5.1]
5547 /// unqualified-id: [C++ 5.1]
5549 /// operator-function-id
5550 /// conversion-function-id
5554 /// C++17 adds the following, which we also handle here:
5556 /// simple-declaration:
5557 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5559 /// Note, any additional constructs added here may need corresponding changes
5560 /// in isConstructorDeclarator.
5561 void Parser::ParseDirectDeclarator(Declarator &D) {
5562 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5564 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5565 // This might be a C++17 structured binding.
5566 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5567 D.getCXXScopeSpec().isEmpty())
5568 return ParseDecompositionDeclarator(D);
5570 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5571 // this context it is a bitfield. Also in range-based for statement colon
5572 // may delimit for-range-declaration.
5573 ColonProtectionRAIIObject X(
5574 *this, D.getContext() == DeclaratorContext::MemberContext ||
5575 (D.getContext() == DeclaratorContext::ForContext &&
5576 getLangOpts().CPlusPlus11));
5578 // ParseDeclaratorInternal might already have parsed the scope.
5579 if (D.getCXXScopeSpec().isEmpty()) {
5580 bool EnteringContext =
5581 D.getContext() == DeclaratorContext::FileContext ||
5582 D.getContext() == DeclaratorContext::MemberContext;
5583 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5587 if (D.getCXXScopeSpec().isValid()) {
5588 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5589 D.getCXXScopeSpec()))
5590 // Change the declaration context for name lookup, until this function
5591 // is exited (and the declarator has been parsed).
5592 DeclScopeObj.EnterDeclaratorScope();
5593 else if (getObjCDeclContext()) {
5594 // Ensure that we don't interpret the next token as an identifier when
5595 // dealing with declarations in an Objective-C container.
5596 D.SetIdentifier(nullptr, Tok.getLocation());
5597 D.setInvalidType(true);
5599 goto PastIdentifier;
5603 // C++0x [dcl.fct]p14:
5604 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5605 // parameter-declaration-clause without a preceding comma. In this case,
5606 // the ellipsis is parsed as part of the abstract-declarator if the type
5607 // of the parameter either names a template parameter pack that has not
5608 // been expanded or contains auto; otherwise, it is parsed as part of the
5609 // parameter-declaration-clause.
5610 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5611 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5612 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5613 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5614 NextToken().is(tok::r_paren) &&
5615 !D.hasGroupingParens() &&
5616 !Actions.containsUnexpandedParameterPacks(D) &&
5617 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5618 SourceLocation EllipsisLoc = ConsumeToken();
5619 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5620 // The ellipsis was put in the wrong place. Recover, and explain to
5621 // the user what they should have done.
5623 if (EllipsisLoc.isValid())
5624 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5627 D.setEllipsisLoc(EllipsisLoc);
5629 // The ellipsis can't be followed by a parenthesized declarator. We
5630 // check for that in ParseParenDeclarator, after we have disambiguated
5631 // the l_paren token.
5634 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5636 // We found something that indicates the start of an unqualified-id.
5637 // Parse that unqualified-id.
5638 bool AllowConstructorName;
5639 bool AllowDeductionGuide;
5640 if (D.getDeclSpec().hasTypeSpecifier()) {
5641 AllowConstructorName = false;
5642 AllowDeductionGuide = false;
5643 } else if (D.getCXXScopeSpec().isSet()) {
5644 AllowConstructorName =
5645 (D.getContext() == DeclaratorContext::FileContext ||
5646 D.getContext() == DeclaratorContext::MemberContext);
5647 AllowDeductionGuide = false;
5649 AllowConstructorName =
5650 (D.getContext() == DeclaratorContext::MemberContext);
5651 AllowDeductionGuide =
5652 (D.getContext() == DeclaratorContext::FileContext ||
5653 D.getContext() == DeclaratorContext::MemberContext);
5656 bool HadScope = D.getCXXScopeSpec().isValid();
5657 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5658 /*EnteringContext=*/true,
5659 /*AllowDestructorName=*/true, AllowConstructorName,
5660 AllowDeductionGuide, nullptr, nullptr,
5662 // Once we're past the identifier, if the scope was bad, mark the
5663 // whole declarator bad.
5664 D.getCXXScopeSpec().isInvalid()) {
5665 D.SetIdentifier(nullptr, Tok.getLocation());
5666 D.setInvalidType(true);
5668 // ParseUnqualifiedId might have parsed a scope specifier during error
5669 // recovery. If it did so, enter that scope.
5670 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5671 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5672 D.getCXXScopeSpec()))
5673 DeclScopeObj.EnterDeclaratorScope();
5675 // Parsed the unqualified-id; update range information and move along.
5676 if (D.getSourceRange().getBegin().isInvalid())
5677 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5678 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5680 goto PastIdentifier;
5683 if (D.getCXXScopeSpec().isNotEmpty()) {
5684 // We have a scope specifier but no following unqualified-id.
5685 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5686 diag::err_expected_unqualified_id)
5688 D.SetIdentifier(nullptr, Tok.getLocation());
5689 goto PastIdentifier;
5691 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5692 assert(!getLangOpts().CPlusPlus &&
5693 "There's a C++-specific check for tok::identifier above");
5694 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5695 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5696 D.SetRangeEnd(Tok.getLocation());
5698 goto PastIdentifier;
5699 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5700 // We're not allowed an identifier here, but we got one. Try to figure out
5701 // if the user was trying to attach a name to the type, or whether the name
5702 // is some unrelated trailing syntax.
5703 bool DiagnoseIdentifier = false;
5704 if (D.hasGroupingParens())
5705 // An identifier within parens is unlikely to be intended to be anything
5706 // other than a name being "declared".
5707 DiagnoseIdentifier = true;
5708 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5709 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5710 DiagnoseIdentifier =
5711 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5712 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5713 D.getContext() == DeclaratorContext::AliasTemplateContext)
5714 // The most likely error is that the ';' was forgotten.
5715 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5716 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5717 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5718 !isCXX11VirtSpecifier(Tok))
5719 DiagnoseIdentifier = NextToken().isOneOf(
5720 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5721 if (DiagnoseIdentifier) {
5722 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5723 << FixItHint::CreateRemoval(Tok.getLocation());
5724 D.SetIdentifier(nullptr, Tok.getLocation());
5726 goto PastIdentifier;
5730 if (Tok.is(tok::l_paren)) {
5731 // If this might be an abstract-declarator followed by a direct-initializer,
5732 // check whether this is a valid declarator chunk. If it can't be, assume
5733 // that it's an initializer instead.
5734 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5735 RevertingTentativeParsingAction PA(*this);
5736 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5738 D.SetIdentifier(nullptr, Tok.getLocation());
5739 goto PastIdentifier;
5743 // direct-declarator: '(' declarator ')'
5744 // direct-declarator: '(' attributes declarator ')'
5745 // Example: 'char (*X)' or 'int (*XX)(void)'
5746 ParseParenDeclarator(D);
5748 // If the declarator was parenthesized, we entered the declarator
5749 // scope when parsing the parenthesized declarator, then exited
5750 // the scope already. Re-enter the scope, if we need to.
5751 if (D.getCXXScopeSpec().isSet()) {
5752 // If there was an error parsing parenthesized declarator, declarator
5753 // scope may have been entered before. Don't do it again.
5754 if (!D.isInvalidType() &&
5755 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5756 D.getCXXScopeSpec()))
5757 // Change the declaration context for name lookup, until this function
5758 // is exited (and the declarator has been parsed).
5759 DeclScopeObj.EnterDeclaratorScope();
5761 } else if (D.mayOmitIdentifier()) {
5762 // This could be something simple like "int" (in which case the declarator
5763 // portion is empty), if an abstract-declarator is allowed.
5764 D.SetIdentifier(nullptr, Tok.getLocation());
5766 // The grammar for abstract-pack-declarator does not allow grouping parens.
5767 // FIXME: Revisit this once core issue 1488 is resolved.
5768 if (D.hasEllipsis() && D.hasGroupingParens())
5769 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5770 diag::ext_abstract_pack_declarator_parens);
5772 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5774 if (Tok.is(tok::l_square))
5775 return ParseMisplacedBracketDeclarator(D);
5776 if (D.getContext() == DeclaratorContext::MemberContext) {
5777 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5778 // treating these keyword as valid member names.
5779 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
5780 Tok.getIdentifierInfo() &&
5781 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5782 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5783 diag::err_expected_member_name_or_semi_objcxx_keyword)
5784 << Tok.getIdentifierInfo()
5785 << (D.getDeclSpec().isEmpty() ? SourceRange()
5786 : D.getDeclSpec().getSourceRange());
5787 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5788 D.SetRangeEnd(Tok.getLocation());
5790 goto PastIdentifier;
5792 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5793 diag::err_expected_member_name_or_semi)
5794 << (D.getDeclSpec().isEmpty() ? SourceRange()
5795 : D.getDeclSpec().getSourceRange());
5796 } else if (getLangOpts().CPlusPlus) {
5797 if (Tok.isOneOf(tok::period, tok::arrow))
5798 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5800 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5801 if (Tok.isAtStartOfLine() && Loc.isValid())
5802 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5803 << getLangOpts().CPlusPlus;
5805 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5806 diag::err_expected_unqualified_id)
5807 << getLangOpts().CPlusPlus;
5810 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5811 diag::err_expected_either)
5812 << tok::identifier << tok::l_paren;
5814 D.SetIdentifier(nullptr, Tok.getLocation());
5815 D.setInvalidType(true);
5819 assert(D.isPastIdentifier() &&
5820 "Haven't past the location of the identifier yet?");
5822 // Don't parse attributes unless we have parsed an unparenthesized name.
5823 if (D.hasName() && !D.getNumTypeObjects())
5824 MaybeParseCXX11Attributes(D);
5827 if (Tok.is(tok::l_paren)) {
5828 // Enter function-declaration scope, limiting any declarators to the
5829 // function prototype scope, including parameter declarators.
5830 ParseScope PrototypeScope(this,
5831 Scope::FunctionPrototypeScope|Scope::DeclScope|
5832 (D.isFunctionDeclaratorAFunctionDeclaration()
5833 ? Scope::FunctionDeclarationScope : 0));
5835 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5836 // In such a case, check if we actually have a function declarator; if it
5837 // is not, the declarator has been fully parsed.
5838 bool IsAmbiguous = false;
5839 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5840 // The name of the declarator, if any, is tentatively declared within
5841 // a possible direct initializer.
5842 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5843 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5844 TentativelyDeclaredIdentifiers.pop_back();
5845 if (!IsFunctionDecl)
5848 ParsedAttributes attrs(AttrFactory);
5849 BalancedDelimiterTracker T(*this, tok::l_paren);
5851 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5852 PrototypeScope.Exit();
5853 } else if (Tok.is(tok::l_square)) {
5854 ParseBracketDeclarator(D);
5861 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5862 assert(Tok.is(tok::l_square));
5864 // If this doesn't look like a structured binding, maybe it's a misplaced
5865 // array declarator.
5866 // FIXME: Consume the l_square first so we don't need extra lookahead for
5868 if (!(NextToken().is(tok::identifier) &&
5869 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5870 !(NextToken().is(tok::r_square) &&
5871 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5872 return ParseMisplacedBracketDeclarator(D);
5874 BalancedDelimiterTracker T(*this, tok::l_square);
5877 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5878 while (Tok.isNot(tok::r_square)) {
5879 if (!Bindings.empty()) {
5880 if (Tok.is(tok::comma))
5883 if (Tok.is(tok::identifier)) {
5884 SourceLocation EndLoc = getEndOfPreviousToken();
5885 Diag(EndLoc, diag::err_expected)
5886 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5888 Diag(Tok, diag::err_expected_comma_or_rsquare);
5891 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5892 StopAtSemi | StopBeforeMatch);
5893 if (Tok.is(tok::comma))
5895 else if (Tok.isNot(tok::identifier))
5900 if (Tok.isNot(tok::identifier)) {
5901 Diag(Tok, diag::err_expected) << tok::identifier;
5905 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5909 if (Tok.isNot(tok::r_square))
5910 // We've already diagnosed a problem here.
5913 // C++17 does not allow the identifier-list in a structured binding
5915 if (Bindings.empty())
5916 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5921 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5922 T.getCloseLocation());
5925 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5926 /// only called before the identifier, so these are most likely just grouping
5927 /// parens for precedence. If we find that these are actually function
5928 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5930 /// direct-declarator:
5931 /// '(' declarator ')'
5932 /// [GNU] '(' attributes declarator ')'
5933 /// direct-declarator '(' parameter-type-list ')'
5934 /// direct-declarator '(' identifier-list[opt] ')'
5935 /// [GNU] direct-declarator '(' parameter-forward-declarations
5936 /// parameter-type-list[opt] ')'
5938 void Parser::ParseParenDeclarator(Declarator &D) {
5939 BalancedDelimiterTracker T(*this, tok::l_paren);
5942 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5944 // Eat any attributes before we look at whether this is a grouping or function
5945 // declarator paren. If this is a grouping paren, the attribute applies to
5946 // the type being built up, for example:
5947 // int (__attribute__(()) *x)(long y)
5948 // If this ends up not being a grouping paren, the attribute applies to the
5949 // first argument, for example:
5950 // int (__attribute__(()) int x)
5951 // In either case, we need to eat any attributes to be able to determine what
5952 // sort of paren this is.
5954 ParsedAttributes attrs(AttrFactory);
5955 bool RequiresArg = false;
5956 if (Tok.is(tok::kw___attribute)) {
5957 ParseGNUAttributes(attrs);
5959 // We require that the argument list (if this is a non-grouping paren) be
5960 // present even if the attribute list was empty.
5964 // Eat any Microsoft extensions.
5965 ParseMicrosoftTypeAttributes(attrs);
5967 // Eat any Borland extensions.
5968 if (Tok.is(tok::kw___pascal))
5969 ParseBorlandTypeAttributes(attrs);
5971 // If we haven't past the identifier yet (or where the identifier would be
5972 // stored, if this is an abstract declarator), then this is probably just
5973 // grouping parens. However, if this could be an abstract-declarator, then
5974 // this could also be the start of function arguments (consider 'void()').
5977 if (!D.mayOmitIdentifier()) {
5978 // If this can't be an abstract-declarator, this *must* be a grouping
5979 // paren, because we haven't seen the identifier yet.
5981 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5982 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5983 NextToken().is(tok::r_paren)) || // C++ int(...)
5984 isDeclarationSpecifier() || // 'int(int)' is a function.
5985 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5986 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5987 // considered to be a type, not a K&R identifier-list.
5990 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5994 // If this is a grouping paren, handle:
5995 // direct-declarator: '(' declarator ')'
5996 // direct-declarator: '(' attributes declarator ')'
5998 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5999 D.setEllipsisLoc(SourceLocation());
6001 bool hadGroupingParens = D.hasGroupingParens();
6002 D.setGroupingParens(true);
6003 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6007 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6008 std::move(attrs), T.getCloseLocation());
6010 D.setGroupingParens(hadGroupingParens);
6012 // An ellipsis cannot be placed outside parentheses.
6013 if (EllipsisLoc.isValid())
6014 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6019 // Okay, if this wasn't a grouping paren, it must be the start of a function
6020 // argument list. Recognize that this declarator will never have an
6021 // identifier (and remember where it would have been), then call into
6022 // ParseFunctionDeclarator to handle of argument list.
6023 D.SetIdentifier(nullptr, Tok.getLocation());
6025 // Enter function-declaration scope, limiting any declarators to the
6026 // function prototype scope, including parameter declarators.
6027 ParseScope PrototypeScope(this,
6028 Scope::FunctionPrototypeScope | Scope::DeclScope |
6029 (D.isFunctionDeclaratorAFunctionDeclaration()
6030 ? Scope::FunctionDeclarationScope : 0));
6031 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6032 PrototypeScope.Exit();
6035 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6036 /// declarator D up to a paren, which indicates that we are parsing function
6039 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6040 /// immediately after the open paren - they should be considered to be the
6041 /// first argument of a parameter.
6043 /// If RequiresArg is true, then the first argument of the function is required
6044 /// to be present and required to not be an identifier list.
6046 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6047 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6048 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6050 /// [C++11] exception-specification:
6051 /// dynamic-exception-specification
6052 /// noexcept-specification
6054 void Parser::ParseFunctionDeclarator(Declarator &D,
6055 ParsedAttributes &FirstArgAttrs,
6056 BalancedDelimiterTracker &Tracker,
6059 assert(getCurScope()->isFunctionPrototypeScope() &&
6060 "Should call from a Function scope");
6061 // lparen is already consumed!
6062 assert(D.isPastIdentifier() && "Should not call before identifier!");
6064 // This should be true when the function has typed arguments.
6065 // Otherwise, it is treated as a K&R-style function.
6066 bool HasProto = false;
6067 // Build up an array of information about the parsed arguments.
6068 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6069 // Remember where we see an ellipsis, if any.
6070 SourceLocation EllipsisLoc;
6072 DeclSpec DS(AttrFactory);
6073 bool RefQualifierIsLValueRef = true;
6074 SourceLocation RefQualifierLoc;
6075 ExceptionSpecificationType ESpecType = EST_None;
6076 SourceRange ESpecRange;
6077 SmallVector<ParsedType, 2> DynamicExceptions;
6078 SmallVector<SourceRange, 2> DynamicExceptionRanges;
6079 ExprResult NoexceptExpr;
6080 CachedTokens *ExceptionSpecTokens = nullptr;
6081 ParsedAttributesWithRange FnAttrs(AttrFactory);
6082 TypeResult TrailingReturnType;
6084 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6085 EndLoc is the end location for the function declarator.
6086 They differ for trailing return types. */
6087 SourceLocation StartLoc, LocalEndLoc, EndLoc;
6088 SourceLocation LParenLoc, RParenLoc;
6089 LParenLoc = Tracker.getOpenLocation();
6090 StartLoc = LParenLoc;
6092 if (isFunctionDeclaratorIdentifierList()) {
6094 Diag(Tok, diag::err_argument_required_after_attribute);
6096 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6098 Tracker.consumeClose();
6099 RParenLoc = Tracker.getCloseLocation();
6100 LocalEndLoc = RParenLoc;
6103 // If there are attributes following the identifier list, parse them and
6105 MaybeParseCXX11Attributes(FnAttrs);
6106 ProhibitAttributes(FnAttrs);
6108 if (Tok.isNot(tok::r_paren))
6109 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6111 else if (RequiresArg)
6112 Diag(Tok, diag::err_argument_required_after_attribute);
6114 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6115 || getLangOpts().OpenCL;
6117 // If we have the closing ')', eat it.
6118 Tracker.consumeClose();
6119 RParenLoc = Tracker.getCloseLocation();
6120 LocalEndLoc = RParenLoc;
6123 if (getLangOpts().CPlusPlus) {
6124 // FIXME: Accept these components in any order, and produce fixits to
6125 // correct the order if the user gets it wrong. Ideally we should deal
6126 // with the pure-specifier in the same way.
6128 // Parse cv-qualifier-seq[opt].
6129 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6130 /*AtomicAllowed*/ false,
6131 /*IdentifierRequired=*/false,
6132 llvm::function_ref<void()>([&]() {
6133 Actions.CodeCompleteFunctionQualifiers(DS, D);
6135 if (!DS.getSourceRange().getEnd().isInvalid()) {
6136 EndLoc = DS.getSourceRange().getEnd();
6139 // Parse ref-qualifier[opt].
6140 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6141 EndLoc = RefQualifierLoc;
6143 // C++11 [expr.prim.general]p3:
6144 // If a declaration declares a member function or member function
6145 // template of a class X, the expression this is a prvalue of type
6146 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6147 // and the end of the function-definition, member-declarator, or
6149 // FIXME: currently, "static" case isn't handled correctly.
6150 bool IsCXX11MemberFunction =
6151 getLangOpts().CPlusPlus11 &&
6152 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6153 (D.getContext() == DeclaratorContext::MemberContext
6154 ? !D.getDeclSpec().isFriendSpecified()
6155 : D.getContext() == DeclaratorContext::FileContext &&
6156 D.getCXXScopeSpec().isValid() &&
6157 Actions.CurContext->isRecord());
6159 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6160 if (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14)
6163 Sema::CXXThisScopeRAII ThisScope(
6164 Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6165 IsCXX11MemberFunction);
6167 // Parse exception-specification[opt].
6168 bool Delayed = D.isFirstDeclarationOfMember() &&
6169 D.isFunctionDeclaratorAFunctionDeclaration();
6170 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6171 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6172 GetLookAheadToken(1).is(tok::l_paren) &&
6173 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6174 GetLookAheadToken(3).is(tok::l_paren) &&
6175 GetLookAheadToken(4).is(tok::identifier) &&
6176 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6177 // HACK: We've got an exception-specification
6178 // noexcept(noexcept(swap(...)))
6180 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6181 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6182 // for 'swap' will only find the function we're currently declaring,
6183 // whereas it expects to find a non-member swap through ADL. Turn off
6184 // delayed parsing to give it a chance to find what it expects.
6187 ESpecType = tryParseExceptionSpecification(Delayed,
6190 DynamicExceptionRanges,
6192 ExceptionSpecTokens);
6193 if (ESpecType != EST_None)
6194 EndLoc = ESpecRange.getEnd();
6196 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6197 // after the exception-specification.
6198 MaybeParseCXX11Attributes(FnAttrs);
6200 // Parse trailing-return-type[opt].
6201 LocalEndLoc = EndLoc;
6202 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6203 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6204 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6205 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6206 LocalEndLoc = Tok.getLocation();
6208 TrailingReturnType =
6209 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6210 EndLoc = Range.getEnd();
6212 } else if (standardAttributesAllowed()) {
6213 MaybeParseCXX11Attributes(FnAttrs);
6217 // Collect non-parameter declarations from the prototype if this is a function
6218 // declaration. They will be moved into the scope of the function. Only do
6219 // this in C and not C++, where the decls will continue to live in the
6220 // surrounding context.
6221 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6222 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6223 !getLangOpts().CPlusPlus) {
6224 for (Decl *D : getCurScope()->decls()) {
6225 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6226 if (!ND || isa<ParmVarDecl>(ND))
6228 DeclsInPrototype.push_back(ND);
6232 // Remember that we parsed a function type, and remember the attributes.
6233 D.AddTypeInfo(DeclaratorChunk::getFunction(
6234 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6235 ParamInfo.size(), EllipsisLoc, RParenLoc,
6236 RefQualifierIsLValueRef, RefQualifierLoc,
6237 /*MutableLoc=*/SourceLocation(),
6238 ESpecType, ESpecRange, DynamicExceptions.data(),
6239 DynamicExceptionRanges.data(), DynamicExceptions.size(),
6240 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6241 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6242 LocalEndLoc, D, TrailingReturnType, &DS),
6243 std::move(FnAttrs), EndLoc);
6246 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6247 /// true if a ref-qualifier is found.
6248 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6249 SourceLocation &RefQualifierLoc) {
6250 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6251 Diag(Tok, getLangOpts().CPlusPlus11 ?
6252 diag::warn_cxx98_compat_ref_qualifier :
6253 diag::ext_ref_qualifier);
6255 RefQualifierIsLValueRef = Tok.is(tok::amp);
6256 RefQualifierLoc = ConsumeToken();
6262 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6263 /// identifier list form for a K&R-style function: void foo(a,b,c)
6265 /// Note that identifier-lists are only allowed for normal declarators, not for
6266 /// abstract-declarators.
6267 bool Parser::isFunctionDeclaratorIdentifierList() {
6268 return !getLangOpts().CPlusPlus
6269 && Tok.is(tok::identifier)
6270 && !TryAltiVecVectorToken()
6271 // K&R identifier lists can't have typedefs as identifiers, per C99
6273 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6274 // Identifier lists follow a really simple grammar: the identifiers can
6275 // be followed *only* by a ", identifier" or ")". However, K&R
6276 // identifier lists are really rare in the brave new modern world, and
6277 // it is very common for someone to typo a type in a non-K&R style
6278 // list. If we are presented with something like: "void foo(intptr x,
6279 // float y)", we don't want to start parsing the function declarator as
6280 // though it is a K&R style declarator just because intptr is an
6283 // To handle this, we check to see if the token after the first
6284 // identifier is a "," or ")". Only then do we parse it as an
6286 && (!Tok.is(tok::eof) &&
6287 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6290 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6291 /// we found a K&R-style identifier list instead of a typed parameter list.
6293 /// After returning, ParamInfo will hold the parsed parameters.
6295 /// identifier-list: [C99 6.7.5]
6297 /// identifier-list ',' identifier
6299 void Parser::ParseFunctionDeclaratorIdentifierList(
6301 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6302 // If there was no identifier specified for the declarator, either we are in
6303 // an abstract-declarator, or we are in a parameter declarator which was found
6304 // to be abstract. In abstract-declarators, identifier lists are not valid:
6306 if (!D.getIdentifier())
6307 Diag(Tok, diag::ext_ident_list_in_param);
6309 // Maintain an efficient lookup of params we have seen so far.
6310 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6313 // If this isn't an identifier, report the error and skip until ')'.
6314 if (Tok.isNot(tok::identifier)) {
6315 Diag(Tok, diag::err_expected) << tok::identifier;
6316 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6317 // Forget we parsed anything.
6322 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6324 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6325 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6326 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6328 // Verify that the argument identifier has not already been mentioned.
6329 if (!ParamsSoFar.insert(ParmII).second) {
6330 Diag(Tok, diag::err_param_redefinition) << ParmII;
6332 // Remember this identifier in ParamInfo.
6333 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6338 // Eat the identifier.
6340 // The list continues if we see a comma.
6341 } while (TryConsumeToken(tok::comma));
6344 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6345 /// after the opening parenthesis. This function will not parse a K&R-style
6346 /// identifier list.
6348 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6349 /// caller parsed those arguments immediately after the open paren - they should
6350 /// be considered to be part of the first parameter.
6352 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6353 /// be the location of the ellipsis, if any was parsed.
6355 /// parameter-type-list: [C99 6.7.5]
6357 /// parameter-list ',' '...'
6358 /// [C++] parameter-list '...'
6360 /// parameter-list: [C99 6.7.5]
6361 /// parameter-declaration
6362 /// parameter-list ',' parameter-declaration
6364 /// parameter-declaration: [C99 6.7.5]
6365 /// declaration-specifiers declarator
6366 /// [C++] declaration-specifiers declarator '=' assignment-expression
6367 /// [C++11] initializer-clause
6368 /// [GNU] declaration-specifiers declarator attributes
6369 /// declaration-specifiers abstract-declarator[opt]
6370 /// [C++] declaration-specifiers abstract-declarator[opt]
6371 /// '=' assignment-expression
6372 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6373 /// [C++11] attribute-specifier-seq parameter-declaration
6375 void Parser::ParseParameterDeclarationClause(
6377 ParsedAttributes &FirstArgAttrs,
6378 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6379 SourceLocation &EllipsisLoc) {
6381 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6382 // before deciding this was a parameter-declaration-clause.
6383 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6386 // Parse the declaration-specifiers.
6387 // Just use the ParsingDeclaration "scope" of the declarator.
6388 DeclSpec DS(AttrFactory);
6390 // Parse any C++11 attributes.
6391 MaybeParseCXX11Attributes(DS.getAttributes());
6393 // Skip any Microsoft attributes before a param.
6394 MaybeParseMicrosoftAttributes(DS.getAttributes());
6396 SourceLocation DSStart = Tok.getLocation();
6398 // If the caller parsed attributes for the first argument, add them now.
6399 // Take them so that we only apply the attributes to the first parameter.
6400 // FIXME: If we can leave the attributes in the token stream somehow, we can
6401 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6403 DS.takeAttributesFrom(FirstArgAttrs);
6405 ParseDeclarationSpecifiers(DS);
6408 // Parse the declarator. This is "PrototypeContext" or
6409 // "LambdaExprParameterContext", because we must accept either
6410 // 'declarator' or 'abstract-declarator' here.
6411 Declarator ParmDeclarator(
6412 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6413 ? DeclaratorContext::LambdaExprParameterContext
6414 : DeclaratorContext::PrototypeContext);
6415 ParseDeclarator(ParmDeclarator);
6417 // Parse GNU attributes, if present.
6418 MaybeParseGNUAttributes(ParmDeclarator);
6420 // Remember this parsed parameter in ParamInfo.
6421 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6423 // DefArgToks is used when the parsing of default arguments needs
6425 std::unique_ptr<CachedTokens> DefArgToks;
6427 // If no parameter was specified, verify that *something* was specified,
6428 // otherwise we have a missing type and identifier.
6429 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6430 ParmDeclarator.getNumTypeObjects() == 0) {
6431 // Completely missing, emit error.
6432 Diag(DSStart, diag::err_missing_param);
6434 // Otherwise, we have something. Add it and let semantic analysis try
6435 // to grok it and add the result to the ParamInfo we are building.
6437 // Last chance to recover from a misplaced ellipsis in an attempted
6438 // parameter pack declaration.
6439 if (Tok.is(tok::ellipsis) &&
6440 (NextToken().isNot(tok::r_paren) ||
6441 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6442 !Actions.isUnexpandedParameterPackPermitted())) &&
6443 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6444 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6446 // Inform the actions module about the parameter declarator, so it gets
6447 // added to the current scope.
6448 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6449 // Parse the default argument, if any. We parse the default
6450 // arguments in all dialects; the semantic analysis in
6451 // ActOnParamDefaultArgument will reject the default argument in
6453 if (Tok.is(tok::equal)) {
6454 SourceLocation EqualLoc = Tok.getLocation();
6456 // Parse the default argument
6457 if (D.getContext() == DeclaratorContext::MemberContext) {
6458 // If we're inside a class definition, cache the tokens
6459 // corresponding to the default argument. We'll actually parse
6460 // them when we see the end of the class definition.
6461 DefArgToks.reset(new CachedTokens);
6463 SourceLocation ArgStartLoc = NextToken().getLocation();
6464 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6466 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6468 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6475 // The argument isn't actually potentially evaluated unless it is
6477 EnterExpressionEvaluationContext Eval(
6479 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6482 ExprResult DefArgResult;
6483 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6484 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6485 DefArgResult = ParseBraceInitializer();
6487 DefArgResult = ParseAssignmentExpression();
6488 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6489 if (DefArgResult.isInvalid()) {
6490 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6491 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6493 // Inform the actions module about the default argument
6494 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6495 DefArgResult.get());
6500 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6501 ParmDeclarator.getIdentifierLoc(),
6502 Param, std::move(DefArgToks)));
6505 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6506 if (!getLangOpts().CPlusPlus) {
6507 // We have ellipsis without a preceding ',', which is ill-formed
6508 // in C. Complain and provide the fix.
6509 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6510 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6511 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6512 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6513 // It looks like this was supposed to be a parameter pack. Warn and
6514 // point out where the ellipsis should have gone.
6515 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6516 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6517 << ParmEllipsis.isValid() << ParmEllipsis;
6518 if (ParmEllipsis.isValid()) {
6520 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6522 Diag(ParmDeclarator.getIdentifierLoc(),
6523 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6524 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6526 << !ParmDeclarator.hasName();
6528 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6529 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6532 // We can't have any more parameters after an ellipsis.
6536 // If the next token is a comma, consume it and keep reading arguments.
6537 } while (TryConsumeToken(tok::comma));
6540 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6541 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6542 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6543 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6544 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6545 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6546 /// attribute-specifier-seq[opt]
6547 void Parser::ParseBracketDeclarator(Declarator &D) {
6548 if (CheckProhibitedCXX11Attribute())
6551 BalancedDelimiterTracker T(*this, tok::l_square);
6554 // C array syntax has many features, but by-far the most common is [] and [4].
6555 // This code does a fast path to handle some of the most obvious cases.
6556 if (Tok.getKind() == tok::r_square) {
6558 ParsedAttributes attrs(AttrFactory);
6559 MaybeParseCXX11Attributes(attrs);
6561 // Remember that we parsed the empty array type.
6562 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6563 T.getOpenLocation(),
6564 T.getCloseLocation()),
6565 std::move(attrs), T.getCloseLocation());
6567 } else if (Tok.getKind() == tok::numeric_constant &&
6568 GetLookAheadToken(1).is(tok::r_square)) {
6569 // [4] is very common. Parse the numeric constant expression.
6570 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6574 ParsedAttributes attrs(AttrFactory);
6575 MaybeParseCXX11Attributes(attrs);
6577 // Remember that we parsed a array type, and remember its features.
6578 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6579 T.getOpenLocation(),
6580 T.getCloseLocation()),
6581 std::move(attrs), T.getCloseLocation());
6583 } else if (Tok.getKind() == tok::code_completion) {
6584 Actions.CodeCompleteBracketDeclarator(getCurScope());
6585 return cutOffParsing();
6588 // If valid, this location is the position where we read the 'static' keyword.
6589 SourceLocation StaticLoc;
6590 TryConsumeToken(tok::kw_static, StaticLoc);
6592 // If there is a type-qualifier-list, read it now.
6593 // Type qualifiers in an array subscript are a C99 feature.
6594 DeclSpec DS(AttrFactory);
6595 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6597 // If we haven't already read 'static', check to see if there is one after the
6598 // type-qualifier-list.
6599 if (!StaticLoc.isValid())
6600 TryConsumeToken(tok::kw_static, StaticLoc);
6602 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6603 bool isStar = false;
6604 ExprResult NumElements;
6606 // Handle the case where we have '[*]' as the array size. However, a leading
6607 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6608 // the token after the star is a ']'. Since stars in arrays are
6609 // infrequent, use of lookahead is not costly here.
6610 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6611 ConsumeToken(); // Eat the '*'.
6613 if (StaticLoc.isValid()) {
6614 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6615 StaticLoc = SourceLocation(); // Drop the static.
6618 } else if (Tok.isNot(tok::r_square)) {
6619 // Note, in C89, this production uses the constant-expr production instead
6620 // of assignment-expr. The only difference is that assignment-expr allows
6621 // things like '=' and '*='. Sema rejects these in C89 mode because they
6622 // are not i-c-e's, so we don't need to distinguish between the two here.
6624 // Parse the constant-expression or assignment-expression now (depending
6626 if (getLangOpts().CPlusPlus) {
6627 NumElements = ParseConstantExpression();
6629 EnterExpressionEvaluationContext Unevaluated(
6630 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6632 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6635 if (StaticLoc.isValid()) {
6636 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6637 StaticLoc = SourceLocation(); // Drop the static.
6641 // If there was an error parsing the assignment-expression, recover.
6642 if (NumElements.isInvalid()) {
6643 D.setInvalidType(true);
6644 // If the expression was invalid, skip it.
6645 SkipUntil(tok::r_square, StopAtSemi);
6651 MaybeParseCXX11Attributes(DS.getAttributes());
6653 // Remember that we parsed a array type, and remember its features.
6655 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6656 isStar, NumElements.get(), T.getOpenLocation(),
6657 T.getCloseLocation()),
6658 std::move(DS.getAttributes()), T.getCloseLocation());
6661 /// Diagnose brackets before an identifier.
6662 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6663 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6664 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6666 SourceLocation StartBracketLoc = Tok.getLocation();
6667 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6669 while (Tok.is(tok::l_square)) {
6670 ParseBracketDeclarator(TempDeclarator);
6673 // Stuff the location of the start of the brackets into the Declarator.
6674 // The diagnostics from ParseDirectDeclarator will make more sense if
6675 // they use this location instead.
6676 if (Tok.is(tok::semi))
6677 D.getName().EndLocation = StartBracketLoc;
6679 SourceLocation SuggestParenLoc = Tok.getLocation();
6681 // Now that the brackets are removed, try parsing the declarator again.
6682 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6684 // Something went wrong parsing the brackets, in which case,
6685 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6687 if (TempDeclarator.getNumTypeObjects() == 0)
6690 // Determine if parens will need to be suggested in the diagnostic.
6691 bool NeedParens = false;
6692 if (D.getNumTypeObjects() != 0) {
6693 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6694 case DeclaratorChunk::Pointer:
6695 case DeclaratorChunk::Reference:
6696 case DeclaratorChunk::BlockPointer:
6697 case DeclaratorChunk::MemberPointer:
6698 case DeclaratorChunk::Pipe:
6701 case DeclaratorChunk::Array:
6702 case DeclaratorChunk::Function:
6703 case DeclaratorChunk::Paren:
6709 // Create a DeclaratorChunk for the inserted parens.
6710 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6711 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
6715 // Adding back the bracket info to the end of the Declarator.
6716 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6717 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6718 D.AddTypeInfo(Chunk, SourceLocation());
6721 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6722 // If parentheses are required, always suggest them.
6723 if (!D.getIdentifier() && !NeedParens)
6726 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
6728 // Generate the move bracket error message.
6729 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6730 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6733 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6734 << getLangOpts().CPlusPlus
6735 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6736 << FixItHint::CreateInsertion(EndLoc, ")")
6737 << FixItHint::CreateInsertionFromRange(
6738 EndLoc, CharSourceRange(BracketRange, true))
6739 << FixItHint::CreateRemoval(BracketRange);
6741 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6742 << getLangOpts().CPlusPlus
6743 << FixItHint::CreateInsertionFromRange(
6744 EndLoc, CharSourceRange(BracketRange, true))
6745 << FixItHint::CreateRemoval(BracketRange);
6749 /// [GNU] typeof-specifier:
6750 /// typeof ( expressions )
6751 /// typeof ( type-name )
6752 /// [GNU/C++] typeof unary-expression
6754 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6755 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6757 SourceLocation StartLoc = ConsumeToken();
6759 const bool hasParens = Tok.is(tok::l_paren);
6761 EnterExpressionEvaluationContext Unevaluated(
6762 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6763 Sema::ReuseLambdaContextDecl);
6767 SourceRange CastRange;
6768 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6769 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6771 DS.setTypeofParensRange(CastRange);
6773 if (CastRange.getEnd().isInvalid())
6774 // FIXME: Not accurate, the range gets one token more than it should.
6775 DS.SetRangeEnd(Tok.getLocation());
6777 DS.SetRangeEnd(CastRange.getEnd());
6781 DS.SetTypeSpecError();
6785 const char *PrevSpec = nullptr;
6787 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6788 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6790 Actions.getASTContext().getPrintingPolicy()))
6791 Diag(StartLoc, DiagID) << PrevSpec;
6795 // If we get here, the operand to the typeof was an expression.
6796 if (Operand.isInvalid()) {
6797 DS.SetTypeSpecError();
6801 // We might need to transform the operand if it is potentially evaluated.
6802 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6803 if (Operand.isInvalid()) {
6804 DS.SetTypeSpecError();
6808 const char *PrevSpec = nullptr;
6810 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6811 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6812 DiagID, Operand.get(),
6813 Actions.getASTContext().getPrintingPolicy()))
6814 Diag(StartLoc, DiagID) << PrevSpec;
6817 /// [C11] atomic-specifier:
6818 /// _Atomic ( type-name )
6820 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6821 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6822 "Not an atomic specifier");
6824 SourceLocation StartLoc = ConsumeToken();
6825 BalancedDelimiterTracker T(*this, tok::l_paren);
6826 if (T.consumeOpen())
6829 TypeResult Result = ParseTypeName();
6830 if (Result.isInvalid()) {
6831 SkipUntil(tok::r_paren, StopAtSemi);
6838 if (T.getCloseLocation().isInvalid())
6841 DS.setTypeofParensRange(T.getRange());
6842 DS.SetRangeEnd(T.getCloseLocation());
6844 const char *PrevSpec = nullptr;
6846 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6847 DiagID, Result.get(),
6848 Actions.getASTContext().getPrintingPolicy()))
6849 Diag(StartLoc, DiagID) << PrevSpec;
6852 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6853 /// from TryAltiVecVectorToken.
6854 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6855 Token Next = NextToken();
6856 switch (Next.getKind()) {
6857 default: return false;
6860 case tok::kw_signed:
6861 case tok::kw_unsigned:
6866 case tok::kw_double:
6868 case tok::kw___bool:
6869 case tok::kw___pixel:
6870 Tok.setKind(tok::kw___vector);
6872 case tok::identifier:
6873 if (Next.getIdentifierInfo() == Ident_pixel) {
6874 Tok.setKind(tok::kw___vector);
6877 if (Next.getIdentifierInfo() == Ident_bool) {
6878 Tok.setKind(tok::kw___vector);
6885 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6886 const char *&PrevSpec, unsigned &DiagID,
6888 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6889 if (Tok.getIdentifierInfo() == Ident_vector) {
6890 Token Next = NextToken();
6891 switch (Next.getKind()) {
6894 case tok::kw_signed:
6895 case tok::kw_unsigned:
6900 case tok::kw_double:
6902 case tok::kw___bool:
6903 case tok::kw___pixel:
6904 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6906 case tok::identifier:
6907 if (Next.getIdentifierInfo() == Ident_pixel) {
6908 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6911 if (Next.getIdentifierInfo() == Ident_bool) {
6912 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6919 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6920 DS.isTypeAltiVecVector()) {
6921 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6923 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6924 DS.isTypeAltiVecVector()) {
6925 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);