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 "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringSwitch.h"
33 using namespace clang;
35 //===----------------------------------------------------------------------===//
36 // C99 6.7: Declarations.
37 //===----------------------------------------------------------------------===//
40 /// type-name: [C99 6.7.6]
41 /// specifier-qualifier-list abstract-declarator[opt]
43 /// Called type-id in C++.
44 TypeResult Parser::ParseTypeName(SourceRange *Range,
45 DeclaratorContext Context,
48 ParsedAttributes *Attrs) {
49 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
50 if (DSC == DeclSpecContext::DSC_normal)
51 DSC = DeclSpecContext::DSC_type_specifier;
53 // Parse the common declaration-specifiers piece.
54 DeclSpec DS(AttrFactory);
56 DS.addAttributes(*Attrs);
57 ParseSpecifierQualifierList(DS, AS, DSC);
59 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
61 // Parse the abstract-declarator, if present.
62 Declarator DeclaratorInfo(DS, Context);
63 ParseDeclarator(DeclaratorInfo);
65 *Range = DeclaratorInfo.getSourceRange();
67 if (DeclaratorInfo.isInvalidType())
70 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
73 /// Normalizes an attribute name by dropping prefixed and suffixed __.
74 static StringRef normalizeAttrName(StringRef Name) {
75 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
76 return Name.drop_front(2).drop_back(2);
80 /// isAttributeLateParsed - Return true if the attribute has arguments that
81 /// require late parsing.
82 static bool isAttributeLateParsed(const IdentifierInfo &II) {
83 #define CLANG_ATTR_LATE_PARSED_LIST
84 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
85 #include "clang/Parse/AttrParserStringSwitches.inc"
87 #undef CLANG_ATTR_LATE_PARSED_LIST
90 /// ParseGNUAttributes - Parse a non-empty attributes list.
94 /// attributes attribute
97 /// '__attribute__' '(' '(' attribute-list ')' ')'
99 /// [GNU] attribute-list:
101 /// attribute_list ',' attrib
106 /// attrib-name '(' identifier ')'
107 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
108 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
110 /// [GNU] attrib-name:
116 /// Whether an attribute takes an 'identifier' is determined by the
117 /// attrib-name. GCC's behavior here is not worth imitating:
119 /// * In C mode, if the attribute argument list starts with an identifier
120 /// followed by a ',' or an ')', and the identifier doesn't resolve to
121 /// a type, it is parsed as an identifier. If the attribute actually
122 /// wanted an expression, it's out of luck (but it turns out that no
123 /// attributes work that way, because C constant expressions are very
125 /// * In C++ mode, if the attribute argument list starts with an identifier,
126 /// and the attribute *wants* an identifier, it is parsed as an identifier.
127 /// At block scope, any additional tokens between the identifier and the
128 /// ',' or ')' are ignored, otherwise they produce a parse error.
130 /// We follow the C++ model, but don't allow junk after the identifier.
131 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
132 SourceLocation *endLoc,
133 LateParsedAttrList *LateAttrs,
135 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
137 while (Tok.is(tok::kw___attribute)) {
139 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
141 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
144 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
145 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
148 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
150 // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
151 if (TryConsumeToken(tok::comma))
154 // Expect an identifier or declaration specifier (const, int, etc.)
155 if (Tok.isAnnotation())
157 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
161 SourceLocation AttrNameLoc = ConsumeToken();
163 if (Tok.isNot(tok::l_paren)) {
164 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
169 // Handle "parameterized" attributes
170 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
171 ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
172 SourceLocation(), ParsedAttr::AS_GNU, D);
176 // Handle attributes with arguments that require late parsing.
177 LateParsedAttribute *LA =
178 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
179 LateAttrs->push_back(LA);
181 // Attributes in a class are parsed at the end of the class, along
182 // with other late-parsed declarations.
183 if (!ClassStack.empty() && !LateAttrs->parseSoon())
184 getCurrentClass().LateParsedDeclarations.push_back(LA);
186 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
187 // recursively consumes balanced parens.
188 LA->Toks.push_back(Tok);
190 // Consume everything up to and including the matching right parens.
191 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
195 Eof.setLocation(Tok.getLocation());
196 LA->Toks.push_back(Eof);
199 if (ExpectAndConsume(tok::r_paren))
200 SkipUntil(tok::r_paren, StopAtSemi);
201 SourceLocation Loc = Tok.getLocation();
202 if (ExpectAndConsume(tok::r_paren))
203 SkipUntil(tok::r_paren, StopAtSemi);
209 /// Determine whether the given attribute has an identifier argument.
210 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
211 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
212 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
213 #include "clang/Parse/AttrParserStringSwitches.inc"
215 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
218 /// Determine whether the given attribute has a variadic identifier argument.
219 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
220 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
221 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
222 #include "clang/Parse/AttrParserStringSwitches.inc"
224 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
227 /// Determine whether the given attribute parses a type argument.
228 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
229 #define CLANG_ATTR_TYPE_ARG_LIST
230 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
231 #include "clang/Parse/AttrParserStringSwitches.inc"
233 #undef CLANG_ATTR_TYPE_ARG_LIST
236 /// Determine whether the given attribute requires parsing its arguments
237 /// in an unevaluated context or not.
238 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
239 #define CLANG_ATTR_ARG_CONTEXT_LIST
240 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
241 #include "clang/Parse/AttrParserStringSwitches.inc"
243 #undef CLANG_ATTR_ARG_CONTEXT_LIST
246 IdentifierLoc *Parser::ParseIdentifierLoc() {
247 assert(Tok.is(tok::identifier) && "expected an identifier");
248 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
250 Tok.getIdentifierInfo());
255 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
256 SourceLocation AttrNameLoc,
257 ParsedAttributes &Attrs,
258 SourceLocation *EndLoc,
259 IdentifierInfo *ScopeName,
260 SourceLocation ScopeLoc,
261 ParsedAttr::Syntax Syntax) {
262 BalancedDelimiterTracker Parens(*this, tok::l_paren);
263 Parens.consumeOpen();
266 if (Tok.isNot(tok::r_paren))
269 if (Parens.consumeClose())
276 Attrs.addNewTypeAttr(&AttrName,
277 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
278 ScopeName, ScopeLoc, T.get(), Syntax);
280 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
281 ScopeName, ScopeLoc, nullptr, 0, Syntax);
284 unsigned Parser::ParseAttributeArgsCommon(
285 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
286 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
287 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
288 // Ignore the left paren location for now.
292 if (Tok.is(tok::identifier)) {
293 // If this attribute wants an 'identifier' argument, make it so.
294 bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
295 attributeHasVariadicIdentifierArg(*AttrName);
296 ParsedAttr::Kind AttrKind =
297 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
299 // If we don't know how to parse this attribute, but this is the only
300 // token in this argument, assume it's meant to be an identifier.
301 if (AttrKind == ParsedAttr::UnknownAttribute ||
302 AttrKind == ParsedAttr::IgnoredAttribute) {
303 const Token &Next = NextToken();
304 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
308 ArgExprs.push_back(ParseIdentifierLoc());
311 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
313 if (!ArgExprs.empty())
316 // Parse the non-empty comma-separated list of expressions.
319 if (Tok.is(tok::identifier) &&
320 attributeHasVariadicIdentifierArg(*AttrName)) {
321 ArgExprs.push_back(ParseIdentifierLoc());
323 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
324 EnterExpressionEvaluationContext Unevaluated(
326 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
327 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
330 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
331 if (ArgExpr.isInvalid()) {
332 SkipUntil(tok::r_paren, StopAtSemi);
335 ArgExprs.push_back(ArgExpr.get());
337 // Eat the comma, move to the next argument
338 } while (TryConsumeToken(tok::comma));
341 SourceLocation RParen = Tok.getLocation();
342 if (!ExpectAndConsume(tok::r_paren)) {
343 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
344 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
345 ArgExprs.data(), ArgExprs.size(), Syntax);
351 return static_cast<unsigned>(ArgExprs.size());
354 /// Parse the arguments to a parameterized GNU attribute or
355 /// a C++11 attribute in "gnu" namespace.
356 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
357 SourceLocation AttrNameLoc,
358 ParsedAttributes &Attrs,
359 SourceLocation *EndLoc,
360 IdentifierInfo *ScopeName,
361 SourceLocation ScopeLoc,
362 ParsedAttr::Syntax Syntax,
365 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
367 ParsedAttr::Kind AttrKind =
368 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
370 if (AttrKind == ParsedAttr::AT_Availability) {
371 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
374 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
375 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
376 ScopeName, ScopeLoc, Syntax);
378 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
379 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
380 ScopeName, ScopeLoc, Syntax);
382 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
383 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
384 ScopeName, ScopeLoc, Syntax);
386 } else if (attributeIsTypeArgAttr(*AttrName)) {
387 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
392 // These may refer to the function arguments, but need to be parsed early to
393 // participate in determining whether it's a redeclaration.
394 llvm::Optional<ParseScope> PrototypeScope;
395 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
396 D && D->isFunctionDeclarator()) {
397 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
398 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
399 Scope::FunctionDeclarationScope |
401 for (unsigned i = 0; i != FTI.NumParams; ++i) {
402 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
403 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
407 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
411 unsigned Parser::ParseClangAttributeArgs(
412 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
413 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
414 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
415 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
417 ParsedAttr::Kind AttrKind =
418 ParsedAttr::getKind(AttrName, ScopeName, Syntax);
422 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
423 ScopeName, ScopeLoc, Syntax);
424 case ParsedAttr::AT_ExternalSourceSymbol:
425 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
426 ScopeName, ScopeLoc, Syntax);
428 case ParsedAttr::AT_Availability:
429 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
432 case ParsedAttr::AT_ObjCBridgeRelated:
433 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
434 ScopeName, ScopeLoc, Syntax);
436 case ParsedAttr::AT_TypeTagForDatatype:
437 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
438 ScopeName, ScopeLoc, Syntax);
441 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
444 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
445 SourceLocation AttrNameLoc,
446 ParsedAttributes &Attrs) {
447 // If the attribute isn't known, we will not attempt to parse any
449 if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
450 getTargetInfo(), getLangOpts())) {
451 // Eat the left paren, then skip to the ending right paren.
453 SkipUntil(tok::r_paren);
457 SourceLocation OpenParenLoc = Tok.getLocation();
459 if (AttrName->getName() == "property") {
460 // The property declspec is more complex in that it can take one or two
461 // assignment expressions as a parameter, but the lhs of the assignment
462 // must be named get or put.
464 BalancedDelimiterTracker T(*this, tok::l_paren);
465 T.expectAndConsume(diag::err_expected_lparen_after,
466 AttrName->getNameStart(), tok::r_paren);
471 AK_Get = 1 // indices into AccessorNames
473 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
474 bool HasInvalidAccessor = false;
476 // Parse the accessor specifications.
478 // Stop if this doesn't look like an accessor spec.
479 if (!Tok.is(tok::identifier)) {
480 // If the user wrote a completely empty list, use a special diagnostic.
481 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
482 AccessorNames[AK_Put] == nullptr &&
483 AccessorNames[AK_Get] == nullptr) {
484 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
488 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
493 SourceLocation KindLoc = Tok.getLocation();
494 StringRef KindStr = Tok.getIdentifierInfo()->getName();
495 if (KindStr == "get") {
497 } else if (KindStr == "put") {
500 // Recover from the common mistake of using 'set' instead of 'put'.
501 } else if (KindStr == "set") {
502 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
503 << FixItHint::CreateReplacement(KindLoc, "put");
506 // Handle the mistake of forgetting the accessor kind by skipping
508 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
509 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
511 HasInvalidAccessor = true;
512 goto next_property_accessor;
514 // Otherwise, complain about the unknown accessor kind.
516 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
517 HasInvalidAccessor = true;
520 // Try to keep parsing unless it doesn't look like an accessor spec.
521 if (!NextToken().is(tok::equal))
525 // Consume the identifier.
529 if (!TryConsumeToken(tok::equal)) {
530 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
535 // Expect the method name.
536 if (!Tok.is(tok::identifier)) {
537 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
541 if (Kind == AK_Invalid) {
542 // Just drop invalid accessors.
543 } else if (AccessorNames[Kind] != nullptr) {
544 // Complain about the repeated accessor, ignore it, and keep parsing.
545 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
547 AccessorNames[Kind] = Tok.getIdentifierInfo();
551 next_property_accessor:
552 // Keep processing accessors until we run out.
553 if (TryConsumeToken(tok::comma))
556 // If we run into the ')', stop without consuming it.
557 if (Tok.is(tok::r_paren))
560 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
564 // Only add the property attribute if it was well-formed.
565 if (!HasInvalidAccessor)
566 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
567 AccessorNames[AK_Get], AccessorNames[AK_Put],
568 ParsedAttr::AS_Declspec);
570 return !HasInvalidAccessor;
574 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
575 SourceLocation(), ParsedAttr::AS_Declspec);
577 // If this attribute's args were parsed, and it was expected to have
578 // arguments but none were provided, emit a diagnostic.
579 if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
580 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
586 /// [MS] decl-specifier:
587 /// __declspec ( extended-decl-modifier-seq )
589 /// [MS] extended-decl-modifier-seq:
590 /// extended-decl-modifier[opt]
591 /// extended-decl-modifier extended-decl-modifier-seq
592 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
593 SourceLocation *End) {
594 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
595 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
597 while (Tok.is(tok::kw___declspec)) {
599 BalancedDelimiterTracker T(*this, tok::l_paren);
600 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
604 // An empty declspec is perfectly legal and should not warn. Additionally,
605 // you can specify multiple attributes per declspec.
606 while (Tok.isNot(tok::r_paren)) {
607 // Attribute not present.
608 if (TryConsumeToken(tok::comma))
611 // We expect either a well-known identifier or a generic string. Anything
612 // else is a malformed declspec.
613 bool IsString = Tok.getKind() == tok::string_literal;
614 if (!IsString && Tok.getKind() != tok::identifier &&
615 Tok.getKind() != tok::kw_restrict) {
616 Diag(Tok, diag::err_ms_declspec_type);
621 IdentifierInfo *AttrName;
622 SourceLocation AttrNameLoc;
624 SmallString<8> StrBuffer;
625 bool Invalid = false;
626 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
631 AttrName = PP.getIdentifierInfo(Str);
632 AttrNameLoc = ConsumeStringToken();
634 AttrName = Tok.getIdentifierInfo();
635 AttrNameLoc = ConsumeToken();
638 bool AttrHandled = false;
640 // Parse attribute arguments.
641 if (Tok.is(tok::l_paren))
642 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
643 else if (AttrName->getName() == "property")
644 // The property attribute must have an argument list.
645 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
646 << AttrName->getName();
649 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
650 ParsedAttr::AS_Declspec);
654 *End = T.getCloseLocation();
658 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
659 // Treat these like attributes
661 switch (Tok.getKind()) {
662 case tok::kw___fastcall:
663 case tok::kw___stdcall:
664 case tok::kw___thiscall:
665 case tok::kw___regcall:
666 case tok::kw___cdecl:
667 case tok::kw___vectorcall:
668 case tok::kw___ptr64:
670 case tok::kw___ptr32:
672 case tok::kw___uptr: {
673 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
674 SourceLocation AttrNameLoc = ConsumeToken();
675 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
676 ParsedAttr::AS_Keyword);
685 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
686 SourceLocation StartLoc = Tok.getLocation();
687 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
689 if (EndLoc.isValid()) {
690 SourceRange Range(StartLoc, EndLoc);
691 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
695 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
696 SourceLocation EndLoc;
699 switch (Tok.getKind()) {
701 case tok::kw_volatile:
702 case tok::kw___fastcall:
703 case tok::kw___stdcall:
704 case tok::kw___thiscall:
705 case tok::kw___cdecl:
706 case tok::kw___vectorcall:
707 case tok::kw___ptr32:
708 case tok::kw___ptr64:
710 case tok::kw___unaligned:
713 EndLoc = ConsumeToken();
721 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
722 // Treat these like attributes
723 while (Tok.is(tok::kw___pascal)) {
724 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
725 SourceLocation AttrNameLoc = ConsumeToken();
726 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
727 ParsedAttr::AS_Keyword);
731 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
732 // Treat these like attributes
733 while (Tok.is(tok::kw___kernel)) {
734 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
735 SourceLocation AttrNameLoc = ConsumeToken();
736 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
737 ParsedAttr::AS_Keyword);
741 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
742 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
743 SourceLocation AttrNameLoc = Tok.getLocation();
744 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
745 ParsedAttr::AS_Keyword);
748 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
749 // Treat these like attributes, even though they're type specifiers.
751 switch (Tok.getKind()) {
752 case tok::kw__Nonnull:
753 case tok::kw__Nullable:
754 case tok::kw__Null_unspecified: {
755 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
756 SourceLocation AttrNameLoc = ConsumeToken();
757 if (!getLangOpts().ObjC1)
758 Diag(AttrNameLoc, diag::ext_nullability)
760 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
761 ParsedAttr::AS_Keyword);
770 static bool VersionNumberSeparator(const char Separator) {
771 return (Separator == '.' || Separator == '_');
774 /// Parse a version number.
778 /// simple-integer '.' simple-integer
779 /// simple-integer '_' simple-integer
780 /// simple-integer '.' simple-integer '.' simple-integer
781 /// simple-integer '_' simple-integer '_' simple-integer
782 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
783 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
785 if (!Tok.is(tok::numeric_constant)) {
786 Diag(Tok, diag::err_expected_version);
787 SkipUntil(tok::comma, tok::r_paren,
788 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
789 return VersionTuple();
792 // Parse the major (and possibly minor and subminor) versions, which
793 // are stored in the numeric constant. We utilize a quirk of the
794 // lexer, which is that it handles something like 1.2.3 as a single
795 // numeric constant, rather than two separate tokens.
796 SmallString<512> Buffer;
797 Buffer.resize(Tok.getLength()+1);
798 const char *ThisTokBegin = &Buffer[0];
800 // Get the spelling of the token, which eliminates trigraphs, etc.
801 bool Invalid = false;
802 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
804 return VersionTuple();
806 // Parse the major version.
807 unsigned AfterMajor = 0;
809 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
810 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
814 if (AfterMajor == 0) {
815 Diag(Tok, diag::err_expected_version);
816 SkipUntil(tok::comma, tok::r_paren,
817 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
818 return VersionTuple();
821 if (AfterMajor == ActualLength) {
824 // We only had a single version component.
826 Diag(Tok, diag::err_zero_version);
827 return VersionTuple();
830 return VersionTuple(Major);
833 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
834 if (!VersionNumberSeparator(AfterMajorSeparator)
835 || (AfterMajor + 1 == ActualLength)) {
836 Diag(Tok, diag::err_expected_version);
837 SkipUntil(tok::comma, tok::r_paren,
838 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
839 return VersionTuple();
842 // Parse the minor version.
843 unsigned AfterMinor = AfterMajor + 1;
845 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
846 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
850 if (AfterMinor == ActualLength) {
853 // We had major.minor.
854 if (Major == 0 && Minor == 0) {
855 Diag(Tok, diag::err_zero_version);
856 return VersionTuple();
859 return VersionTuple(Major, Minor);
862 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
863 // If what follows is not a '.' or '_', we have a problem.
864 if (!VersionNumberSeparator(AfterMinorSeparator)) {
865 Diag(Tok, diag::err_expected_version);
866 SkipUntil(tok::comma, tok::r_paren,
867 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
868 return VersionTuple();
871 // Warn if separators, be it '.' or '_', do not match.
872 if (AfterMajorSeparator != AfterMinorSeparator)
873 Diag(Tok, diag::warn_expected_consistent_version_separator);
875 // Parse the subminor version.
876 unsigned AfterSubminor = AfterMinor + 1;
877 unsigned Subminor = 0;
878 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
879 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
883 if (AfterSubminor != ActualLength) {
884 Diag(Tok, diag::err_expected_version);
885 SkipUntil(tok::comma, tok::r_paren,
886 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
887 return VersionTuple();
890 return VersionTuple(Major, Minor, Subminor);
893 /// Parse the contents of the "availability" attribute.
895 /// availability-attribute:
896 /// 'availability' '(' platform ',' opt-strict version-arg-list,
897 /// opt-replacement, opt-message')'
905 /// version-arg-list:
907 /// version-arg ',' version-arg-list
910 /// 'introduced' '=' version
911 /// 'deprecated' '=' version
912 /// 'obsoleted' = version
915 /// 'replacement' '=' <string>
917 /// 'message' '=' <string>
918 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
919 SourceLocation AvailabilityLoc,
920 ParsedAttributes &attrs,
921 SourceLocation *endLoc,
922 IdentifierInfo *ScopeName,
923 SourceLocation ScopeLoc,
924 ParsedAttr::Syntax Syntax) {
925 enum { Introduced, Deprecated, Obsoleted, Unknown };
926 AvailabilityChange Changes[Unknown];
927 ExprResult MessageExpr, ReplacementExpr;
930 BalancedDelimiterTracker T(*this, tok::l_paren);
931 if (T.consumeOpen()) {
932 Diag(Tok, diag::err_expected) << tok::l_paren;
936 // Parse the platform name.
937 if (Tok.isNot(tok::identifier)) {
938 Diag(Tok, diag::err_availability_expected_platform);
939 SkipUntil(tok::r_paren, StopAtSemi);
942 IdentifierLoc *Platform = ParseIdentifierLoc();
943 if (const IdentifierInfo *const Ident = Platform->Ident) {
944 // Canonicalize platform name from "macosx" to "macos".
945 if (Ident->getName() == "macosx")
946 Platform->Ident = PP.getIdentifierInfo("macos");
947 // Canonicalize platform name from "macosx_app_extension" to
948 // "macos_app_extension".
949 else if (Ident->getName() == "macosx_app_extension")
950 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
952 Platform->Ident = PP.getIdentifierInfo(
953 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
956 // Parse the ',' following the platform name.
957 if (ExpectAndConsume(tok::comma)) {
958 SkipUntil(tok::r_paren, StopAtSemi);
962 // If we haven't grabbed the pointers for the identifiers
963 // "introduced", "deprecated", and "obsoleted", do so now.
964 if (!Ident_introduced) {
965 Ident_introduced = PP.getIdentifierInfo("introduced");
966 Ident_deprecated = PP.getIdentifierInfo("deprecated");
967 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
968 Ident_unavailable = PP.getIdentifierInfo("unavailable");
969 Ident_message = PP.getIdentifierInfo("message");
970 Ident_strict = PP.getIdentifierInfo("strict");
971 Ident_replacement = PP.getIdentifierInfo("replacement");
974 // Parse the optional "strict", the optional "replacement" and the set of
975 // introductions/deprecations/removals.
976 SourceLocation UnavailableLoc, StrictLoc;
978 if (Tok.isNot(tok::identifier)) {
979 Diag(Tok, diag::err_availability_expected_change);
980 SkipUntil(tok::r_paren, StopAtSemi);
983 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
984 SourceLocation KeywordLoc = ConsumeToken();
986 if (Keyword == Ident_strict) {
987 if (StrictLoc.isValid()) {
988 Diag(KeywordLoc, diag::err_availability_redundant)
989 << Keyword << SourceRange(StrictLoc);
991 StrictLoc = KeywordLoc;
995 if (Keyword == Ident_unavailable) {
996 if (UnavailableLoc.isValid()) {
997 Diag(KeywordLoc, diag::err_availability_redundant)
998 << Keyword << SourceRange(UnavailableLoc);
1000 UnavailableLoc = KeywordLoc;
1004 if (Tok.isNot(tok::equal)) {
1005 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1006 SkipUntil(tok::r_paren, StopAtSemi);
1010 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1011 if (Tok.isNot(tok::string_literal)) {
1012 Diag(Tok, diag::err_expected_string_literal)
1013 << /*Source='availability attribute'*/2;
1014 SkipUntil(tok::r_paren, StopAtSemi);
1017 if (Keyword == Ident_message)
1018 MessageExpr = ParseStringLiteralExpression();
1020 ReplacementExpr = ParseStringLiteralExpression();
1021 // Also reject wide string literals.
1022 if (StringLiteral *MessageStringLiteral =
1023 cast_or_null<StringLiteral>(MessageExpr.get())) {
1024 if (MessageStringLiteral->getCharByteWidth() != 1) {
1025 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1026 diag::err_expected_string_literal)
1027 << /*Source='availability attribute'*/ 2;
1028 SkipUntil(tok::r_paren, StopAtSemi);
1032 if (Keyword == Ident_message)
1038 // Special handling of 'NA' only when applied to introduced or
1040 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1041 Tok.is(tok::identifier)) {
1042 IdentifierInfo *NA = Tok.getIdentifierInfo();
1043 if (NA->getName() == "NA") {
1045 if (Keyword == Ident_introduced)
1046 UnavailableLoc = KeywordLoc;
1051 SourceRange VersionRange;
1052 VersionTuple Version = ParseVersionTuple(VersionRange);
1054 if (Version.empty()) {
1055 SkipUntil(tok::r_paren, StopAtSemi);
1060 if (Keyword == Ident_introduced)
1062 else if (Keyword == Ident_deprecated)
1064 else if (Keyword == Ident_obsoleted)
1069 if (Index < Unknown) {
1070 if (!Changes[Index].KeywordLoc.isInvalid()) {
1071 Diag(KeywordLoc, diag::err_availability_redundant)
1073 << SourceRange(Changes[Index].KeywordLoc,
1074 Changes[Index].VersionRange.getEnd());
1077 Changes[Index].KeywordLoc = KeywordLoc;
1078 Changes[Index].Version = Version;
1079 Changes[Index].VersionRange = VersionRange;
1081 Diag(KeywordLoc, diag::err_availability_unknown_change)
1082 << Keyword << VersionRange;
1085 } while (TryConsumeToken(tok::comma));
1088 if (T.consumeClose())
1092 *endLoc = T.getCloseLocation();
1094 // The 'unavailable' availability cannot be combined with any other
1095 // availability changes. Make sure that hasn't happened.
1096 if (UnavailableLoc.isValid()) {
1097 bool Complained = false;
1098 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1099 if (Changes[Index].KeywordLoc.isValid()) {
1101 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1102 << SourceRange(Changes[Index].KeywordLoc,
1103 Changes[Index].VersionRange.getEnd());
1107 // Clear out the availability.
1108 Changes[Index] = AvailabilityChange();
1113 // Record this attribute
1114 attrs.addNew(&Availability,
1115 SourceRange(AvailabilityLoc, T.getCloseLocation()),
1116 ScopeName, ScopeLoc,
1118 Changes[Introduced],
1119 Changes[Deprecated],
1121 UnavailableLoc, MessageExpr.get(),
1122 Syntax, StrictLoc, ReplacementExpr.get());
1125 /// Parse the contents of the "external_source_symbol" attribute.
1127 /// external-source-symbol-attribute:
1128 /// 'external_source_symbol' '(' keyword-arg-list ')'
1130 /// keyword-arg-list:
1132 /// keyword-arg ',' keyword-arg-list
1135 /// 'language' '=' <string>
1136 /// 'defined_in' '=' <string>
1137 /// 'generated_declaration'
1138 void Parser::ParseExternalSourceSymbolAttribute(
1139 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1140 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1141 SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1143 BalancedDelimiterTracker T(*this, tok::l_paren);
1144 if (T.expectAndConsume())
1147 // Initialize the pointers for the keyword identifiers when required.
1148 if (!Ident_language) {
1149 Ident_language = PP.getIdentifierInfo("language");
1150 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1151 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1154 ExprResult Language;
1155 bool HasLanguage = false;
1156 ExprResult DefinedInExpr;
1157 bool HasDefinedIn = false;
1158 IdentifierLoc *GeneratedDeclaration = nullptr;
1160 // Parse the language/defined_in/generated_declaration keywords
1162 if (Tok.isNot(tok::identifier)) {
1163 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1164 SkipUntil(tok::r_paren, StopAtSemi);
1168 SourceLocation KeywordLoc = Tok.getLocation();
1169 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1170 if (Keyword == Ident_generated_declaration) {
1171 if (GeneratedDeclaration) {
1172 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1173 SkipUntil(tok::r_paren, StopAtSemi);
1176 GeneratedDeclaration = ParseIdentifierLoc();
1180 if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1181 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1182 SkipUntil(tok::r_paren, StopAtSemi);
1187 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1188 Keyword->getName())) {
1189 SkipUntil(tok::r_paren, StopAtSemi);
1193 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1194 if (Keyword == Ident_language)
1197 HasDefinedIn = true;
1199 if (Tok.isNot(tok::string_literal)) {
1200 Diag(Tok, diag::err_expected_string_literal)
1201 << /*Source='external_source_symbol attribute'*/ 3
1202 << /*language | source container*/ (Keyword != Ident_language);
1203 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1206 if (Keyword == Ident_language) {
1208 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1210 ParseStringLiteralExpression();
1213 Language = ParseStringLiteralExpression();
1215 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1217 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1219 ParseStringLiteralExpression();
1222 DefinedInExpr = ParseStringLiteralExpression();
1224 } while (TryConsumeToken(tok::comma));
1227 if (T.consumeClose())
1230 *EndLoc = T.getCloseLocation();
1232 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1233 GeneratedDeclaration};
1234 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1235 ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1238 /// Parse the contents of the "objc_bridge_related" attribute.
1239 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1243 /// opt-class_method:
1244 /// Identifier: | <empty>
1246 /// opt-instance_method:
1247 /// Identifier | <empty>
1249 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1250 SourceLocation ObjCBridgeRelatedLoc,
1251 ParsedAttributes &attrs,
1252 SourceLocation *endLoc,
1253 IdentifierInfo *ScopeName,
1254 SourceLocation ScopeLoc,
1255 ParsedAttr::Syntax Syntax) {
1257 BalancedDelimiterTracker T(*this, tok::l_paren);
1258 if (T.consumeOpen()) {
1259 Diag(Tok, diag::err_expected) << tok::l_paren;
1263 // Parse the related class name.
1264 if (Tok.isNot(tok::identifier)) {
1265 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1266 SkipUntil(tok::r_paren, StopAtSemi);
1269 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1270 if (ExpectAndConsume(tok::comma)) {
1271 SkipUntil(tok::r_paren, StopAtSemi);
1275 // Parse class method name. It's non-optional in the sense that a trailing
1276 // comma is required, but it can be the empty string, and then we record a
1278 IdentifierLoc *ClassMethod = nullptr;
1279 if (Tok.is(tok::identifier)) {
1280 ClassMethod = ParseIdentifierLoc();
1281 if (!TryConsumeToken(tok::colon)) {
1282 Diag(Tok, diag::err_objcbridge_related_selector_name);
1283 SkipUntil(tok::r_paren, StopAtSemi);
1287 if (!TryConsumeToken(tok::comma)) {
1288 if (Tok.is(tok::colon))
1289 Diag(Tok, diag::err_objcbridge_related_selector_name);
1291 Diag(Tok, diag::err_expected) << tok::comma;
1292 SkipUntil(tok::r_paren, StopAtSemi);
1296 // Parse instance method name. Also non-optional but empty string is
1298 IdentifierLoc *InstanceMethod = nullptr;
1299 if (Tok.is(tok::identifier))
1300 InstanceMethod = ParseIdentifierLoc();
1301 else if (Tok.isNot(tok::r_paren)) {
1302 Diag(Tok, diag::err_expected) << tok::r_paren;
1303 SkipUntil(tok::r_paren, StopAtSemi);
1308 if (T.consumeClose())
1312 *endLoc = T.getCloseLocation();
1314 // Record this attribute
1315 attrs.addNew(&ObjCBridgeRelated,
1316 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1317 ScopeName, ScopeLoc,
1324 // Late Parsed Attributes:
1325 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1327 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1329 void Parser::LateParsedClass::ParseLexedAttributes() {
1330 Self->ParseLexedAttributes(*Class);
1333 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1334 Self->ParseLexedAttribute(*this, true, false);
1337 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1338 /// scope appropriately.
1339 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1340 // Deal with templates
1341 // FIXME: Test cases to make sure this does the right thing for templates.
1342 bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1343 ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1345 if (HasTemplateScope)
1346 Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1348 // Set or update the scope flags.
1349 bool AlreadyHasClassScope = Class.TopLevelClass;
1350 unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1351 ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1352 ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1354 // Enter the scope of nested classes
1355 if (!AlreadyHasClassScope)
1356 Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1357 Class.TagOrTemplate);
1358 if (!Class.LateParsedDeclarations.empty()) {
1359 for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1360 Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1364 if (!AlreadyHasClassScope)
1365 Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1366 Class.TagOrTemplate);
1369 /// Parse all attributes in LAs, and attach them to Decl D.
1370 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1371 bool EnterScope, bool OnDefinition) {
1372 assert(LAs.parseSoon() &&
1373 "Attribute list should be marked for immediate parsing.");
1374 for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1377 ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1383 /// Finish parsing an attribute for which parsing was delayed.
1384 /// This will be called at the end of parsing a class declaration
1385 /// for each LateParsedAttribute. We consume the saved tokens and
1386 /// create an attribute with the arguments filled in. We add this
1387 /// to the Attribute list for the decl.
1388 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1389 bool EnterScope, bool OnDefinition) {
1390 // Create a fake EOF so that attribute parsing won't go off the end of the
1393 AttrEnd.startToken();
1394 AttrEnd.setKind(tok::eof);
1395 AttrEnd.setLocation(Tok.getLocation());
1396 AttrEnd.setEofData(LA.Toks.data());
1397 LA.Toks.push_back(AttrEnd);
1399 // Append the current token at the end of the new token stream so that it
1400 // doesn't get lost.
1401 LA.Toks.push_back(Tok);
1402 PP.EnterTokenStream(LA.Toks, true);
1403 // Consume the previously pushed token.
1404 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1406 ParsedAttributes Attrs(AttrFactory);
1407 SourceLocation endLoc;
1409 if (LA.Decls.size() > 0) {
1410 Decl *D = LA.Decls[0];
1411 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1412 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1414 // Allow 'this' within late-parsed attributes.
1415 Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
1416 ND && ND->isCXXInstanceMember());
1418 if (LA.Decls.size() == 1) {
1419 // If the Decl is templatized, add template parameters to scope.
1420 bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1421 ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1422 if (HasTemplateScope)
1423 Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1425 // If the Decl is on a function, add function parameters to the scope.
1426 bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1428 this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1431 Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1433 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1434 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1438 Actions.ActOnExitFunctionContext();
1439 FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1441 if (HasTemplateScope) {
1445 // If there are multiple decls, then the decl cannot be within the
1447 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1448 nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1452 Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1455 if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1456 Attrs.begin()->isKnownToGCC())
1457 Diag(Tok, diag::warn_attribute_on_function_definition)
1460 for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1461 Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1463 // Due to a parsing error, we either went over the cached tokens or
1464 // there are still cached tokens left, so we skip the leftover tokens.
1465 while (Tok.isNot(tok::eof))
1468 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1472 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1473 SourceLocation AttrNameLoc,
1474 ParsedAttributes &Attrs,
1475 SourceLocation *EndLoc,
1476 IdentifierInfo *ScopeName,
1477 SourceLocation ScopeLoc,
1478 ParsedAttr::Syntax Syntax) {
1479 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1481 BalancedDelimiterTracker T(*this, tok::l_paren);
1484 if (Tok.isNot(tok::identifier)) {
1485 Diag(Tok, diag::err_expected) << tok::identifier;
1489 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1491 if (ExpectAndConsume(tok::comma)) {
1496 SourceRange MatchingCTypeRange;
1497 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1498 if (MatchingCType.isInvalid()) {
1503 bool LayoutCompatible = false;
1504 bool MustBeNull = false;
1505 while (TryConsumeToken(tok::comma)) {
1506 if (Tok.isNot(tok::identifier)) {
1507 Diag(Tok, diag::err_expected) << tok::identifier;
1511 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1512 if (Flag->isStr("layout_compatible"))
1513 LayoutCompatible = true;
1514 else if (Flag->isStr("must_be_null"))
1517 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1521 ConsumeToken(); // consume flag
1524 if (!T.consumeClose()) {
1525 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1526 ArgumentKind, MatchingCType.get(),
1527 LayoutCompatible, MustBeNull, Syntax);
1531 *EndLoc = T.getCloseLocation();
1534 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1535 /// of a C++11 attribute-specifier in a location where an attribute is not
1536 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1539 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1540 /// this doesn't appear to actually be an attribute-specifier, and the caller
1541 /// should try to parse it.
1542 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1543 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1545 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1546 case CAK_NotAttributeSpecifier:
1547 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1550 case CAK_InvalidAttributeSpecifier:
1551 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1554 case CAK_AttributeSpecifier:
1555 // Parse and discard the attributes.
1556 SourceLocation BeginLoc = ConsumeBracket();
1558 SkipUntil(tok::r_square);
1559 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1560 SourceLocation EndLoc = ConsumeBracket();
1561 Diag(BeginLoc, diag::err_attributes_not_allowed)
1562 << SourceRange(BeginLoc, EndLoc);
1565 llvm_unreachable("All cases handled above.");
1568 /// We have found the opening square brackets of a C++11
1569 /// attribute-specifier in a location where an attribute is not permitted, but
1570 /// we know where the attributes ought to be written. Parse them anyway, and
1571 /// provide a fixit moving them to the right place.
1572 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1573 SourceLocation CorrectLocation) {
1574 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1575 Tok.is(tok::kw_alignas));
1577 // Consume the attributes.
1578 SourceLocation Loc = Tok.getLocation();
1579 ParseCXX11Attributes(Attrs);
1580 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1581 // FIXME: use err_attributes_misplaced
1582 Diag(Loc, diag::err_attributes_not_allowed)
1583 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1584 << FixItHint::CreateRemoval(AttrRange);
1587 void Parser::DiagnoseProhibitedAttributes(
1588 const SourceRange &Range, const SourceLocation CorrectLocation) {
1589 if (CorrectLocation.isValid()) {
1590 CharSourceRange AttrRange(Range, true);
1591 Diag(CorrectLocation, diag::err_attributes_misplaced)
1592 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1593 << FixItHint::CreateRemoval(AttrRange);
1595 Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1598 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1600 for (const ParsedAttr &AL : Attrs) {
1601 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1603 if (AL.getKind() == ParsedAttr::UnknownAttribute)
1604 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
1606 Diag(AL.getLoc(), DiagID) << AL.getName();
1612 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1613 // applies to var, not the type Foo.
1614 // As an exception to the rule, __declspec(align(...)) before the
1615 // class-key affects the type instead of the variable.
1616 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1618 // This function moves attributes that should apply to the type off DS to Attrs.
1619 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1621 Sema::TagUseKind TUK) {
1622 if (TUK == Sema::TUK_Reference)
1625 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1627 for (ParsedAttr &AL : DS.getAttributes()) {
1628 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1629 AL.isDeclspecAttribute()) ||
1630 AL.isMicrosoftAttribute())
1631 ToBeMoved.push_back(&AL);
1634 for (ParsedAttr *AL : ToBeMoved) {
1635 DS.getAttributes().remove(AL);
1640 /// ParseDeclaration - Parse a full 'declaration', which consists of
1641 /// declaration-specifiers, some number of declarators, and a semicolon.
1642 /// 'Context' should be a DeclaratorContext value. This returns the
1643 /// location of the semicolon in DeclEnd.
1645 /// declaration: [C99 6.7]
1646 /// block-declaration ->
1647 /// simple-declaration
1649 /// [C++] template-declaration
1650 /// [C++] namespace-definition
1651 /// [C++] using-directive
1652 /// [C++] using-declaration
1653 /// [C++11/C11] static_assert-declaration
1654 /// others... [FIXME]
1656 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1657 SourceLocation &DeclEnd,
1658 ParsedAttributesWithRange &attrs) {
1659 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1660 // Must temporarily exit the objective-c container scope for
1661 // parsing c none objective-c decls.
1662 ObjCDeclContextSwitch ObjCDC(*this);
1664 Decl *SingleDecl = nullptr;
1665 switch (Tok.getKind()) {
1666 case tok::kw_template:
1667 case tok::kw_export:
1668 ProhibitAttributes(attrs);
1669 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1671 case tok::kw_inline:
1672 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1673 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1674 ProhibitAttributes(attrs);
1675 SourceLocation InlineLoc = ConsumeToken();
1676 return ParseNamespace(Context, DeclEnd, InlineLoc);
1678 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
1680 case tok::kw_namespace:
1681 ProhibitAttributes(attrs);
1682 return ParseNamespace(Context, DeclEnd);
1684 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1686 case tok::kw_static_assert:
1687 case tok::kw__Static_assert:
1688 ProhibitAttributes(attrs);
1689 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1692 return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
1695 // This routine returns a DeclGroup, if the thing we parsed only contains a
1696 // single decl, convert it now.
1697 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1700 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1701 /// declaration-specifiers init-declarator-list[opt] ';'
1702 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1703 /// init-declarator-list ';'
1704 ///[C90/C++]init-declarator-list ';' [TODO]
1705 /// [OMP] threadprivate-directive [TODO]
1707 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1708 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1710 /// If RequireSemi is false, this does not check for a ';' at the end of the
1711 /// declaration. If it is true, it checks for and eats it.
1713 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1714 /// of a simple-declaration. If we find that we are, we also parse the
1715 /// for-range-initializer, and place it here.
1716 Parser::DeclGroupPtrTy
1717 Parser::ParseSimpleDeclaration(DeclaratorContext Context,
1718 SourceLocation &DeclEnd,
1719 ParsedAttributesWithRange &Attrs,
1720 bool RequireSemi, ForRangeInit *FRI) {
1721 // Parse the common declaration-specifiers piece.
1722 ParsingDeclSpec DS(*this);
1724 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1725 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1727 // If we had a free-standing type definition with a missing semicolon, we
1728 // may get this far before the problem becomes obvious.
1729 if (DS.hasTagDefinition() &&
1730 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1733 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1734 // declaration-specifiers init-declarator-list[opt] ';'
1735 if (Tok.is(tok::semi)) {
1736 ProhibitAttributes(Attrs);
1737 DeclEnd = Tok.getLocation();
1738 if (RequireSemi) ConsumeToken();
1739 RecordDecl *AnonRecord = nullptr;
1740 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1742 DS.complete(TheDecl);
1744 Decl* decls[] = {AnonRecord, TheDecl};
1745 return Actions.BuildDeclaratorGroup(decls);
1747 return Actions.ConvertDeclToDeclGroup(TheDecl);
1750 DS.takeAttributesFrom(Attrs);
1751 return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1754 /// Returns true if this might be the start of a declarator, or a common typo
1755 /// for a declarator.
1756 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1757 switch (Tok.getKind()) {
1758 case tok::annot_cxxscope:
1759 case tok::annot_template_id:
1761 case tok::code_completion:
1762 case tok::coloncolon:
1764 case tok::kw___attribute:
1765 case tok::kw_operator:
1772 return getLangOpts().CPlusPlus;
1774 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1775 return Context == DeclaratorContext::MemberContext &&
1776 getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1778 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1779 return Context == DeclaratorContext::MemberContext ||
1780 getLangOpts().CPlusPlus;
1782 case tok::identifier:
1783 switch (NextToken().getKind()) {
1784 case tok::code_completion:
1785 case tok::coloncolon:
1788 case tok::equalequal: // Might be a typo for '='.
1789 case tok::kw_alignas:
1791 case tok::kw___attribute:
1803 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1804 // and in block scope it's probably a label. Inside a class definition,
1805 // this is a bit-field.
1806 return Context == DeclaratorContext::MemberContext ||
1807 (getLangOpts().CPlusPlus &&
1808 Context == DeclaratorContext::FileContext);
1810 case tok::identifier: // Possible virt-specifier.
1811 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1822 /// Skip until we reach something which seems like a sensible place to pick
1823 /// up parsing after a malformed declaration. This will sometimes stop sooner
1824 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1825 void Parser::SkipMalformedDecl() {
1827 switch (Tok.getKind()) {
1829 // Skip until matching }, then stop. We've probably skipped over
1830 // a malformed class or function definition or similar.
1832 SkipUntil(tok::r_brace);
1833 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1834 // This declaration isn't over yet. Keep skipping.
1837 TryConsumeToken(tok::semi);
1842 SkipUntil(tok::r_square);
1847 SkipUntil(tok::r_paren);
1857 case tok::kw_inline:
1858 // 'inline namespace' at the start of a line is almost certainly
1859 // a good place to pick back up parsing, except in an Objective-C
1860 // @interface context.
1861 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1862 (!ParsingInObjCContainer || CurParsedObjCImpl))
1866 case tok::kw_namespace:
1867 // 'namespace' at the start of a line is almost certainly a good
1868 // place to pick back up parsing, except in an Objective-C
1869 // @interface context.
1870 if (Tok.isAtStartOfLine() &&
1871 (!ParsingInObjCContainer || CurParsedObjCImpl))
1876 // @end is very much like } in Objective-C contexts.
1877 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1878 ParsingInObjCContainer)
1884 // - and + probably start new method declarations in Objective-C contexts.
1885 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1890 case tok::annot_module_begin:
1891 case tok::annot_module_end:
1892 case tok::annot_module_include:
1903 /// ParseDeclGroup - Having concluded that this is either a function
1904 /// definition or a group of object declarations, actually parse the
1906 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1907 DeclaratorContext Context,
1908 SourceLocation *DeclEnd,
1909 ForRangeInit *FRI) {
1910 // Parse the first declarator.
1911 ParsingDeclarator D(*this, DS, Context);
1914 // Bail out if the first declarator didn't seem well-formed.
1915 if (!D.hasName() && !D.mayOmitIdentifier()) {
1916 SkipMalformedDecl();
1920 // Save late-parsed attributes for now; they need to be parsed in the
1921 // appropriate function scope after the function Decl has been constructed.
1922 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1923 LateParsedAttrList LateParsedAttrs(true);
1924 if (D.isFunctionDeclarator()) {
1925 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1927 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1928 // attribute. If we find the keyword here, tell the user to put it
1929 // at the start instead.
1930 if (Tok.is(tok::kw__Noreturn)) {
1931 SourceLocation Loc = ConsumeToken();
1932 const char *PrevSpec;
1935 // We can offer a fixit if it's valid to mark this function as _Noreturn
1936 // and we don't have any other declarators in this declaration.
1937 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
1938 MaybeParseGNUAttributes(D, &LateParsedAttrs);
1939 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
1941 Diag(Loc, diag::err_c11_noreturn_misplaced)
1942 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
1943 << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
1948 // Check to see if we have a function *definition* which must have a body.
1949 if (D.isFunctionDeclarator() &&
1950 // Look at the next token to make sure that this isn't a function
1951 // declaration. We have to check this because __attribute__ might be the
1952 // start of a function definition in GCC-extended K&R C.
1953 !isDeclarationAfterDeclarator()) {
1955 // Function definitions are only allowed at file scope and in C++ classes.
1956 // The C++ inline method definition case is handled elsewhere, so we only
1957 // need to handle the file scope definition case.
1958 if (Context == DeclaratorContext::FileContext) {
1959 if (isStartOfFunctionDefinition(D)) {
1960 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1961 Diag(Tok, diag::err_function_declared_typedef);
1963 // Recover by treating the 'typedef' as spurious.
1964 DS.ClearStorageClassSpecs();
1968 ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
1969 return Actions.ConvertDeclToDeclGroup(TheDecl);
1972 if (isDeclarationSpecifier()) {
1973 // If there is an invalid declaration specifier right after the
1974 // function prototype, then we must be in a missing semicolon case
1975 // where this isn't actually a body. Just fall through into the code
1976 // that handles it as a prototype, and let the top-level code handle
1977 // the erroneous declspec where it would otherwise expect a comma or
1980 Diag(Tok, diag::err_expected_fn_body);
1981 SkipUntil(tok::semi);
1985 if (Tok.is(tok::l_brace)) {
1986 Diag(Tok, diag::err_function_definition_not_allowed);
1987 SkipMalformedDecl();
1993 if (ParseAsmAttributesAfterDeclarator(D))
1996 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
1997 // must parse and analyze the for-range-initializer before the declaration is
2000 // Handle the Objective-C for-in loop variable similarly, although we
2001 // don't need to parse the container in advance.
2002 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2003 bool IsForRangeLoop = false;
2004 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2005 IsForRangeLoop = true;
2006 if (Tok.is(tok::l_brace))
2007 FRI->RangeExpr = ParseBraceInitializer();
2009 FRI->RangeExpr = ParseExpression();
2012 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2013 if (IsForRangeLoop) {
2014 Actions.ActOnCXXForRangeDecl(ThisDecl);
2017 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2018 VD->setObjCForDecl(true);
2020 Actions.FinalizeDeclaration(ThisDecl);
2021 D.complete(ThisDecl);
2022 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2025 SmallVector<Decl *, 8> DeclsInGroup;
2026 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2027 D, ParsedTemplateInfo(), FRI);
2028 if (LateParsedAttrs.size() > 0)
2029 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2030 D.complete(FirstDecl);
2032 DeclsInGroup.push_back(FirstDecl);
2034 bool ExpectSemi = Context != DeclaratorContext::ForContext;
2036 // If we don't have a comma, it is either the end of the list (a ';') or an
2038 SourceLocation CommaLoc;
2039 while (TryConsumeToken(tok::comma, CommaLoc)) {
2040 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2041 // This comma was followed by a line-break and something which can't be
2042 // the start of a declarator. The comma was probably a typo for a
2044 Diag(CommaLoc, diag::err_expected_semi_declaration)
2045 << FixItHint::CreateReplacement(CommaLoc, ";");
2050 // Parse the next declarator.
2052 D.setCommaLoc(CommaLoc);
2054 // Accept attributes in an init-declarator. In the first declarator in a
2055 // declaration, these would be part of the declspec. In subsequent
2056 // declarators, they become part of the declarator itself, so that they
2057 // don't apply to declarators after *this* one. Examples:
2058 // short __attribute__((common)) var; -> declspec
2059 // short var __attribute__((common)); -> declarator
2060 // short x, __attribute__((common)) var; -> declarator
2061 MaybeParseGNUAttributes(D);
2063 // MSVC parses but ignores qualifiers after the comma as an extension.
2064 if (getLangOpts().MicrosoftExt)
2065 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2068 if (!D.isInvalidType()) {
2069 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2070 D.complete(ThisDecl);
2072 DeclsInGroup.push_back(ThisDecl);
2077 *DeclEnd = Tok.getLocation();
2080 ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2081 ? diag::err_invalid_token_after_toplevel_declarator
2082 : diag::err_expected_semi_declaration)) {
2083 // Okay, there was no semicolon and one was expected. If we see a
2084 // declaration specifier, just assume it was missing and continue parsing.
2085 // Otherwise things are very confused and we skip to recover.
2086 if (!isDeclarationSpecifier()) {
2087 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2088 TryConsumeToken(tok::semi);
2092 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2095 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2096 /// declarator. Returns true on an error.
2097 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2098 // If a simple-asm-expr is present, parse it.
2099 if (Tok.is(tok::kw_asm)) {
2101 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2102 if (AsmLabel.isInvalid()) {
2103 SkipUntil(tok::semi, StopBeforeMatch);
2107 D.setAsmLabel(AsmLabel.get());
2111 MaybeParseGNUAttributes(D);
2115 /// Parse 'declaration' after parsing 'declaration-specifiers
2116 /// declarator'. This method parses the remainder of the declaration
2117 /// (including any attributes or initializer, among other things) and
2118 /// finalizes the declaration.
2120 /// init-declarator: [C99 6.7]
2122 /// declarator '=' initializer
2123 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2124 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2125 /// [C++] declarator initializer[opt]
2127 /// [C++] initializer:
2128 /// [C++] '=' initializer-clause
2129 /// [C++] '(' expression-list ')'
2130 /// [C++0x] '=' 'default' [TODO]
2131 /// [C++0x] '=' 'delete'
2132 /// [C++0x] braced-init-list
2134 /// According to the standard grammar, =default and =delete are function
2135 /// definitions, but that definitely doesn't fit with the parser here.
2137 Decl *Parser::ParseDeclarationAfterDeclarator(
2138 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2139 if (ParseAsmAttributesAfterDeclarator(D))
2142 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2145 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2146 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2147 // RAII type used to track whether we're inside an initializer.
2148 struct InitializerScopeRAII {
2153 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2154 : P(P), D(D), ThisDecl(ThisDecl) {
2155 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2157 if (D.getCXXScopeSpec().isSet()) {
2159 S = P.getCurScope();
2161 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2164 ~InitializerScopeRAII() { pop(); }
2166 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2168 if (D.getCXXScopeSpec().isSet())
2169 S = P.getCurScope();
2170 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2178 // Inform the current actions module that we just parsed this declarator.
2179 Decl *ThisDecl = nullptr;
2180 switch (TemplateInfo.Kind) {
2181 case ParsedTemplateInfo::NonTemplate:
2182 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2185 case ParsedTemplateInfo::Template:
2186 case ParsedTemplateInfo::ExplicitSpecialization: {
2187 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2188 *TemplateInfo.TemplateParams,
2190 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2191 // Re-direct this decl to refer to the templated decl so that we can
2193 ThisDecl = VT->getTemplatedDecl();
2196 case ParsedTemplateInfo::ExplicitInstantiation: {
2197 if (Tok.is(tok::semi)) {
2198 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2199 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2200 if (ThisRes.isInvalid()) {
2201 SkipUntil(tok::semi, StopBeforeMatch);
2204 ThisDecl = ThisRes.get();
2206 // FIXME: This check should be for a variable template instantiation only.
2208 // Check that this is a valid instantiation
2209 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2210 // If the declarator-id is not a template-id, issue a diagnostic and
2211 // recover by ignoring the 'template' keyword.
2212 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2213 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2214 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2216 SourceLocation LAngleLoc =
2217 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2218 Diag(D.getIdentifierLoc(),
2219 diag::err_explicit_instantiation_with_definition)
2220 << SourceRange(TemplateInfo.TemplateLoc)
2221 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2223 // Recover as if it were an explicit specialization.
2224 TemplateParameterLists FakedParamLists;
2225 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2226 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2227 LAngleLoc, nullptr));
2230 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2237 // Parse declarator '=' initializer.
2238 // If a '==' or '+=' is found, suggest a fixit to '='.
2239 if (isTokenEqualOrEqualTypo()) {
2240 SourceLocation EqualLoc = ConsumeToken();
2242 if (Tok.is(tok::kw_delete)) {
2243 if (D.isFunctionDeclarator())
2244 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2247 Diag(ConsumeToken(), diag::err_deleted_non_function);
2248 } else if (Tok.is(tok::kw_default)) {
2249 if (D.isFunctionDeclarator())
2250 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2253 Diag(ConsumeToken(), diag::err_default_special_members);
2255 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2257 if (Tok.is(tok::code_completion)) {
2258 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2259 Actions.FinalizeDeclaration(ThisDecl);
2264 ExprResult Init(ParseInitializer());
2266 // If this is the only decl in (possibly) range based for statement,
2267 // our best guess is that the user meant ':' instead of '='.
2268 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2269 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2270 << FixItHint::CreateReplacement(EqualLoc, ":");
2271 // We are trying to stop parser from looking for ';' in this for
2272 // statement, therefore preventing spurious errors to be issued.
2273 FRI->ColonLoc = EqualLoc;
2275 FRI->RangeExpr = Init;
2280 if (Init.isInvalid()) {
2281 SmallVector<tok::TokenKind, 2> StopTokens;
2282 StopTokens.push_back(tok::comma);
2283 if (D.getContext() == DeclaratorContext::ForContext ||
2284 D.getContext() == DeclaratorContext::InitStmtContext)
2285 StopTokens.push_back(tok::r_paren);
2286 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2287 Actions.ActOnInitializerError(ThisDecl);
2289 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2290 /*DirectInit=*/false);
2292 } else if (Tok.is(tok::l_paren)) {
2293 // Parse C++ direct initializer: '(' expression-list ')'
2294 BalancedDelimiterTracker T(*this, tok::l_paren);
2298 CommaLocsTy CommaLocs;
2300 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2302 llvm::function_ref<void()> ExprListCompleter;
2303 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2304 auto ConstructorCompleter = [&, ThisVarDecl] {
2305 Actions.CodeCompleteConstructor(
2306 getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2307 ThisDecl->getLocation(), Exprs);
2310 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2311 // VarDecl. This is an error and it is reported in a call to
2312 // Actions.ActOnInitializerError(). However, we call
2313 // CodeCompleteConstructor only on VarDecls, falling back to default
2314 // completer in other cases.
2315 ExprListCompleter = ConstructorCompleter;
2318 if (ParseExpressionList(Exprs, CommaLocs, ExprListCompleter)) {
2319 Actions.ActOnInitializerError(ThisDecl);
2320 SkipUntil(tok::r_paren, StopAtSemi);
2325 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2326 "Unexpected number of commas!");
2330 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2331 T.getCloseLocation(),
2333 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2334 /*DirectInit=*/true);
2336 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2337 (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2338 // Parse C++0x braced-init-list.
2339 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2341 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2343 ExprResult Init(ParseBraceInitializer());
2347 if (Init.isInvalid()) {
2348 Actions.ActOnInitializerError(ThisDecl);
2350 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2353 Actions.ActOnUninitializedDecl(ThisDecl);
2356 Actions.FinalizeDeclaration(ThisDecl);
2361 /// ParseSpecifierQualifierList
2362 /// specifier-qualifier-list:
2363 /// type-specifier specifier-qualifier-list[opt]
2364 /// type-qualifier specifier-qualifier-list[opt]
2365 /// [GNU] attributes specifier-qualifier-list[opt]
2367 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2368 DeclSpecContext DSC) {
2369 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2370 /// parse declaration-specifiers and complain about extra stuff.
2371 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2372 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2374 // Validate declspec for type-name.
2375 unsigned Specs = DS.getParsedSpecifiers();
2376 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2377 Diag(Tok, diag::err_expected_type);
2378 DS.SetTypeSpecError();
2379 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2380 Diag(Tok, diag::err_typename_requires_specqual);
2381 if (!DS.hasTypeSpecifier())
2382 DS.SetTypeSpecError();
2385 // Issue diagnostic and remove storage class if present.
2386 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2387 if (DS.getStorageClassSpecLoc().isValid())
2388 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2390 Diag(DS.getThreadStorageClassSpecLoc(),
2391 diag::err_typename_invalid_storageclass);
2392 DS.ClearStorageClassSpecs();
2395 // Issue diagnostic and remove function specifier if present.
2396 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2397 if (DS.isInlineSpecified())
2398 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2399 if (DS.isVirtualSpecified())
2400 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2401 if (DS.isExplicitSpecified())
2402 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2403 DS.ClearFunctionSpecs();
2406 // Issue diagnostic and remove constexpr specfier if present.
2407 if (DS.isConstexprSpecified() && DSC != DeclSpecContext::DSC_condition) {
2408 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
2409 DS.ClearConstexprSpec();
2413 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2414 /// specified token is valid after the identifier in a declarator which
2415 /// immediately follows the declspec. For example, these things are valid:
2417 /// int x [ 4]; // direct-declarator
2418 /// int x ( int y); // direct-declarator
2419 /// int(int x ) // direct-declarator
2420 /// int x ; // simple-declaration
2421 /// int x = 17; // init-declarator-list
2422 /// int x , y; // init-declarator-list
2423 /// int x __asm__ ("foo"); // init-declarator-list
2424 /// int x : 4; // struct-declarator
2425 /// int x { 5}; // C++'0x unified initializers
2427 /// This is not, because 'x' does not immediately follow the declspec (though
2428 /// ')' happens to be valid anyway).
2431 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2432 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2433 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2437 /// ParseImplicitInt - This method is called when we have an non-typename
2438 /// identifier in a declspec (which normally terminates the decl spec) when
2439 /// the declspec has no type specifier. In this case, the declspec is either
2440 /// malformed or is "implicit int" (in K&R and C89).
2442 /// This method handles diagnosing this prettily and returns false if the
2443 /// declspec is done being processed. If it recovers and thinks there may be
2444 /// other pieces of declspec after it, it returns true.
2446 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2447 const ParsedTemplateInfo &TemplateInfo,
2448 AccessSpecifier AS, DeclSpecContext DSC,
2449 ParsedAttributesWithRange &Attrs) {
2450 assert(Tok.is(tok::identifier) && "should have identifier");
2452 SourceLocation Loc = Tok.getLocation();
2453 // If we see an identifier that is not a type name, we normally would
2454 // parse it as the identifier being declared. However, when a typename
2455 // is typo'd or the definition is not included, this will incorrectly
2456 // parse the typename as the identifier name and fall over misparsing
2457 // later parts of the diagnostic.
2459 // As such, we try to do some look-ahead in cases where this would
2460 // otherwise be an "implicit-int" case to see if this is invalid. For
2461 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2462 // an identifier with implicit int, we'd get a parse error because the
2463 // next token is obviously invalid for a type. Parse these as a case
2464 // with an invalid type specifier.
2465 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2467 // Since we know that this either implicit int (which is rare) or an
2468 // error, do lookahead to try to do better recovery. This never applies
2469 // within a type specifier. Outside of C++, we allow this even if the
2470 // language doesn't "officially" support implicit int -- we support
2471 // implicit int as an extension in C99 and C11.
2472 if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2473 isValidAfterIdentifierInDeclarator(NextToken())) {
2474 // If this token is valid for implicit int, e.g. "static x = 4", then
2475 // we just avoid eating the identifier, so it will be parsed as the
2476 // identifier in the declarator.
2480 if (getLangOpts().CPlusPlus &&
2481 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2482 // Don't require a type specifier if we have the 'auto' storage class
2483 // specifier in C++98 -- we'll promote it to a type specifier.
2485 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2489 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2490 getLangOpts().MSVCCompat) {
2491 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2492 // Give Sema a chance to recover if we are in a template with dependent base
2494 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2495 *Tok.getIdentifierInfo(), Tok.getLocation(),
2496 DSC == DeclSpecContext::DSC_template_type_arg)) {
2497 const char *PrevSpec;
2499 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2500 Actions.getASTContext().getPrintingPolicy());
2501 DS.SetRangeEnd(Tok.getLocation());
2507 // Otherwise, if we don't consume this token, we are going to emit an
2508 // error anyway. Try to recover from various common problems. Check
2509 // to see if this was a reference to a tag name without a tag specified.
2510 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2512 // C++ doesn't need this, and isTagName doesn't take SS.
2513 if (SS == nullptr) {
2514 const char *TagName = nullptr, *FixitTagName = nullptr;
2515 tok::TokenKind TagKind = tok::unknown;
2517 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2519 case DeclSpec::TST_enum:
2520 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2521 case DeclSpec::TST_union:
2522 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2523 case DeclSpec::TST_struct:
2524 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2525 case DeclSpec::TST_interface:
2526 TagName="__interface"; FixitTagName = "__interface ";
2527 TagKind=tok::kw___interface;break;
2528 case DeclSpec::TST_class:
2529 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2533 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2534 LookupResult R(Actions, TokenName, SourceLocation(),
2535 Sema::LookupOrdinaryName);
2537 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2538 << TokenName << TagName << getLangOpts().CPlusPlus
2539 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2541 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2542 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2544 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2545 << TokenName << TagName;
2548 // Parse this as a tag as if the missing tag were present.
2549 if (TagKind == tok::kw_enum)
2550 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2551 DeclSpecContext::DSC_normal);
2553 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2554 /*EnteringContext*/ false,
2555 DeclSpecContext::DSC_normal, Attrs);
2560 // Determine whether this identifier could plausibly be the name of something
2561 // being declared (with a missing type).
2562 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2563 DSC == DeclSpecContext::DSC_class)) {
2564 // Look ahead to the next token to try to figure out what this declaration
2565 // was supposed to be.
2566 switch (NextToken().getKind()) {
2567 case tok::l_paren: {
2568 // static x(4); // 'x' is not a type
2569 // x(int n); // 'x' is not a type
2570 // x (*p)[]; // 'x' is a type
2572 // Since we're in an error case, we can afford to perform a tentative
2573 // parse to determine which case we're in.
2574 TentativeParsingAction PA(*this);
2576 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2579 if (TPR != TPResult::False) {
2580 // The identifier is followed by a parenthesized declarator.
2581 // It's supposed to be a type.
2585 // If we're in a context where we could be declaring a constructor,
2586 // check whether this is a constructor declaration with a bogus name.
2587 if (DSC == DeclSpecContext::DSC_class ||
2588 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2589 IdentifierInfo *II = Tok.getIdentifierInfo();
2590 if (Actions.isCurrentClassNameTypo(II, SS)) {
2591 Diag(Loc, diag::err_constructor_bad_name)
2592 << Tok.getIdentifierInfo() << II
2593 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2594 Tok.setIdentifierInfo(II);
2606 // This looks like a variable or function declaration. The type is
2607 // probably missing. We're done parsing decl-specifiers.
2609 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2613 // This is probably supposed to be a type. This includes cases like:
2615 // struct S { unsinged : 4; };
2620 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2621 // and attempt to recover.
2623 IdentifierInfo *II = Tok.getIdentifierInfo();
2624 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2625 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2628 // The action has suggested that the type T could be used. Set that as
2629 // the type in the declaration specifiers, consume the would-be type
2630 // name token, and we're done.
2631 const char *PrevSpec;
2633 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2634 Actions.getASTContext().getPrintingPolicy());
2635 DS.SetRangeEnd(Tok.getLocation());
2637 // There may be other declaration specifiers after this.
2639 } else if (II != Tok.getIdentifierInfo()) {
2640 // If no type was suggested, the correction is to a keyword
2641 Tok.setKind(II->getTokenID());
2642 // There may be other declaration specifiers after this.
2646 // Otherwise, the action had no suggestion for us. Mark this as an error.
2647 DS.SetTypeSpecError();
2648 DS.SetRangeEnd(Tok.getLocation());
2651 // Eat any following template arguments.
2652 if (IsTemplateName) {
2653 SourceLocation LAngle, RAngle;
2654 TemplateArgList Args;
2655 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2658 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2659 // avoid rippling error messages on subsequent uses of the same type,
2660 // could be useful if #include was forgotten.
2664 /// Determine the declaration specifier context from the declarator
2667 /// \param Context the declarator context, which is one of the
2668 /// DeclaratorContext enumerator values.
2669 Parser::DeclSpecContext
2670 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2671 if (Context == DeclaratorContext::MemberContext)
2672 return DeclSpecContext::DSC_class;
2673 if (Context == DeclaratorContext::FileContext)
2674 return DeclSpecContext::DSC_top_level;
2675 if (Context == DeclaratorContext::TemplateParamContext)
2676 return DeclSpecContext::DSC_template_param;
2677 if (Context == DeclaratorContext::TemplateArgContext ||
2678 Context == DeclaratorContext::TemplateTypeArgContext)
2679 return DeclSpecContext::DSC_template_type_arg;
2680 if (Context == DeclaratorContext::TrailingReturnContext ||
2681 Context == DeclaratorContext::TrailingReturnVarContext)
2682 return DeclSpecContext::DSC_trailing;
2683 if (Context == DeclaratorContext::AliasDeclContext ||
2684 Context == DeclaratorContext::AliasTemplateContext)
2685 return DeclSpecContext::DSC_alias_declaration;
2686 return DeclSpecContext::DSC_normal;
2689 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2691 /// FIXME: Simply returns an alignof() expression if the argument is a
2692 /// type. Ideally, the type should be propagated directly into Sema.
2695 /// [C11] constant-expression
2696 /// [C++0x] type-id ...[opt]
2697 /// [C++0x] assignment-expression ...[opt]
2698 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2699 SourceLocation &EllipsisLoc) {
2701 if (isTypeIdInParens()) {
2702 SourceLocation TypeLoc = Tok.getLocation();
2703 ParsedType Ty = ParseTypeName().get();
2704 SourceRange TypeRange(Start, Tok.getLocation());
2705 ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2706 Ty.getAsOpaquePtr(), TypeRange);
2708 ER = ParseConstantExpression();
2710 if (getLangOpts().CPlusPlus11)
2711 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2716 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2717 /// attribute to Attrs.
2719 /// alignment-specifier:
2720 /// [C11] '_Alignas' '(' type-id ')'
2721 /// [C11] '_Alignas' '(' constant-expression ')'
2722 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2723 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2724 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2725 SourceLocation *EndLoc) {
2726 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2727 "Not an alignment-specifier!");
2729 IdentifierInfo *KWName = Tok.getIdentifierInfo();
2730 SourceLocation KWLoc = ConsumeToken();
2732 BalancedDelimiterTracker T(*this, tok::l_paren);
2733 if (T.expectAndConsume())
2736 SourceLocation EllipsisLoc;
2737 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2738 if (ArgExpr.isInvalid()) {
2745 *EndLoc = T.getCloseLocation();
2747 ArgsVector ArgExprs;
2748 ArgExprs.push_back(ArgExpr.get());
2749 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2750 ParsedAttr::AS_Keyword, EllipsisLoc);
2753 /// Determine whether we're looking at something that might be a declarator
2754 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2755 /// diagnose a missing semicolon after a prior tag definition in the decl
2758 /// \return \c true if an error occurred and this can't be any kind of
2761 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2762 DeclSpecContext DSContext,
2763 LateParsedAttrList *LateAttrs) {
2764 assert(DS.hasTagDefinition() && "shouldn't call this");
2766 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2767 DSContext == DeclSpecContext::DSC_top_level);
2769 if (getLangOpts().CPlusPlus &&
2770 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2771 tok::annot_template_id) &&
2772 TryAnnotateCXXScopeToken(EnteringContext)) {
2773 SkipMalformedDecl();
2777 bool HasScope = Tok.is(tok::annot_cxxscope);
2778 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2779 Token AfterScope = HasScope ? NextToken() : Tok;
2781 // Determine whether the following tokens could possibly be a
2783 bool MightBeDeclarator = true;
2784 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2785 // A declarator-id can't start with 'typename'.
2786 MightBeDeclarator = false;
2787 } else if (AfterScope.is(tok::annot_template_id)) {
2788 // If we have a type expressed as a template-id, this cannot be a
2789 // declarator-id (such a type cannot be redeclared in a simple-declaration).
2790 TemplateIdAnnotation *Annot =
2791 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2792 if (Annot->Kind == TNK_Type_template)
2793 MightBeDeclarator = false;
2794 } else if (AfterScope.is(tok::identifier)) {
2795 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2797 // These tokens cannot come after the declarator-id in a
2798 // simple-declaration, and are likely to come after a type-specifier.
2799 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2800 tok::annot_cxxscope, tok::coloncolon)) {
2801 // Missing a semicolon.
2802 MightBeDeclarator = false;
2803 } else if (HasScope) {
2804 // If the declarator-id has a scope specifier, it must redeclare a
2805 // previously-declared entity. If that's a type (and this is not a
2806 // typedef), that's an error.
2808 Actions.RestoreNestedNameSpecifierAnnotation(
2809 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2810 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2811 Sema::NameClassification Classification = Actions.ClassifyName(
2812 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2813 /*IsAddressOfOperand*/false);
2814 switch (Classification.getKind()) {
2815 case Sema::NC_Error:
2816 SkipMalformedDecl();
2819 case Sema::NC_Keyword:
2820 case Sema::NC_NestedNameSpecifier:
2821 llvm_unreachable("typo correction and nested name specifiers not "
2825 case Sema::NC_TypeTemplate:
2826 // Not a previously-declared non-type entity.
2827 MightBeDeclarator = false;
2830 case Sema::NC_Unknown:
2831 case Sema::NC_Expression:
2832 case Sema::NC_VarTemplate:
2833 case Sema::NC_FunctionTemplate:
2834 // Might be a redeclaration of a prior entity.
2840 if (MightBeDeclarator)
2843 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2844 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
2845 diag::err_expected_after)
2846 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2848 // Try to recover from the typo, by dropping the tag definition and parsing
2849 // the problematic tokens as a type.
2851 // FIXME: Split the DeclSpec into pieces for the standalone
2852 // declaration and pieces for the following declaration, instead
2853 // of assuming that all the other pieces attach to new declaration,
2854 // and call ParsedFreeStandingDeclSpec as appropriate.
2855 DS.ClearTypeSpecType();
2856 ParsedTemplateInfo NotATemplate;
2857 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2861 // Choose the apprpriate diagnostic error for why fixed point types are
2862 // disabled, set the previous specifier, and mark as invalid.
2863 static void SetupFixedPointError(const LangOptions &LangOpts,
2864 const char *&PrevSpec, unsigned &DiagID,
2866 assert(!LangOpts.FixedPoint);
2867 DiagID = diag::err_fixed_point_not_enabled;
2868 PrevSpec = ""; // Not used by diagnostic
2872 /// ParseDeclarationSpecifiers
2873 /// declaration-specifiers: [C99 6.7]
2874 /// storage-class-specifier declaration-specifiers[opt]
2875 /// type-specifier declaration-specifiers[opt]
2876 /// [C99] function-specifier declaration-specifiers[opt]
2877 /// [C11] alignment-specifier declaration-specifiers[opt]
2878 /// [GNU] attributes declaration-specifiers[opt]
2879 /// [Clang] '__module_private__' declaration-specifiers[opt]
2880 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2882 /// storage-class-specifier: [C99 6.7.1]
2889 /// [C++11] 'thread_local'
2890 /// [C11] '_Thread_local'
2891 /// [GNU] '__thread'
2892 /// function-specifier: [C99 6.7.4]
2895 /// [C++] 'explicit'
2896 /// [OpenCL] '__kernel'
2897 /// 'friend': [C++ dcl.friend]
2898 /// 'constexpr': [C++0x dcl.constexpr]
2899 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
2900 const ParsedTemplateInfo &TemplateInfo,
2902 DeclSpecContext DSContext,
2903 LateParsedAttrList *LateAttrs) {
2904 if (DS.getSourceRange().isInvalid()) {
2905 // Start the range at the current token but make the end of the range
2906 // invalid. This will make the entire range invalid unless we successfully
2908 DS.SetRangeStart(Tok.getLocation());
2909 DS.SetRangeEnd(SourceLocation());
2912 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2913 DSContext == DeclSpecContext::DSC_top_level);
2914 bool AttrsLastTime = false;
2915 ParsedAttributesWithRange attrs(AttrFactory);
2916 // We use Sema's policy to get bool macros right.
2917 PrintingPolicy Policy = Actions.getPrintingPolicy();
2919 bool isInvalid = false;
2920 bool isStorageClass = false;
2921 const char *PrevSpec = nullptr;
2922 unsigned DiagID = 0;
2924 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2925 // implementation for VS2013 uses _Atomic as an identifier for one of the
2926 // classes in <atomic>.
2928 // A typedef declaration containing _Atomic<...> is among the places where
2929 // the class is used. If we are currently parsing such a declaration, treat
2930 // the token as an identifier.
2931 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2932 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
2933 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
2934 Tok.setKind(tok::identifier);
2936 SourceLocation Loc = Tok.getLocation();
2938 switch (Tok.getKind()) {
2942 ProhibitAttributes(attrs);
2944 // Reject C++11 attributes that appertain to decl specifiers as
2945 // we don't support any C++11 attributes that appertain to decl
2946 // specifiers. This also conforms to what g++ 4.8 is doing.
2947 ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
2949 DS.takeAttributesFrom(attrs);
2952 // If this is not a declaration specifier token, we're done reading decl
2953 // specifiers. First verify that DeclSpec's are consistent.
2954 DS.Finish(Actions, Policy);
2958 case tok::kw_alignas:
2959 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
2960 goto DoneWithDeclSpec;
2962 ProhibitAttributes(attrs);
2963 // FIXME: It would be good to recover by accepting the attributes,
2964 // but attempting to do that now would cause serious
2965 // madness in terms of diagnostics.
2967 attrs.Range = SourceRange();
2969 ParseCXX11Attributes(attrs);
2970 AttrsLastTime = true;
2973 case tok::code_completion: {
2974 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
2975 if (DS.hasTypeSpecifier()) {
2976 bool AllowNonIdentifiers
2977 = (getCurScope()->getFlags() & (Scope::ControlScope |
2979 Scope::TemplateParamScope |
2980 Scope::FunctionPrototypeScope |
2981 Scope::AtCatchScope)) == 0;
2982 bool AllowNestedNameSpecifiers
2983 = DSContext == DeclSpecContext::DSC_top_level ||
2984 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
2986 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
2987 AllowNonIdentifiers,
2988 AllowNestedNameSpecifiers);
2989 return cutOffParsing();
2992 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
2993 CCC = Sema::PCC_LocalDeclarationSpecifiers;
2994 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
2995 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
2996 : Sema::PCC_Template;
2997 else if (DSContext == DeclSpecContext::DSC_class)
2998 CCC = Sema::PCC_Class;
2999 else if (CurParsedObjCImpl)
3000 CCC = Sema::PCC_ObjCImplementation;
3002 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3003 return cutOffParsing();
3006 case tok::coloncolon: // ::foo::bar
3007 // C++ scope specifier. Annotate and loop, or bail out on error.
3008 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3009 if (!DS.hasTypeSpecifier())
3010 DS.SetTypeSpecError();
3011 goto DoneWithDeclSpec;
3013 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3014 goto DoneWithDeclSpec;
3017 case tok::annot_cxxscope: {
3018 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3019 goto DoneWithDeclSpec;
3022 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3023 Tok.getAnnotationRange(),
3026 // We are looking for a qualified typename.
3027 Token Next = NextToken();
3028 if (Next.is(tok::annot_template_id) &&
3029 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3030 ->Kind == TNK_Type_template) {
3031 // We have a qualified template-id, e.g., N::A<int>
3033 // If this would be a valid constructor declaration with template
3034 // arguments, we will reject the attempt to form an invalid type-id
3035 // referring to the injected-class-name when we annotate the token,
3036 // per C++ [class.qual]p2.
3038 // To improve diagnostics for this case, parse the declaration as a
3039 // constructor (and reject the extra template arguments later).
3040 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3041 if ((DSContext == DeclSpecContext::DSC_top_level ||
3042 DSContext == DeclSpecContext::DSC_class) &&
3044 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3045 isConstructorDeclarator(/*Unqualified*/ false)) {
3046 // The user meant this to be an out-of-line constructor
3047 // definition, but template arguments are not allowed
3048 // there. Just allow this as a constructor; we'll
3049 // complain about it later.
3050 goto DoneWithDeclSpec;
3053 DS.getTypeSpecScope() = SS;
3054 ConsumeAnnotationToken(); // The C++ scope.
3055 assert(Tok.is(tok::annot_template_id) &&
3056 "ParseOptionalCXXScopeSpecifier not working");
3057 AnnotateTemplateIdTokenAsType();
3061 if (Next.is(tok::annot_typename)) {
3062 DS.getTypeSpecScope() = SS;
3063 ConsumeAnnotationToken(); // The C++ scope.
3064 if (Tok.getAnnotationValue()) {
3065 ParsedType T = getTypeAnnotation(Tok);
3066 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3067 Tok.getAnnotationEndLoc(),
3068 PrevSpec, DiagID, T, Policy);
3073 DS.SetTypeSpecError();
3074 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3075 ConsumeAnnotationToken(); // The typename
3078 if (Next.isNot(tok::identifier))
3079 goto DoneWithDeclSpec;
3081 // Check whether this is a constructor declaration. If we're in a
3082 // context where the identifier could be a class name, and it has the
3083 // shape of a constructor declaration, process it as one.
3084 if ((DSContext == DeclSpecContext::DSC_top_level ||
3085 DSContext == DeclSpecContext::DSC_class) &&
3086 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3088 isConstructorDeclarator(/*Unqualified*/ false))
3089 goto DoneWithDeclSpec;
3091 ParsedType TypeRep =
3092 Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3093 getCurScope(), &SS, false, false, nullptr,
3094 /*IsCtorOrDtorName=*/false,
3095 /*WantNonTrivialSourceInfo=*/true,
3096 isClassTemplateDeductionContext(DSContext));
3098 // If the referenced identifier is not a type, then this declspec is
3099 // erroneous: We already checked about that it has no type specifier, and
3100 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3103 // Eat the scope spec so the identifier is current.
3104 ConsumeAnnotationToken();
3105 ParsedAttributesWithRange Attrs(AttrFactory);
3106 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3107 if (!Attrs.empty()) {
3108 AttrsLastTime = true;
3109 attrs.takeAllFrom(Attrs);
3113 goto DoneWithDeclSpec;
3116 DS.getTypeSpecScope() = SS;
3117 ConsumeAnnotationToken(); // The C++ scope.
3119 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3120 DiagID, TypeRep, Policy);
3124 DS.SetRangeEnd(Tok.getLocation());
3125 ConsumeToken(); // The typename.
3130 case tok::annot_typename: {
3131 // If we've previously seen a tag definition, we were almost surely
3132 // missing a semicolon after it.
3133 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3134 goto DoneWithDeclSpec;
3136 if (Tok.getAnnotationValue()) {
3137 ParsedType T = getTypeAnnotation(Tok);
3138 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3141 DS.SetTypeSpecError();
3146 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3147 ConsumeAnnotationToken(); // The typename
3152 case tok::kw___is_signed:
3153 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3154 // typically treats it as a trait. If we see __is_signed as it appears
3155 // in libstdc++, e.g.,
3157 // static const bool __is_signed;
3159 // then treat __is_signed as an identifier rather than as a keyword.
3160 if (DS.getTypeSpecType() == TST_bool &&
3161 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3162 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3163 TryKeywordIdentFallback(true);
3165 // We're done with the declaration-specifiers.
3166 goto DoneWithDeclSpec;
3169 case tok::kw___super:
3170 case tok::kw_decltype:
3171 case tok::identifier: {
3172 // This identifier can only be a typedef name if we haven't already seen
3173 // a type-specifier. Without this check we misparse:
3174 // typedef int X; struct Y { short X; }; as 'short int'.
3175 if (DS.hasTypeSpecifier())
3176 goto DoneWithDeclSpec;
3178 // If the token is an identifier named "__declspec" and Microsoft
3179 // extensions are not enabled, it is likely that there will be cascading
3180 // parse errors if this really is a __declspec attribute. Attempt to
3181 // recognize that scenario and recover gracefully.
3182 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3183 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3184 Diag(Loc, diag::err_ms_attributes_not_enabled);
3186 // The next token should be an open paren. If it is, eat the entire
3187 // attribute declaration and continue.
3188 if (NextToken().is(tok::l_paren)) {
3189 // Consume the __declspec identifier.
3192 // Eat the parens and everything between them.
3193 BalancedDelimiterTracker T(*this, tok::l_paren);
3194 if (T.consumeOpen()) {
3195 assert(false && "Not a left paren?");
3203 // In C++, check to see if this is a scope specifier like foo::bar::, if
3204 // so handle it as such. This is important for ctor parsing.
3205 if (getLangOpts().CPlusPlus) {
3206 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3207 DS.SetTypeSpecError();
3208 goto DoneWithDeclSpec;
3210 if (!Tok.is(tok::identifier))
3214 // Check for need to substitute AltiVec keyword tokens.
3215 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3218 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3219 // allow the use of a typedef name as a type specifier.
3220 if (DS.isTypeAltiVecVector())
3221 goto DoneWithDeclSpec;
3223 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3224 isObjCInstancetype()) {
3225 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3227 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3228 DiagID, TypeRep, Policy);
3232 DS.SetRangeEnd(Loc);
3237 // If we're in a context where the identifier could be a class name,
3238 // check whether this is a constructor declaration.
3239 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3240 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3241 isConstructorDeclarator(/*Unqualified*/true))
3242 goto DoneWithDeclSpec;
3244 ParsedType TypeRep = Actions.getTypeName(
3245 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3246 false, false, nullptr, false, false,
3247 isClassTemplateDeductionContext(DSContext));
3249 // If this is not a typedef name, don't parse it as part of the declspec,
3250 // it must be an implicit int or an error.
3252 ParsedAttributesWithRange Attrs(AttrFactory);
3253 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3254 if (!Attrs.empty()) {
3255 AttrsLastTime = true;
3256 attrs.takeAllFrom(Attrs);
3260 goto DoneWithDeclSpec;
3263 // Likewise, if this is a context where the identifier could be a template
3264 // name, check whether this is a deduction guide declaration.
3265 if (getLangOpts().CPlusPlus17 &&
3266 (DSContext == DeclSpecContext::DSC_class ||
3267 DSContext == DeclSpecContext::DSC_top_level) &&
3268 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3269 Tok.getLocation()) &&
3270 isConstructorDeclarator(/*Unqualified*/ true,
3271 /*DeductionGuide*/ true))
3272 goto DoneWithDeclSpec;
3274 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3275 DiagID, TypeRep, Policy);
3279 DS.SetRangeEnd(Tok.getLocation());
3280 ConsumeToken(); // The identifier
3282 // Objective-C supports type arguments and protocol references
3283 // following an Objective-C object or object pointer
3284 // type. Handle either one of them.
3285 if (Tok.is(tok::less) && getLangOpts().ObjC1) {
3286 SourceLocation NewEndLoc;
3287 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3288 Loc, TypeRep, /*consumeLastToken=*/true,
3290 if (NewTypeRep.isUsable()) {
3291 DS.UpdateTypeRep(NewTypeRep.get());
3292 DS.SetRangeEnd(NewEndLoc);
3296 // Need to support trailing type qualifiers (e.g. "id<p> const").
3297 // If a type specifier follows, it will be diagnosed elsewhere.
3302 case tok::annot_template_id: {
3303 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3304 if (TemplateId->Kind != TNK_Type_template) {
3305 // This template-id does not refer to a type name, so we're
3306 // done with the type-specifiers.
3307 goto DoneWithDeclSpec;
3310 // If we're in a context where the template-id could be a
3311 // constructor name or specialization, check whether this is a
3312 // constructor declaration.
3313 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3314 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3315 isConstructorDeclarator(TemplateId->SS.isEmpty()))
3316 goto DoneWithDeclSpec;
3318 // Turn the template-id annotation token into a type annotation
3319 // token, then try again to parse it as a type-specifier.
3320 AnnotateTemplateIdTokenAsType();
3324 // GNU attributes support.
3325 case tok::kw___attribute:
3326 ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3329 // Microsoft declspec support.
3330 case tok::kw___declspec:
3331 ParseMicrosoftDeclSpecs(DS.getAttributes());
3334 // Microsoft single token adornments.
3335 case tok::kw___forceinline: {
3336 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3337 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3338 SourceLocation AttrNameLoc = Tok.getLocation();
3339 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3340 nullptr, 0, ParsedAttr::AS_Keyword);
3344 case tok::kw___unaligned:
3345 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3349 case tok::kw___sptr:
3350 case tok::kw___uptr:
3351 case tok::kw___ptr64:
3352 case tok::kw___ptr32:
3354 case tok::kw___cdecl:
3355 case tok::kw___stdcall:
3356 case tok::kw___fastcall:
3357 case tok::kw___thiscall:
3358 case tok::kw___regcall:
3359 case tok::kw___vectorcall:
3360 ParseMicrosoftTypeAttributes(DS.getAttributes());
3363 // Borland single token adornments.
3364 case tok::kw___pascal:
3365 ParseBorlandTypeAttributes(DS.getAttributes());
3368 // OpenCL single token adornments.
3369 case tok::kw___kernel:
3370 ParseOpenCLKernelAttributes(DS.getAttributes());
3373 // Nullability type specifiers.
3374 case tok::kw__Nonnull:
3375 case tok::kw__Nullable:
3376 case tok::kw__Null_unspecified:
3377 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3380 // Objective-C 'kindof' types.
3381 case tok::kw___kindof:
3382 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3383 nullptr, 0, ParsedAttr::AS_Keyword);
3384 (void)ConsumeToken();
3387 // storage-class-specifier
3388 case tok::kw_typedef:
3389 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3390 PrevSpec, DiagID, Policy);
3391 isStorageClass = true;
3393 case tok::kw_extern:
3394 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3395 Diag(Tok, diag::ext_thread_before) << "extern";
3396 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3397 PrevSpec, DiagID, Policy);
3398 isStorageClass = true;
3400 case tok::kw___private_extern__:
3401 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3402 Loc, PrevSpec, DiagID, Policy);
3403 isStorageClass = true;
3405 case tok::kw_static:
3406 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3407 Diag(Tok, diag::ext_thread_before) << "static";
3408 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3409 PrevSpec, DiagID, Policy);
3410 isStorageClass = true;
3413 if (getLangOpts().CPlusPlus11) {
3414 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3415 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3416 PrevSpec, DiagID, Policy);
3418 Diag(Tok, diag::ext_auto_storage_class)
3419 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3421 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3424 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3425 PrevSpec, DiagID, Policy);
3426 isStorageClass = true;
3428 case tok::kw___auto_type:
3429 Diag(Tok, diag::ext_auto_type);
3430 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3433 case tok::kw_register:
3434 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3435 PrevSpec, DiagID, Policy);
3436 isStorageClass = true;
3438 case tok::kw_mutable:
3439 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3440 PrevSpec, DiagID, Policy);
3441 isStorageClass = true;
3443 case tok::kw___thread:
3444 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3446 isStorageClass = true;
3448 case tok::kw_thread_local:
3449 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3451 isStorageClass = true;
3453 case tok::kw__Thread_local:
3454 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3455 Loc, PrevSpec, DiagID);
3456 isStorageClass = true;
3459 // function-specifier
3460 case tok::kw_inline:
3461 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3463 case tok::kw_virtual:
3464 // OpenCL C++ v1.0 s2.9: the virtual function qualifier is not supported.
3465 if (getLangOpts().OpenCLCPlusPlus) {
3466 DiagID = diag::err_openclcxx_virtual_function;
3467 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3471 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3474 case tok::kw_explicit:
3475 isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
3477 case tok::kw__Noreturn:
3478 if (!getLangOpts().C11)
3479 Diag(Loc, diag::ext_c11_noreturn);
3480 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3483 // alignment-specifier
3484 case tok::kw__Alignas:
3485 if (!getLangOpts().C11)
3486 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
3487 ParseAlignmentSpecifier(DS.getAttributes());
3491 case tok::kw_friend:
3492 if (DSContext == DeclSpecContext::DSC_class)
3493 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3495 PrevSpec = ""; // not actually used by the diagnostic
3496 DiagID = diag::err_friend_invalid_in_context;
3502 case tok::kw___module_private__:
3503 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3507 case tok::kw_constexpr:
3508 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
3513 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3517 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3518 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3521 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3524 case tok::kw___int64:
3525 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3528 case tok::kw_signed:
3529 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3532 case tok::kw_unsigned:
3533 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3536 case tok::kw__Complex:
3537 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3540 case tok::kw__Imaginary:
3541 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3545 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3549 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3553 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3556 case tok::kw___int128:
3557 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3561 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3565 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3568 case tok::kw_double:
3569 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3572 case tok::kw__Float16:
3573 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3576 case tok::kw__Accum:
3577 if (!getLangOpts().FixedPoint) {
3578 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3580 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3584 case tok::kw__Fract:
3585 if (!getLangOpts().FixedPoint) {
3586 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3588 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3593 if (!getLangOpts().FixedPoint) {
3594 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3596 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3599 case tok::kw___float128:
3600 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3603 case tok::kw_wchar_t:
3604 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3607 case tok::kw_char8_t:
3608 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3611 case tok::kw_char16_t:
3612 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3615 case tok::kw_char32_t:
3616 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3621 if (Tok.is(tok::kw_bool) &&
3622 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3623 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3624 PrevSpec = ""; // Not used by the diagnostic.
3625 DiagID = diag::err_bool_redeclaration;
3626 // For better error recovery.
3627 Tok.setKind(tok::identifier);
3630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3634 case tok::kw__Decimal32:
3635 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3638 case tok::kw__Decimal64:
3639 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3642 case tok::kw__Decimal128:
3643 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3646 case tok::kw___vector:
3647 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3649 case tok::kw___pixel:
3650 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3652 case tok::kw___bool:
3653 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3656 if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
3657 // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3658 // support the "pipe" word as identifier.
3659 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3660 goto DoneWithDeclSpec;
3662 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3664 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3665 case tok::kw_##ImgType##_t: \
3666 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3669 #include "clang/Basic/OpenCLImageTypes.def"
3670 case tok::kw___unknown_anytype:
3671 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3672 PrevSpec, DiagID, Policy);
3677 case tok::kw_struct:
3678 case tok::kw___interface:
3679 case tok::kw_union: {
3680 tok::TokenKind Kind = Tok.getKind();
3683 // These are attributes following class specifiers.
3684 // To produce better diagnostic, we parse them when
3685 // parsing class specifier.
3686 ParsedAttributesWithRange Attributes(AttrFactory);
3687 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3688 EnteringContext, DSContext, Attributes);
3690 // If there are attributes following class specifier,
3691 // take them over and handle them here.
3692 if (!Attributes.empty()) {
3693 AttrsLastTime = true;
3694 attrs.takeAllFrom(Attributes);
3702 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3707 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3710 case tok::kw_volatile:
3711 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3714 case tok::kw_restrict:
3715 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3719 // C++ typename-specifier:
3720 case tok::kw_typename:
3721 if (TryAnnotateTypeOrScopeToken()) {
3722 DS.SetTypeSpecError();
3723 goto DoneWithDeclSpec;
3725 if (!Tok.is(tok::kw_typename))
3729 // GNU typeof support.
3730 case tok::kw_typeof:
3731 ParseTypeofSpecifier(DS);
3734 case tok::annot_decltype:
3735 ParseDecltypeSpecifier(DS);
3738 case tok::annot_pragma_pack:
3742 case tok::annot_pragma_ms_pragma:
3743 HandlePragmaMSPragma();
3746 case tok::annot_pragma_ms_vtordisp:
3747 HandlePragmaMSVtorDisp();
3750 case tok::annot_pragma_ms_pointers_to_members:
3751 HandlePragmaMSPointersToMembers();
3754 case tok::kw___underlying_type:
3755 ParseUnderlyingTypeSpecifier(DS);
3758 case tok::kw__Atomic:
3760 // If the _Atomic keyword is immediately followed by a left parenthesis,
3761 // it is interpreted as a type specifier (with a type name), not as a
3763 if (NextToken().is(tok::l_paren)) {
3764 ParseAtomicSpecifier(DS);
3767 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3771 // OpenCL access qualifiers:
3772 case tok::kw___read_only:
3773 case tok::kw___write_only:
3774 case tok::kw___read_write:
3775 // OpenCL C++ 1.0 s2.2: access qualifiers are reserved keywords.
3776 if (Actions.getLangOpts().OpenCLCPlusPlus) {
3777 DiagID = diag::err_openclcxx_reserved;
3778 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3781 ParseOpenCLQualifiers(DS.getAttributes());
3784 // OpenCL address space qualifiers:
3785 case tok::kw___generic:
3786 // generic address space is introduced only in OpenCL v2.0
3787 // see OpenCL C Spec v2.0 s6.5.5
3788 if (Actions.getLangOpts().OpenCLVersion < 200 &&
3789 !Actions.getLangOpts().OpenCLCPlusPlus) {
3790 DiagID = diag::err_opencl_unknown_type_specifier;
3791 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3796 case tok::kw___private:
3797 case tok::kw___global:
3798 case tok::kw___local:
3799 case tok::kw___constant:
3800 ParseOpenCLQualifiers(DS.getAttributes());
3804 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3805 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3806 // but we support it.
3807 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
3808 goto DoneWithDeclSpec;
3810 SourceLocation StartLoc = Tok.getLocation();
3811 SourceLocation EndLoc;
3812 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3813 if (Type.isUsable()) {
3814 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3815 PrevSpec, DiagID, Type.get(),
3816 Actions.getASTContext().getPrintingPolicy()))
3817 Diag(StartLoc, DiagID) << PrevSpec;
3819 DS.SetRangeEnd(EndLoc);
3821 DS.SetTypeSpecError();
3824 // Need to support trailing type qualifiers (e.g. "id<p> const").
3825 // If a type specifier follows, it will be diagnosed elsewhere.
3828 // If the specifier wasn't legal, issue a diagnostic.
3830 assert(PrevSpec && "Method did not return previous specifier!");
3833 if (DiagID == diag::ext_duplicate_declspec)
3835 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
3836 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
3837 Diag(Tok, DiagID) << getLangOpts().OpenCLCPlusPlus
3838 << getLangOpts().getOpenCLVersionTuple().getAsString()
3839 << PrevSpec << isStorageClass;
3841 Diag(Tok, DiagID) << PrevSpec;
3844 DS.SetRangeEnd(Tok.getLocation());
3845 if (DiagID != diag::err_bool_redeclaration)
3846 // After an error the next token can be an annotation token.
3849 AttrsLastTime = false;
3853 /// ParseStructDeclaration - Parse a struct declaration without the terminating
3856 /// struct-declaration:
3857 /// [C2x] attributes-specifier-seq[opt]
3858 /// specifier-qualifier-list struct-declarator-list
3859 /// [GNU] __extension__ struct-declaration
3860 /// [GNU] specifier-qualifier-list
3861 /// struct-declarator-list:
3862 /// struct-declarator
3863 /// struct-declarator-list ',' struct-declarator
3864 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
3865 /// struct-declarator:
3867 /// [GNU] declarator attributes[opt]
3868 /// declarator[opt] ':' constant-expression
3869 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
3871 void Parser::ParseStructDeclaration(
3872 ParsingDeclSpec &DS,
3873 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
3875 if (Tok.is(tok::kw___extension__)) {
3876 // __extension__ silences extension warnings in the subexpression.
3877 ExtensionRAIIObject O(Diags); // Use RAII to do this.
3879 return ParseStructDeclaration(DS, FieldsCallback);
3882 // Parse leading attributes.
3883 ParsedAttributesWithRange Attrs(AttrFactory);
3884 MaybeParseCXX11Attributes(Attrs);
3885 DS.takeAttributesFrom(Attrs);
3887 // Parse the common specifier-qualifiers-list piece.
3888 ParseSpecifierQualifierList(DS);
3890 // If there are no declarators, this is a free-standing declaration
3891 // specifier. Let the actions module cope with it.
3892 if (Tok.is(tok::semi)) {
3893 RecordDecl *AnonRecord = nullptr;
3894 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
3896 assert(!AnonRecord && "Did not expect anonymous struct or union here");
3897 DS.complete(TheDecl);
3901 // Read struct-declarators until we find the semicolon.
3902 bool FirstDeclarator = true;
3903 SourceLocation CommaLoc;
3905 ParsingFieldDeclarator DeclaratorInfo(*this, DS);
3906 DeclaratorInfo.D.setCommaLoc(CommaLoc);
3908 // Attributes are only allowed here on successive declarators.
3909 if (!FirstDeclarator)
3910 MaybeParseGNUAttributes(DeclaratorInfo.D);
3912 /// struct-declarator: declarator
3913 /// struct-declarator: declarator[opt] ':' constant-expression
3914 if (Tok.isNot(tok::colon)) {
3915 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
3916 ColonProtectionRAIIObject X(*this);
3917 ParseDeclarator(DeclaratorInfo.D);
3919 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
3921 if (TryConsumeToken(tok::colon)) {
3922 ExprResult Res(ParseConstantExpression());
3923 if (Res.isInvalid())
3924 SkipUntil(tok::semi, StopBeforeMatch);
3926 DeclaratorInfo.BitfieldSize = Res.get();
3929 // If attributes exist after the declarator, parse them.
3930 MaybeParseGNUAttributes(DeclaratorInfo.D);
3932 // We're done with this declarator; invoke the callback.
3933 FieldsCallback(DeclaratorInfo);
3935 // If we don't have a comma, it is either the end of the list (a ';')
3936 // or an error, bail out.
3937 if (!TryConsumeToken(tok::comma, CommaLoc))
3940 FirstDeclarator = false;
3944 /// ParseStructUnionBody
3945 /// struct-contents:
3946 /// struct-declaration-list
3948 /// [GNU] "struct-declaration-list" without terminatoring ';'
3949 /// struct-declaration-list:
3950 /// struct-declaration
3951 /// struct-declaration-list struct-declaration
3952 /// [OBC] '@' 'defs' '(' class-name ')'
3954 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
3955 unsigned TagType, Decl *TagDecl) {
3956 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3957 "parsing struct/union body");
3958 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
3960 BalancedDelimiterTracker T(*this, tok::l_brace);
3961 if (T.consumeOpen())
3964 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
3965 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3967 SmallVector<Decl *, 32> FieldDecls;
3969 // While we still have something to read, read the declarations in the struct.
3970 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3971 Tok.isNot(tok::eof)) {
3972 // Each iteration of this loop reads one struct-declaration.
3974 // Check for extraneous top-level semicolon.
3975 if (Tok.is(tok::semi)) {
3976 ConsumeExtraSemi(InsideStruct, TagType);
3980 // Parse _Static_assert declaration.
3981 if (Tok.is(tok::kw__Static_assert)) {
3982 SourceLocation DeclEnd;
3983 ParseStaticAssertDeclaration(DeclEnd);
3987 if (Tok.is(tok::annot_pragma_pack)) {
3992 if (Tok.is(tok::annot_pragma_align)) {
3993 HandlePragmaAlign();
3997 if (Tok.is(tok::annot_pragma_openmp)) {
3998 // Result can be ignored, because it must be always empty.
3999 AccessSpecifier AS = AS_none;
4000 ParsedAttributesWithRange Attrs(AttrFactory);
4001 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4005 if (!Tok.is(tok::at)) {
4006 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4007 // Install the declarator into the current TagDecl.
4009 Actions.ActOnField(getCurScope(), TagDecl,
4010 FD.D.getDeclSpec().getSourceRange().getBegin(),
4011 FD.D, FD.BitfieldSize);
4012 FieldDecls.push_back(Field);
4016 // Parse all the comma separated declarators.
4017 ParsingDeclSpec DS(*this);
4018 ParseStructDeclaration(DS, CFieldCallback);
4019 } else { // Handle @defs
4021 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4022 Diag(Tok, diag::err_unexpected_at);
4023 SkipUntil(tok::semi);
4027 ExpectAndConsume(tok::l_paren);
4028 if (!Tok.is(tok::identifier)) {
4029 Diag(Tok, diag::err_expected) << tok::identifier;
4030 SkipUntil(tok::semi);
4033 SmallVector<Decl *, 16> Fields;
4034 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4035 Tok.getIdentifierInfo(), Fields);
4036 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4038 ExpectAndConsume(tok::r_paren);
4041 if (TryConsumeToken(tok::semi))
4044 if (Tok.is(tok::r_brace)) {
4045 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4049 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4050 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4051 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4052 // If we stopped at a ';', eat it.
4053 TryConsumeToken(tok::semi);
4058 ParsedAttributes attrs(AttrFactory);
4059 // If attributes exist after struct contents, parse them.
4060 MaybeParseGNUAttributes(attrs);
4062 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4063 T.getOpenLocation(), T.getCloseLocation(), attrs);
4065 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4068 /// ParseEnumSpecifier
4069 /// enum-specifier: [C99 6.7.2.2]
4070 /// 'enum' identifier[opt] '{' enumerator-list '}'
4071 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4072 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4073 /// '}' attributes[opt]
4074 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4076 /// 'enum' identifier
4077 /// [GNU] 'enum' attributes[opt] identifier
4079 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4080 /// [C++11] enum-head '{' enumerator-list ',' '}'
4082 /// enum-head: [C++11]
4083 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4084 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4085 /// identifier enum-base[opt]
4087 /// enum-key: [C++11]
4092 /// enum-base: [C++11]
4093 /// ':' type-specifier-seq
4095 /// [C++] elaborated-type-specifier:
4096 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4098 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4099 const ParsedTemplateInfo &TemplateInfo,
4100 AccessSpecifier AS, DeclSpecContext DSC) {
4101 // Parse the tag portion of this.
4102 if (Tok.is(tok::code_completion)) {
4103 // Code completion for an enum name.
4104 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4105 return cutOffParsing();
4108 // If attributes exist after tag, parse them.
4109 ParsedAttributesWithRange attrs(AttrFactory);
4110 MaybeParseGNUAttributes(attrs);
4111 MaybeParseCXX11Attributes(attrs);
4112 MaybeParseMicrosoftDeclSpecs(attrs);
4114 SourceLocation ScopedEnumKWLoc;
4115 bool IsScopedUsingClassTag = false;
4117 // In C++11, recognize 'enum class' and 'enum struct'.
4118 if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4119 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4120 : diag::ext_scoped_enum);
4121 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4122 ScopedEnumKWLoc = ConsumeToken();
4124 // Attributes are not allowed between these keywords. Diagnose,
4125 // but then just treat them like they appeared in the right place.
4126 ProhibitAttributes(attrs);
4128 // They are allowed afterwards, though.
4129 MaybeParseGNUAttributes(attrs);
4130 MaybeParseCXX11Attributes(attrs);
4131 MaybeParseMicrosoftDeclSpecs(attrs);
4134 // C++11 [temp.explicit]p12:
4135 // The usual access controls do not apply to names used to specify
4136 // explicit instantiations.
4137 // We extend this to also cover explicit specializations. Note that
4138 // we don't suppress if this turns out to be an elaborated type
4140 bool shouldDelayDiagsInTag =
4141 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4142 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4143 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4145 // Enum definitions should not be parsed in a trailing-return-type.
4146 bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4148 bool AllowFixedUnderlyingType = AllowDeclaration &&
4149 (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
4150 getLangOpts().ObjC2);
4152 CXXScopeSpec &SS = DS.getTypeSpecScope();
4153 if (getLangOpts().CPlusPlus) {
4154 // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4155 // if a fixed underlying type is allowed.
4156 ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
4159 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4160 /*EnteringContext=*/true))
4163 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4164 Diag(Tok, diag::err_expected) << tok::identifier;
4165 if (Tok.isNot(tok::l_brace)) {
4166 // Has no name and is not a definition.
4167 // Skip the rest of this declarator, up until the comma or semicolon.
4168 SkipUntil(tok::comma, StopAtSemi);
4176 // Must have either 'enum name' or 'enum {...}'.
4177 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4178 !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
4179 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4181 // Skip the rest of this declarator, up until the comma or semicolon.
4182 SkipUntil(tok::comma, StopAtSemi);
4186 // If an identifier is present, consume and remember it.
4187 IdentifierInfo *Name = nullptr;
4188 SourceLocation NameLoc;
4189 if (Tok.is(tok::identifier)) {
4190 Name = Tok.getIdentifierInfo();
4191 NameLoc = ConsumeToken();
4194 if (!Name && ScopedEnumKWLoc.isValid()) {
4195 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4196 // declaration of a scoped enumeration.
4197 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4198 ScopedEnumKWLoc = SourceLocation();
4199 IsScopedUsingClassTag = false;
4202 // Okay, end the suppression area. We'll decide whether to emit the
4203 // diagnostics in a second.
4204 if (shouldDelayDiagsInTag)
4205 diagsFromTag.done();
4207 TypeResult BaseType;
4209 // Parse the fixed underlying type.
4210 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4211 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
4212 bool PossibleBitfield = false;
4213 if (CanBeBitfield) {
4214 // If we're in class scope, this can either be an enum declaration with
4215 // an underlying type, or a declaration of a bitfield member. We try to
4216 // use a simple disambiguation scheme first to catch the common cases
4217 // (integer literal, sizeof); if it's still ambiguous, we then consider
4218 // anything that's a simple-type-specifier followed by '(' as an
4219 // expression. This suffices because function types are not valid
4220 // underlying types anyway.
4221 EnterExpressionEvaluationContext Unevaluated(
4222 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4223 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4224 // If the next token starts an expression, we know we're parsing a
4225 // bit-field. This is the common case.
4226 if (TPR == TPResult::True)
4227 PossibleBitfield = true;
4228 // If the next token starts a type-specifier-seq, it may be either a
4229 // a fixed underlying type or the start of a function-style cast in C++;
4230 // lookahead one more token to see if it's obvious that we have a
4231 // fixed underlying type.
4232 else if (TPR == TPResult::False &&
4233 GetLookAheadToken(2).getKind() == tok::semi) {
4237 // We have the start of a type-specifier-seq, so we have to perform
4238 // tentative parsing to determine whether we have an expression or a
4240 TentativeParsingAction TPA(*this);
4245 // If we see a type specifier followed by an open-brace, we have an
4246 // ambiguity between an underlying type and a C++11 braced
4247 // function-style cast. Resolve this by always treating it as an
4249 // FIXME: The standard is not entirely clear on how to disambiguate in
4251 if ((getLangOpts().CPlusPlus &&
4252 isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4253 (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4254 // We'll parse this as a bitfield later.
4255 PossibleBitfield = true;
4258 // We have a type-specifier-seq.
4267 if (!PossibleBitfield) {
4269 BaseType = ParseTypeName(&Range);
4271 if (getLangOpts().CPlusPlus11) {
4272 Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4273 } else if (!getLangOpts().ObjC2) {
4274 if (getLangOpts().CPlusPlus)
4275 Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
4277 Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
4282 // There are four options here. If we have 'friend enum foo;' then this is a
4283 // friend declaration, and cannot have an accompanying definition. If we have
4284 // 'enum foo;', then this is a forward declaration. If we have
4285 // 'enum foo {...' then this is a definition. Otherwise we have something
4286 // like 'enum foo xyz', a reference.
4288 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4289 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4290 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4292 Sema::TagUseKind TUK;
4293 if (!AllowDeclaration) {
4294 TUK = Sema::TUK_Reference;
4295 } else if (Tok.is(tok::l_brace)) {
4296 if (DS.isFriendSpecified()) {
4297 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4298 << SourceRange(DS.getFriendSpecLoc());
4300 SkipUntil(tok::r_brace, StopAtSemi);
4301 TUK = Sema::TUK_Friend;
4303 TUK = Sema::TUK_Definition;
4305 } else if (!isTypeSpecifier(DSC) &&
4306 (Tok.is(tok::semi) ||
4307 (Tok.isAtStartOfLine() &&
4308 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4309 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4310 if (Tok.isNot(tok::semi)) {
4311 // A semicolon was missing after this declaration. Diagnose and recover.
4312 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4314 Tok.setKind(tok::semi);
4317 TUK = Sema::TUK_Reference;
4320 // If this is an elaborated type specifier, and we delayed
4321 // diagnostics before, just merge them into the current pool.
4322 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4323 diagsFromTag.redelay();
4326 MultiTemplateParamsArg TParams;
4327 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4328 TUK != Sema::TUK_Reference) {
4329 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4330 // Skip the rest of this declarator, up until the comma or semicolon.
4331 Diag(Tok, diag::err_enum_template);
4332 SkipUntil(tok::comma, StopAtSemi);
4336 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4337 // Enumerations can't be explicitly instantiated.
4338 DS.SetTypeSpecError();
4339 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4343 assert(TemplateInfo.TemplateParams && "no template parameters");
4344 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4345 TemplateInfo.TemplateParams->size());
4348 if (TUK == Sema::TUK_Reference)
4349 ProhibitAttributes(attrs);
4351 if (!Name && TUK != Sema::TUK_Definition) {
4352 Diag(Tok, diag::err_enumerator_unnamed_no_def);
4354 // Skip the rest of this declarator, up until the comma or semicolon.
4355 SkipUntil(tok::comma, StopAtSemi);
4359 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4361 Sema::SkipBodyInfo SkipBody;
4362 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4363 NextToken().is(tok::identifier))
4364 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4365 NextToken().getIdentifierInfo(),
4366 NextToken().getLocation());
4369 bool IsDependent = false;
4370 const char *PrevSpec = nullptr;
4372 Decl *TagDecl = Actions.ActOnTag(
4373 getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4374 attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4375 ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4376 DSC == DeclSpecContext::DSC_type_specifier,
4377 DSC == DeclSpecContext::DSC_template_param ||
4378 DSC == DeclSpecContext::DSC_template_type_arg,
4381 if (SkipBody.ShouldSkip) {
4382 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4384 BalancedDelimiterTracker T(*this, tok::l_brace);
4388 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4389 NameLoc.isValid() ? NameLoc : StartLoc,
4390 PrevSpec, DiagID, TagDecl, Owned,
4391 Actions.getASTContext().getPrintingPolicy()))
4392 Diag(StartLoc, DiagID) << PrevSpec;
4397 // This enum has a dependent nested-name-specifier. Handle it as a
4400 DS.SetTypeSpecError();
4401 Diag(Tok, diag::err_expected_type_name_after_typename);
4405 TypeResult Type = Actions.ActOnDependentTag(
4406 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4407 if (Type.isInvalid()) {
4408 DS.SetTypeSpecError();
4412 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4413 NameLoc.isValid() ? NameLoc : StartLoc,
4414 PrevSpec, DiagID, Type.get(),
4415 Actions.getASTContext().getPrintingPolicy()))
4416 Diag(StartLoc, DiagID) << PrevSpec;
4422 // The action failed to produce an enumeration tag. If this is a
4423 // definition, consume the entire definition.
4424 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4426 SkipUntil(tok::r_brace, StopAtSemi);
4429 DS.SetTypeSpecError();
4433 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4434 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4435 ParseEnumBody(StartLoc, D);
4436 if (SkipBody.CheckSameAsPrevious &&
4437 !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4438 DS.SetTypeSpecError();
4443 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4444 NameLoc.isValid() ? NameLoc : StartLoc,
4445 PrevSpec, DiagID, TagDecl, Owned,
4446 Actions.getASTContext().getPrintingPolicy()))
4447 Diag(StartLoc, DiagID) << PrevSpec;
4450 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4451 /// enumerator-list:
4453 /// enumerator-list ',' enumerator
4455 /// enumeration-constant attributes[opt]
4456 /// enumeration-constant attributes[opt] '=' constant-expression
4457 /// enumeration-constant:
4460 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4461 // Enter the scope of the enum body and start the definition.
4462 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4463 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4465 BalancedDelimiterTracker T(*this, tok::l_brace);
4468 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4469 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4470 Diag(Tok, diag::err_empty_enum);
4472 SmallVector<Decl *, 32> EnumConstantDecls;
4473 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4475 Decl *LastEnumConstDecl = nullptr;
4477 // Parse the enumerator-list.
4478 while (Tok.isNot(tok::r_brace)) {
4479 // Parse enumerator. If failed, try skipping till the start of the next
4480 // enumerator definition.
4481 if (Tok.isNot(tok::identifier)) {
4482 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4483 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4484 TryConsumeToken(tok::comma))
4488 IdentifierInfo *Ident = Tok.getIdentifierInfo();
4489 SourceLocation IdentLoc = ConsumeToken();
4491 // If attributes exist after the enumerator, parse them.
4492 ParsedAttributesWithRange attrs(AttrFactory);
4493 MaybeParseGNUAttributes(attrs);
4494 ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4495 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4496 if (getLangOpts().CPlusPlus)
4497 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4498 ? diag::warn_cxx14_compat_ns_enum_attribute
4499 : diag::ext_ns_enum_attribute)
4500 << 1 /*enumerator*/;
4501 ParseCXX11Attributes(attrs);
4504 SourceLocation EqualLoc;
4505 ExprResult AssignedVal;
4506 EnumAvailabilityDiags.emplace_back(*this);
4508 if (TryConsumeToken(tok::equal, EqualLoc)) {
4509 AssignedVal = ParseConstantExpression();
4510 if (AssignedVal.isInvalid())
4511 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4514 // Install the enumerator constant into EnumDecl.
4515 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4516 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4517 EqualLoc, AssignedVal.get());
4518 EnumAvailabilityDiags.back().done();
4520 EnumConstantDecls.push_back(EnumConstDecl);
4521 LastEnumConstDecl = EnumConstDecl;
4523 if (Tok.is(tok::identifier)) {
4524 // We're missing a comma between enumerators.
4525 SourceLocation Loc = getEndOfPreviousToken();
4526 Diag(Loc, diag::err_enumerator_list_missing_comma)
4527 << FixItHint::CreateInsertion(Loc, ", ");
4531 // Emumerator definition must be finished, only comma or r_brace are
4533 SourceLocation CommaLoc;
4534 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4535 if (EqualLoc.isValid())
4536 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4539 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4540 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4541 if (TryConsumeToken(tok::comma, CommaLoc))
4548 // If comma is followed by r_brace, emit appropriate warning.
4549 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4550 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4551 Diag(CommaLoc, getLangOpts().CPlusPlus ?
4552 diag::ext_enumerator_list_comma_cxx :
4553 diag::ext_enumerator_list_comma_c)
4554 << FixItHint::CreateRemoval(CommaLoc);
4555 else if (getLangOpts().CPlusPlus11)
4556 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4557 << FixItHint::CreateRemoval(CommaLoc);
4565 // If attributes exist after the identifier list, parse them.
4566 ParsedAttributes attrs(AttrFactory);
4567 MaybeParseGNUAttributes(attrs);
4569 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4570 getCurScope(), attrs);
4572 // Now handle enum constant availability diagnostics.
4573 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4574 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4575 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4576 EnumAvailabilityDiags[i].redelay();
4577 PD.complete(EnumConstantDecls[i]);
4581 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4583 // The next token must be valid after an enum definition. If not, a ';'
4584 // was probably forgotten.
4585 bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4586 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4587 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4588 // Push this token back into the preprocessor and change our current token
4589 // to ';' so that the rest of the code recovers as though there were an
4590 // ';' after the definition.
4592 Tok.setKind(tok::semi);
4596 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4597 /// is definitely a type-specifier. Return false if it isn't part of a type
4598 /// specifier or if we're not sure.
4599 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4600 switch (Tok.getKind()) {
4601 default: return false;
4605 case tok::kw___int64:
4606 case tok::kw___int128:
4607 case tok::kw_signed:
4608 case tok::kw_unsigned:
4609 case tok::kw__Complex:
4610 case tok::kw__Imaginary:
4613 case tok::kw_wchar_t:
4614 case tok::kw_char8_t:
4615 case tok::kw_char16_t:
4616 case tok::kw_char32_t:
4620 case tok::kw_double:
4621 case tok::kw__Accum:
4622 case tok::kw__Fract:
4623 case tok::kw__Float16:
4624 case tok::kw___float128:
4627 case tok::kw__Decimal32:
4628 case tok::kw__Decimal64:
4629 case tok::kw__Decimal128:
4630 case tok::kw___vector:
4631 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4632 #include "clang/Basic/OpenCLImageTypes.def"
4634 // struct-or-union-specifier (C99) or class-specifier (C++)
4636 case tok::kw_struct:
4637 case tok::kw___interface:
4643 case tok::annot_typename:
4648 /// isTypeSpecifierQualifier - Return true if the current token could be the
4649 /// start of a specifier-qualifier-list.
4650 bool Parser::isTypeSpecifierQualifier() {
4651 switch (Tok.getKind()) {
4652 default: return false;
4654 case tok::identifier: // foo::bar
4655 if (TryAltiVecVectorToken())
4658 case tok::kw_typename: // typename T::type
4659 // Annotate typenames and C++ scope specifiers. If we get one, just
4660 // recurse to handle whatever we get.
4661 if (TryAnnotateTypeOrScopeToken())
4663 if (Tok.is(tok::identifier))
4665 return isTypeSpecifierQualifier();
4667 case tok::coloncolon: // ::foo::bar
4668 if (NextToken().is(tok::kw_new) || // ::new
4669 NextToken().is(tok::kw_delete)) // ::delete
4672 if (TryAnnotateTypeOrScopeToken())
4674 return isTypeSpecifierQualifier();
4676 // GNU attributes support.
4677 case tok::kw___attribute:
4678 // GNU typeof support.
4679 case tok::kw_typeof:
4684 case tok::kw___int64:
4685 case tok::kw___int128:
4686 case tok::kw_signed:
4687 case tok::kw_unsigned:
4688 case tok::kw__Complex:
4689 case tok::kw__Imaginary:
4692 case tok::kw_wchar_t:
4693 case tok::kw_char8_t:
4694 case tok::kw_char16_t:
4695 case tok::kw_char32_t:
4699 case tok::kw_double:
4700 case tok::kw__Accum:
4701 case tok::kw__Fract:
4702 case tok::kw__Float16:
4703 case tok::kw___float128:
4706 case tok::kw__Decimal32:
4707 case tok::kw__Decimal64:
4708 case tok::kw__Decimal128:
4709 case tok::kw___vector:
4710 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4711 #include "clang/Basic/OpenCLImageTypes.def"
4713 // struct-or-union-specifier (C99) or class-specifier (C++)
4715 case tok::kw_struct:
4716 case tok::kw___interface:
4723 case tok::kw_volatile:
4724 case tok::kw_restrict:
4727 // Debugger support.
4728 case tok::kw___unknown_anytype:
4731 case tok::annot_typename:
4734 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4736 return getLangOpts().ObjC1;
4738 case tok::kw___cdecl:
4739 case tok::kw___stdcall:
4740 case tok::kw___fastcall:
4741 case tok::kw___thiscall:
4742 case tok::kw___regcall:
4743 case tok::kw___vectorcall:
4745 case tok::kw___ptr64:
4746 case tok::kw___ptr32:
4747 case tok::kw___pascal:
4748 case tok::kw___unaligned:
4750 case tok::kw__Nonnull:
4751 case tok::kw__Nullable:
4752 case tok::kw__Null_unspecified:
4754 case tok::kw___kindof:
4756 case tok::kw___private:
4757 case tok::kw___local:
4758 case tok::kw___global:
4759 case tok::kw___constant:
4760 case tok::kw___generic:
4761 case tok::kw___read_only:
4762 case tok::kw___read_write:
4763 case tok::kw___write_only:
4768 case tok::kw__Atomic:
4773 /// isDeclarationSpecifier() - Return true if the current token is part of a
4774 /// declaration specifier.
4776 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4777 /// this check is to disambiguate between an expression and a declaration.
4778 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4779 switch (Tok.getKind()) {
4780 default: return false;
4783 return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
4785 case tok::identifier: // foo::bar
4786 // Unfortunate hack to support "Class.factoryMethod" notation.
4787 if (getLangOpts().ObjC1 && NextToken().is(tok::period))
4789 if (TryAltiVecVectorToken())
4792 case tok::kw_decltype: // decltype(T())::type
4793 case tok::kw_typename: // typename T::type
4794 // Annotate typenames and C++ scope specifiers. If we get one, just
4795 // recurse to handle whatever we get.
4796 if (TryAnnotateTypeOrScopeToken())
4798 if (Tok.is(tok::identifier))
4801 // If we're in Objective-C and we have an Objective-C class type followed
4802 // by an identifier and then either ':' or ']', in a place where an
4803 // expression is permitted, then this is probably a class message send
4804 // missing the initial '['. In this case, we won't consider this to be
4805 // the start of a declaration.
4806 if (DisambiguatingWithExpression &&
4807 isStartOfObjCClassMessageMissingOpenBracket())
4810 return isDeclarationSpecifier();
4812 case tok::coloncolon: // ::foo::bar
4813 if (NextToken().is(tok::kw_new) || // ::new
4814 NextToken().is(tok::kw_delete)) // ::delete
4817 // Annotate typenames and C++ scope specifiers. If we get one, just
4818 // recurse to handle whatever we get.
4819 if (TryAnnotateTypeOrScopeToken())
4821 return isDeclarationSpecifier();
4823 // storage-class-specifier
4824 case tok::kw_typedef:
4825 case tok::kw_extern:
4826 case tok::kw___private_extern__:
4827 case tok::kw_static:
4829 case tok::kw___auto_type:
4830 case tok::kw_register:
4831 case tok::kw___thread:
4832 case tok::kw_thread_local:
4833 case tok::kw__Thread_local:
4836 case tok::kw___module_private__:
4839 case tok::kw___unknown_anytype:
4844 case tok::kw___int64:
4845 case tok::kw___int128:
4846 case tok::kw_signed:
4847 case tok::kw_unsigned:
4848 case tok::kw__Complex:
4849 case tok::kw__Imaginary:
4852 case tok::kw_wchar_t:
4853 case tok::kw_char8_t:
4854 case tok::kw_char16_t:
4855 case tok::kw_char32_t:
4860 case tok::kw_double:
4861 case tok::kw__Accum:
4862 case tok::kw__Fract:
4863 case tok::kw__Float16:
4864 case tok::kw___float128:
4867 case tok::kw__Decimal32:
4868 case tok::kw__Decimal64:
4869 case tok::kw__Decimal128:
4870 case tok::kw___vector:
4872 // struct-or-union-specifier (C99) or class-specifier (C++)
4874 case tok::kw_struct:
4876 case tok::kw___interface:
4882 case tok::kw_volatile:
4883 case tok::kw_restrict:
4886 // function-specifier
4887 case tok::kw_inline:
4888 case tok::kw_virtual:
4889 case tok::kw_explicit:
4890 case tok::kw__Noreturn:
4892 // alignment-specifier
4893 case tok::kw__Alignas:
4896 case tok::kw_friend:
4898 // static_assert-declaration
4899 case tok::kw__Static_assert:
4901 // GNU typeof support.
4902 case tok::kw_typeof:
4905 case tok::kw___attribute:
4907 // C++11 decltype and constexpr.
4908 case tok::annot_decltype:
4909 case tok::kw_constexpr:
4912 case tok::kw__Atomic:
4915 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4917 return getLangOpts().ObjC1;
4920 case tok::annot_typename:
4921 return !DisambiguatingWithExpression ||
4922 !isStartOfObjCClassMessageMissingOpenBracket();
4924 case tok::kw___declspec:
4925 case tok::kw___cdecl:
4926 case tok::kw___stdcall:
4927 case tok::kw___fastcall:
4928 case tok::kw___thiscall:
4929 case tok::kw___regcall:
4930 case tok::kw___vectorcall:
4932 case tok::kw___sptr:
4933 case tok::kw___uptr:
4934 case tok::kw___ptr64:
4935 case tok::kw___ptr32:
4936 case tok::kw___forceinline:
4937 case tok::kw___pascal:
4938 case tok::kw___unaligned:
4940 case tok::kw__Nonnull:
4941 case tok::kw__Nullable:
4942 case tok::kw__Null_unspecified:
4944 case tok::kw___kindof:
4946 case tok::kw___private:
4947 case tok::kw___local:
4948 case tok::kw___global:
4949 case tok::kw___constant:
4950 case tok::kw___generic:
4951 case tok::kw___read_only:
4952 case tok::kw___read_write:
4953 case tok::kw___write_only:
4954 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4955 #include "clang/Basic/OpenCLImageTypes.def"
4961 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
4962 TentativeParsingAction TPA(*this);
4964 // Parse the C++ scope specifier.
4966 if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
4967 /*EnteringContext=*/true)) {
4972 // Parse the constructor name.
4973 if (Tok.is(tok::identifier)) {
4974 // We already know that we have a constructor name; just consume
4977 } else if (Tok.is(tok::annot_template_id)) {
4978 ConsumeAnnotationToken();
4984 // There may be attributes here, appertaining to the constructor name or type
4985 // we just stepped past.
4986 SkipCXX11Attributes();
4988 // Current class name must be followed by a left parenthesis.
4989 if (Tok.isNot(tok::l_paren)) {
4995 // A right parenthesis, or ellipsis followed by a right parenthesis signals
4996 // that we have a constructor.
4997 if (Tok.is(tok::r_paren) ||
4998 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5003 // A C++11 attribute here signals that we have a constructor, and is an
5004 // attribute on the first constructor parameter.
5005 if (getLangOpts().CPlusPlus11 &&
5006 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5007 /*OuterMightBeMessageSend*/ true)) {
5012 // If we need to, enter the specified scope.
5013 DeclaratorScopeObj DeclScopeObj(*this, SS);
5014 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5015 DeclScopeObj.EnterDeclaratorScope();
5017 // Optionally skip Microsoft attributes.
5018 ParsedAttributes Attrs(AttrFactory);
5019 MaybeParseMicrosoftAttributes(Attrs);
5021 // Check whether the next token(s) are part of a declaration
5022 // specifier, in which case we have the start of a parameter and,
5023 // therefore, we know that this is a constructor.
5024 bool IsConstructor = false;
5025 if (isDeclarationSpecifier())
5026 IsConstructor = true;
5027 else if (Tok.is(tok::identifier) ||
5028 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5029 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5030 // This might be a parenthesized member name, but is more likely to
5031 // be a constructor declaration with an invalid argument type. Keep
5033 if (Tok.is(tok::annot_cxxscope))
5034 ConsumeAnnotationToken();
5037 // If this is not a constructor, we must be parsing a declarator,
5038 // which must have one of the following syntactic forms (see the
5039 // grammar extract at the start of ParseDirectDeclarator):
5040 switch (Tok.getKind()) {
5045 // C(X [ [attribute]]);
5046 case tok::coloncolon:
5049 // Assume this isn't a constructor, rather than assuming it's a
5050 // constructor with an unnamed parameter of an ill-formed type.
5056 // Skip past the right-paren and any following attributes to get to
5057 // the function body or trailing-return-type.
5059 SkipCXX11Attributes();
5061 if (DeductionGuide) {
5062 // C(X) -> ... is a deduction guide.
5063 IsConstructor = Tok.is(tok::arrow);
5066 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5067 // Assume these were meant to be constructors:
5068 // C(X) : (the name of a bit-field cannot be parenthesized).
5069 // C(X) try (this is otherwise ill-formed).
5070 IsConstructor = true;
5072 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5073 // If we have a constructor name within the class definition,
5074 // assume these were meant to be constructors:
5077 // ... because otherwise we would be declaring a non-static data
5078 // member that is ill-formed because it's of the same type as its
5079 // surrounding class.
5081 // FIXME: We can actually do this whether or not the name is qualified,
5082 // because if it is qualified in this context it must be being used as
5083 // a constructor name.
5084 // currently, so we're somewhat conservative here.
5085 IsConstructor = IsUnqualified;
5090 IsConstructor = true;
5096 return IsConstructor;
5099 /// ParseTypeQualifierListOpt
5100 /// type-qualifier-list: [C99 6.7.5]
5102 /// [vendor] attributes
5103 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5104 /// type-qualifier-list type-qualifier
5105 /// [vendor] type-qualifier-list attributes
5106 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5107 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5108 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5109 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5110 /// AttrRequirements bitmask values.
5111 void Parser::ParseTypeQualifierListOpt(
5112 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5113 bool IdentifierRequired,
5114 Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5115 if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5116 isCXX11AttributeSpecifier()) {
5117 ParsedAttributesWithRange attrs(AttrFactory);
5118 ParseCXX11Attributes(attrs);
5119 DS.takeAttributesFrom(attrs);
5122 SourceLocation EndLoc;
5125 bool isInvalid = false;
5126 const char *PrevSpec = nullptr;
5127 unsigned DiagID = 0;
5128 SourceLocation Loc = Tok.getLocation();
5130 switch (Tok.getKind()) {
5131 case tok::code_completion:
5132 if (CodeCompletionHandler)
5133 (*CodeCompletionHandler)();
5135 Actions.CodeCompleteTypeQualifiers(DS);
5136 return cutOffParsing();
5139 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5142 case tok::kw_volatile:
5143 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5146 case tok::kw_restrict:
5147 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5150 case tok::kw__Atomic:
5152 goto DoneWithTypeQuals;
5153 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5157 // OpenCL qualifiers:
5158 case tok::kw___private:
5159 case tok::kw___global:
5160 case tok::kw___local:
5161 case tok::kw___constant:
5162 case tok::kw___generic:
5163 case tok::kw___read_only:
5164 case tok::kw___write_only:
5165 case tok::kw___read_write:
5166 ParseOpenCLQualifiers(DS.getAttributes());
5169 case tok::kw___unaligned:
5170 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5173 case tok::kw___uptr:
5174 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5175 // with the MS modifier keyword.
5176 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5177 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5178 if (TryKeywordIdentFallback(false))
5182 case tok::kw___sptr:
5184 case tok::kw___ptr64:
5185 case tok::kw___ptr32:
5186 case tok::kw___cdecl:
5187 case tok::kw___stdcall:
5188 case tok::kw___fastcall:
5189 case tok::kw___thiscall:
5190 case tok::kw___regcall:
5191 case tok::kw___vectorcall:
5192 if (AttrReqs & AR_DeclspecAttributesParsed) {
5193 ParseMicrosoftTypeAttributes(DS.getAttributes());
5196 goto DoneWithTypeQuals;
5197 case tok::kw___pascal:
5198 if (AttrReqs & AR_VendorAttributesParsed) {
5199 ParseBorlandTypeAttributes(DS.getAttributes());
5202 goto DoneWithTypeQuals;
5204 // Nullability type specifiers.
5205 case tok::kw__Nonnull:
5206 case tok::kw__Nullable:
5207 case tok::kw__Null_unspecified:
5208 ParseNullabilityTypeSpecifiers(DS.getAttributes());
5211 // Objective-C 'kindof' types.
5212 case tok::kw___kindof:
5213 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5214 nullptr, 0, ParsedAttr::AS_Keyword);
5215 (void)ConsumeToken();
5218 case tok::kw___attribute:
5219 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5220 // When GNU attributes are expressly forbidden, diagnose their usage.
5221 Diag(Tok, diag::err_attributes_not_allowed);
5223 // Parse the attributes even if they are rejected to ensure that error
5224 // recovery is graceful.
5225 if (AttrReqs & AR_GNUAttributesParsed ||
5226 AttrReqs & AR_GNUAttributesParsedAndRejected) {
5227 ParseGNUAttributes(DS.getAttributes());
5228 continue; // do *not* consume the next token!
5230 // otherwise, FALL THROUGH!
5234 // If this is not a type-qualifier token, we're done reading type
5235 // qualifiers. First verify that DeclSpec's are consistent.
5236 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5237 if (EndLoc.isValid())
5238 DS.SetRangeEnd(EndLoc);
5242 // If the specifier combination wasn't legal, issue a diagnostic.
5244 assert(PrevSpec && "Method did not return previous specifier!");
5245 Diag(Tok, DiagID) << PrevSpec;
5247 EndLoc = ConsumeToken();
5251 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5253 void Parser::ParseDeclarator(Declarator &D) {
5254 /// This implements the 'declarator' production in the C grammar, then checks
5255 /// for well-formedness and issues diagnostics.
5256 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5259 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5260 DeclaratorContext TheContext) {
5261 if (Kind == tok::star || Kind == tok::caret)
5264 if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
5267 if (!Lang.CPlusPlus)
5270 if (Kind == tok::amp)
5273 // We parse rvalue refs in C++03, because otherwise the errors are scary.
5274 // But we must not parse them in conversion-type-ids and new-type-ids, since
5275 // those can be legitimately followed by a && operator.
5276 // (The same thing can in theory happen after a trailing-return-type, but
5277 // since those are a C++11 feature, there is no rejects-valid issue there.)
5278 if (Kind == tok::ampamp)
5279 return Lang.CPlusPlus11 ||
5280 (TheContext != DeclaratorContext::ConversionIdContext &&
5281 TheContext != DeclaratorContext::CXXNewContext);
5286 // Indicates whether the given declarator is a pipe declarator.
5287 static bool isPipeDeclerator(const Declarator &D) {
5288 const unsigned NumTypes = D.getNumTypeObjects();
5290 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5291 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5297 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5298 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5299 /// isn't parsed at all, making this function effectively parse the C++
5300 /// ptr-operator production.
5302 /// If the grammar of this construct is extended, matching changes must also be
5303 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5304 /// isConstructorDeclarator.
5306 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5307 /// [C] pointer[opt] direct-declarator
5308 /// [C++] direct-declarator
5309 /// [C++] ptr-operator declarator
5311 /// pointer: [C99 6.7.5]
5312 /// '*' type-qualifier-list[opt]
5313 /// '*' type-qualifier-list[opt] pointer
5316 /// '*' cv-qualifier-seq[opt]
5319 /// [GNU] '&' restrict[opt] attributes[opt]
5320 /// [GNU?] '&&' restrict[opt] attributes[opt]
5321 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5322 void Parser::ParseDeclaratorInternal(Declarator &D,
5323 DirectDeclParseFunction DirectDeclParser) {
5324 if (Diags.hasAllExtensionsSilenced())
5327 // C++ member pointers start with a '::' or a nested-name.
5328 // Member pointers get special handling, since there's no place for the
5329 // scope spec in the generic path below.
5330 if (getLangOpts().CPlusPlus &&
5331 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5332 (Tok.is(tok::identifier) &&
5333 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5334 Tok.is(tok::annot_cxxscope))) {
5335 bool EnteringContext =
5336 D.getContext() == DeclaratorContext::FileContext ||
5337 D.getContext() == DeclaratorContext::MemberContext;
5339 ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5341 if (SS.isNotEmpty()) {
5342 if (Tok.isNot(tok::star)) {
5343 // The scope spec really belongs to the direct-declarator.
5344 if (D.mayHaveIdentifier())
5345 D.getCXXScopeSpec() = SS;
5347 AnnotateScopeToken(SS, true);
5349 if (DirectDeclParser)
5350 (this->*DirectDeclParser)(D);
5354 SourceLocation Loc = ConsumeToken();
5356 DeclSpec DS(AttrFactory);
5357 ParseTypeQualifierListOpt(DS);
5358 D.ExtendWithDeclSpec(DS);
5360 // Recurse to parse whatever is left.
5361 ParseDeclaratorInternal(D, DirectDeclParser);
5363 // Sema will have to catch (syntactically invalid) pointers into global
5364 // scope. It has to catch pointers into namespace scope anyway.
5365 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5366 SS, DS.getTypeQualifiers(), DS.getLocEnd()),
5367 std::move(DS.getAttributes()),
5368 /* Don't replace range end. */ SourceLocation());
5373 tok::TokenKind Kind = Tok.getKind();
5375 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5376 DeclSpec DS(AttrFactory);
5377 ParseTypeQualifierListOpt(DS);
5380 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5381 std::move(DS.getAttributes()), SourceLocation());
5384 // Not a pointer, C++ reference, or block.
5385 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5386 if (DirectDeclParser)
5387 (this->*DirectDeclParser)(D);
5391 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5392 // '&&' -> rvalue reference
5393 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5396 if (Kind == tok::star || Kind == tok::caret) {
5398 DeclSpec DS(AttrFactory);
5400 // GNU attributes are not allowed here in a new-type-id, but Declspec and
5401 // C++11 attributes are allowed.
5402 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5403 ((D.getContext() != DeclaratorContext::CXXNewContext)
5404 ? AR_GNUAttributesParsed
5405 : AR_GNUAttributesParsedAndRejected);
5406 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5407 D.ExtendWithDeclSpec(DS);
5409 // Recursively parse the declarator.
5410 ParseDeclaratorInternal(D, DirectDeclParser);
5411 if (Kind == tok::star)
5412 // Remember that we parsed a pointer type, and remember the type-quals.
5413 D.AddTypeInfo(DeclaratorChunk::getPointer(
5414 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5415 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5416 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5417 std::move(DS.getAttributes()), SourceLocation());
5419 // Remember that we parsed a Block type, and remember the type-quals.
5421 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5422 std::move(DS.getAttributes()), SourceLocation());
5425 DeclSpec DS(AttrFactory);
5427 // Complain about rvalue references in C++03, but then go on and build
5429 if (Kind == tok::ampamp)
5430 Diag(Loc, getLangOpts().CPlusPlus11 ?
5431 diag::warn_cxx98_compat_rvalue_reference :
5432 diag::ext_rvalue_reference);
5434 // GNU-style and C++11 attributes are allowed here, as is restrict.
5435 ParseTypeQualifierListOpt(DS);
5436 D.ExtendWithDeclSpec(DS);
5438 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5439 // cv-qualifiers are introduced through the use of a typedef or of a
5440 // template type argument, in which case the cv-qualifiers are ignored.
5441 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5442 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5443 Diag(DS.getConstSpecLoc(),
5444 diag::err_invalid_reference_qualifier_application) << "const";
5445 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5446 Diag(DS.getVolatileSpecLoc(),
5447 diag::err_invalid_reference_qualifier_application) << "volatile";
5448 // 'restrict' is permitted as an extension.
5449 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5450 Diag(DS.getAtomicSpecLoc(),
5451 diag::err_invalid_reference_qualifier_application) << "_Atomic";
5454 // Recursively parse the declarator.
5455 ParseDeclaratorInternal(D, DirectDeclParser);
5457 if (D.getNumTypeObjects() > 0) {
5458 // C++ [dcl.ref]p4: There shall be no references to references.
5459 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5460 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5461 if (const IdentifierInfo *II = D.getIdentifier())
5462 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5465 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5468 // Once we've complained about the reference-to-reference, we
5469 // can go ahead and build the (technically ill-formed)
5470 // declarator: reference collapsing will take care of it.
5474 // Remember that we parsed a reference type.
5475 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5477 std::move(DS.getAttributes()), SourceLocation());
5481 // When correcting from misplaced brackets before the identifier, the location
5482 // is saved inside the declarator so that other diagnostic messages can use
5483 // them. This extracts and returns that location, or returns the provided
5484 // location if a stored location does not exist.
5485 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5486 SourceLocation Loc) {
5487 if (D.getName().StartLocation.isInvalid() &&
5488 D.getName().EndLocation.isValid())
5489 return D.getName().EndLocation;
5494 /// ParseDirectDeclarator
5495 /// direct-declarator: [C99 6.7.5]
5496 /// [C99] identifier
5497 /// '(' declarator ')'
5498 /// [GNU] '(' attributes declarator ')'
5499 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5500 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5501 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5502 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5503 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5504 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5505 /// attribute-specifier-seq[opt]
5506 /// direct-declarator '(' parameter-type-list ')'
5507 /// direct-declarator '(' identifier-list[opt] ')'
5508 /// [GNU] direct-declarator '(' parameter-forward-declarations
5509 /// parameter-type-list[opt] ')'
5510 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5511 /// cv-qualifier-seq[opt] exception-specification[opt]
5512 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5513 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5514 /// ref-qualifier[opt] exception-specification[opt]
5515 /// [C++] declarator-id
5516 /// [C++11] declarator-id attribute-specifier-seq[opt]
5518 /// declarator-id: [C++ 8]
5519 /// '...'[opt] id-expression
5520 /// '::'[opt] nested-name-specifier[opt] type-name
5522 /// id-expression: [C++ 5.1]
5526 /// unqualified-id: [C++ 5.1]
5528 /// operator-function-id
5529 /// conversion-function-id
5533 /// C++17 adds the following, which we also handle here:
5535 /// simple-declaration:
5536 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5538 /// Note, any additional constructs added here may need corresponding changes
5539 /// in isConstructorDeclarator.
5540 void Parser::ParseDirectDeclarator(Declarator &D) {
5541 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5543 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5544 // This might be a C++17 structured binding.
5545 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5546 D.getCXXScopeSpec().isEmpty())
5547 return ParseDecompositionDeclarator(D);
5549 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5550 // this context it is a bitfield. Also in range-based for statement colon
5551 // may delimit for-range-declaration.
5552 ColonProtectionRAIIObject X(
5553 *this, D.getContext() == DeclaratorContext::MemberContext ||
5554 (D.getContext() == DeclaratorContext::ForContext &&
5555 getLangOpts().CPlusPlus11));
5557 // ParseDeclaratorInternal might already have parsed the scope.
5558 if (D.getCXXScopeSpec().isEmpty()) {
5559 bool EnteringContext =
5560 D.getContext() == DeclaratorContext::FileContext ||
5561 D.getContext() == DeclaratorContext::MemberContext;
5562 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5566 if (D.getCXXScopeSpec().isValid()) {
5567 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5568 D.getCXXScopeSpec()))
5569 // Change the declaration context for name lookup, until this function
5570 // is exited (and the declarator has been parsed).
5571 DeclScopeObj.EnterDeclaratorScope();
5572 else if (getObjCDeclContext()) {
5573 // Ensure that we don't interpret the next token as an identifier when
5574 // dealing with declarations in an Objective-C container.
5575 D.SetIdentifier(nullptr, Tok.getLocation());
5576 D.setInvalidType(true);
5578 goto PastIdentifier;
5582 // C++0x [dcl.fct]p14:
5583 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5584 // parameter-declaration-clause without a preceding comma. In this case,
5585 // the ellipsis is parsed as part of the abstract-declarator if the type
5586 // of the parameter either names a template parameter pack that has not
5587 // been expanded or contains auto; otherwise, it is parsed as part of the
5588 // parameter-declaration-clause.
5589 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5590 !((D.getContext() == DeclaratorContext::PrototypeContext ||
5591 D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5592 D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5593 NextToken().is(tok::r_paren) &&
5594 !D.hasGroupingParens() &&
5595 !Actions.containsUnexpandedParameterPacks(D) &&
5596 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5597 SourceLocation EllipsisLoc = ConsumeToken();
5598 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5599 // The ellipsis was put in the wrong place. Recover, and explain to
5600 // the user what they should have done.
5602 if (EllipsisLoc.isValid())
5603 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5606 D.setEllipsisLoc(EllipsisLoc);
5608 // The ellipsis can't be followed by a parenthesized declarator. We
5609 // check for that in ParseParenDeclarator, after we have disambiguated
5610 // the l_paren token.
5613 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5615 // We found something that indicates the start of an unqualified-id.
5616 // Parse that unqualified-id.
5617 bool AllowConstructorName;
5618 bool AllowDeductionGuide;
5619 if (D.getDeclSpec().hasTypeSpecifier()) {
5620 AllowConstructorName = false;
5621 AllowDeductionGuide = false;
5622 } else if (D.getCXXScopeSpec().isSet()) {
5623 AllowConstructorName =
5624 (D.getContext() == DeclaratorContext::FileContext ||
5625 D.getContext() == DeclaratorContext::MemberContext);
5626 AllowDeductionGuide = false;
5628 AllowConstructorName =
5629 (D.getContext() == DeclaratorContext::MemberContext);
5630 AllowDeductionGuide =
5631 (D.getContext() == DeclaratorContext::FileContext ||
5632 D.getContext() == DeclaratorContext::MemberContext);
5635 bool HadScope = D.getCXXScopeSpec().isValid();
5636 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5637 /*EnteringContext=*/true,
5638 /*AllowDestructorName=*/true, AllowConstructorName,
5639 AllowDeductionGuide, nullptr, nullptr,
5641 // Once we're past the identifier, if the scope was bad, mark the
5642 // whole declarator bad.
5643 D.getCXXScopeSpec().isInvalid()) {
5644 D.SetIdentifier(nullptr, Tok.getLocation());
5645 D.setInvalidType(true);
5647 // ParseUnqualifiedId might have parsed a scope specifier during error
5648 // recovery. If it did so, enter that scope.
5649 if (!HadScope && D.getCXXScopeSpec().isValid() &&
5650 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5651 D.getCXXScopeSpec()))
5652 DeclScopeObj.EnterDeclaratorScope();
5654 // Parsed the unqualified-id; update range information and move along.
5655 if (D.getSourceRange().getBegin().isInvalid())
5656 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5657 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5659 goto PastIdentifier;
5662 if (D.getCXXScopeSpec().isNotEmpty()) {
5663 // We have a scope specifier but no following unqualified-id.
5664 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5665 diag::err_expected_unqualified_id)
5667 D.SetIdentifier(nullptr, Tok.getLocation());
5668 goto PastIdentifier;
5670 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5671 assert(!getLangOpts().CPlusPlus &&
5672 "There's a C++-specific check for tok::identifier above");
5673 assert(Tok.getIdentifierInfo() && "Not an identifier?");
5674 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5675 D.SetRangeEnd(Tok.getLocation());
5677 goto PastIdentifier;
5678 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5679 // We're not allowed an identifier here, but we got one. Try to figure out
5680 // if the user was trying to attach a name to the type, or whether the name
5681 // is some unrelated trailing syntax.
5682 bool DiagnoseIdentifier = false;
5683 if (D.hasGroupingParens())
5684 // An identifier within parens is unlikely to be intended to be anything
5685 // other than a name being "declared".
5686 DiagnoseIdentifier = true;
5687 else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5688 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5689 DiagnoseIdentifier =
5690 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5691 else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5692 D.getContext() == DeclaratorContext::AliasTemplateContext)
5693 // The most likely error is that the ';' was forgotten.
5694 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5695 else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5696 D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5697 !isCXX11VirtSpecifier(Tok))
5698 DiagnoseIdentifier = NextToken().isOneOf(
5699 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5700 if (DiagnoseIdentifier) {
5701 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5702 << FixItHint::CreateRemoval(Tok.getLocation());
5703 D.SetIdentifier(nullptr, Tok.getLocation());
5705 goto PastIdentifier;
5709 if (Tok.is(tok::l_paren)) {
5710 // If this might be an abstract-declarator followed by a direct-initializer,
5711 // check whether this is a valid declarator chunk. If it can't be, assume
5712 // that it's an initializer instead.
5713 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5714 RevertingTentativeParsingAction PA(*this);
5715 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5717 D.SetIdentifier(nullptr, Tok.getLocation());
5718 goto PastIdentifier;
5722 // direct-declarator: '(' declarator ')'
5723 // direct-declarator: '(' attributes declarator ')'
5724 // Example: 'char (*X)' or 'int (*XX)(void)'
5725 ParseParenDeclarator(D);
5727 // If the declarator was parenthesized, we entered the declarator
5728 // scope when parsing the parenthesized declarator, then exited
5729 // the scope already. Re-enter the scope, if we need to.
5730 if (D.getCXXScopeSpec().isSet()) {
5731 // If there was an error parsing parenthesized declarator, declarator
5732 // scope may have been entered before. Don't do it again.
5733 if (!D.isInvalidType() &&
5734 Actions.ShouldEnterDeclaratorScope(getCurScope(),
5735 D.getCXXScopeSpec()))
5736 // Change the declaration context for name lookup, until this function
5737 // is exited (and the declarator has been parsed).
5738 DeclScopeObj.EnterDeclaratorScope();
5740 } else if (D.mayOmitIdentifier()) {
5741 // This could be something simple like "int" (in which case the declarator
5742 // portion is empty), if an abstract-declarator is allowed.
5743 D.SetIdentifier(nullptr, Tok.getLocation());
5745 // The grammar for abstract-pack-declarator does not allow grouping parens.
5746 // FIXME: Revisit this once core issue 1488 is resolved.
5747 if (D.hasEllipsis() && D.hasGroupingParens())
5748 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5749 diag::ext_abstract_pack_declarator_parens);
5751 if (Tok.getKind() == tok::annot_pragma_parser_crash)
5753 if (Tok.is(tok::l_square))
5754 return ParseMisplacedBracketDeclarator(D);
5755 if (D.getContext() == DeclaratorContext::MemberContext) {
5756 // Objective-C++: Detect C++ keywords and try to prevent further errors by
5757 // treating these keyword as valid member names.
5758 if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
5759 Tok.getIdentifierInfo() &&
5760 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5761 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5762 diag::err_expected_member_name_or_semi_objcxx_keyword)
5763 << Tok.getIdentifierInfo()
5764 << (D.getDeclSpec().isEmpty() ? SourceRange()
5765 : D.getDeclSpec().getSourceRange());
5766 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5767 D.SetRangeEnd(Tok.getLocation());
5769 goto PastIdentifier;
5771 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5772 diag::err_expected_member_name_or_semi)
5773 << (D.getDeclSpec().isEmpty() ? SourceRange()
5774 : D.getDeclSpec().getSourceRange());
5775 } else if (getLangOpts().CPlusPlus) {
5776 if (Tok.isOneOf(tok::period, tok::arrow))
5777 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5779 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5780 if (Tok.isAtStartOfLine() && Loc.isValid())
5781 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5782 << getLangOpts().CPlusPlus;
5784 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5785 diag::err_expected_unqualified_id)
5786 << getLangOpts().CPlusPlus;
5789 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5790 diag::err_expected_either)
5791 << tok::identifier << tok::l_paren;
5793 D.SetIdentifier(nullptr, Tok.getLocation());
5794 D.setInvalidType(true);
5798 assert(D.isPastIdentifier() &&
5799 "Haven't past the location of the identifier yet?");
5801 // Don't parse attributes unless we have parsed an unparenthesized name.
5802 if (D.hasName() && !D.getNumTypeObjects())
5803 MaybeParseCXX11Attributes(D);
5806 if (Tok.is(tok::l_paren)) {
5807 // Enter function-declaration scope, limiting any declarators to the
5808 // function prototype scope, including parameter declarators.
5809 ParseScope PrototypeScope(this,
5810 Scope::FunctionPrototypeScope|Scope::DeclScope|
5811 (D.isFunctionDeclaratorAFunctionDeclaration()
5812 ? Scope::FunctionDeclarationScope : 0));
5814 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
5815 // In such a case, check if we actually have a function declarator; if it
5816 // is not, the declarator has been fully parsed.
5817 bool IsAmbiguous = false;
5818 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
5819 // The name of the declarator, if any, is tentatively declared within
5820 // a possible direct initializer.
5821 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
5822 bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
5823 TentativelyDeclaredIdentifiers.pop_back();
5824 if (!IsFunctionDecl)
5827 ParsedAttributes attrs(AttrFactory);
5828 BalancedDelimiterTracker T(*this, tok::l_paren);
5830 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
5831 PrototypeScope.Exit();
5832 } else if (Tok.is(tok::l_square)) {
5833 ParseBracketDeclarator(D);
5840 void Parser::ParseDecompositionDeclarator(Declarator &D) {
5841 assert(Tok.is(tok::l_square));
5843 // If this doesn't look like a structured binding, maybe it's a misplaced
5844 // array declarator.
5845 // FIXME: Consume the l_square first so we don't need extra lookahead for
5847 if (!(NextToken().is(tok::identifier) &&
5848 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
5849 !(NextToken().is(tok::r_square) &&
5850 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
5851 return ParseMisplacedBracketDeclarator(D);
5853 BalancedDelimiterTracker T(*this, tok::l_square);
5856 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
5857 while (Tok.isNot(tok::r_square)) {
5858 if (!Bindings.empty()) {
5859 if (Tok.is(tok::comma))
5862 if (Tok.is(tok::identifier)) {
5863 SourceLocation EndLoc = getEndOfPreviousToken();
5864 Diag(EndLoc, diag::err_expected)
5865 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
5867 Diag(Tok, diag::err_expected_comma_or_rsquare);
5870 SkipUntil(tok::r_square, tok::comma, tok::identifier,
5871 StopAtSemi | StopBeforeMatch);
5872 if (Tok.is(tok::comma))
5874 else if (Tok.isNot(tok::identifier))
5879 if (Tok.isNot(tok::identifier)) {
5880 Diag(Tok, diag::err_expected) << tok::identifier;
5884 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
5888 if (Tok.isNot(tok::r_square))
5889 // We've already diagnosed a problem here.
5892 // C++17 does not allow the identifier-list in a structured binding
5894 if (Bindings.empty())
5895 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
5900 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
5901 T.getCloseLocation());
5904 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
5905 /// only called before the identifier, so these are most likely just grouping
5906 /// parens for precedence. If we find that these are actually function
5907 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
5909 /// direct-declarator:
5910 /// '(' declarator ')'
5911 /// [GNU] '(' attributes declarator ')'
5912 /// direct-declarator '(' parameter-type-list ')'
5913 /// direct-declarator '(' identifier-list[opt] ')'
5914 /// [GNU] direct-declarator '(' parameter-forward-declarations
5915 /// parameter-type-list[opt] ')'
5917 void Parser::ParseParenDeclarator(Declarator &D) {
5918 BalancedDelimiterTracker T(*this, tok::l_paren);
5921 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
5923 // Eat any attributes before we look at whether this is a grouping or function
5924 // declarator paren. If this is a grouping paren, the attribute applies to
5925 // the type being built up, for example:
5926 // int (__attribute__(()) *x)(long y)
5927 // If this ends up not being a grouping paren, the attribute applies to the
5928 // first argument, for example:
5929 // int (__attribute__(()) int x)
5930 // In either case, we need to eat any attributes to be able to determine what
5931 // sort of paren this is.
5933 ParsedAttributes attrs(AttrFactory);
5934 bool RequiresArg = false;
5935 if (Tok.is(tok::kw___attribute)) {
5936 ParseGNUAttributes(attrs);
5938 // We require that the argument list (if this is a non-grouping paren) be
5939 // present even if the attribute list was empty.
5943 // Eat any Microsoft extensions.
5944 ParseMicrosoftTypeAttributes(attrs);
5946 // Eat any Borland extensions.
5947 if (Tok.is(tok::kw___pascal))
5948 ParseBorlandTypeAttributes(attrs);
5950 // If we haven't past the identifier yet (or where the identifier would be
5951 // stored, if this is an abstract declarator), then this is probably just
5952 // grouping parens. However, if this could be an abstract-declarator, then
5953 // this could also be the start of function arguments (consider 'void()').
5956 if (!D.mayOmitIdentifier()) {
5957 // If this can't be an abstract-declarator, this *must* be a grouping
5958 // paren, because we haven't seen the identifier yet.
5960 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
5961 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
5962 NextToken().is(tok::r_paren)) || // C++ int(...)
5963 isDeclarationSpecifier() || // 'int(int)' is a function.
5964 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
5965 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
5966 // considered to be a type, not a K&R identifier-list.
5969 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
5973 // If this is a grouping paren, handle:
5974 // direct-declarator: '(' declarator ')'
5975 // direct-declarator: '(' attributes declarator ')'
5977 SourceLocation EllipsisLoc = D.getEllipsisLoc();
5978 D.setEllipsisLoc(SourceLocation());
5980 bool hadGroupingParens = D.hasGroupingParens();
5981 D.setGroupingParens(true);
5982 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5986 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
5987 std::move(attrs), T.getCloseLocation());
5989 D.setGroupingParens(hadGroupingParens);
5991 // An ellipsis cannot be placed outside parentheses.
5992 if (EllipsisLoc.isValid())
5993 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5998 // Okay, if this wasn't a grouping paren, it must be the start of a function
5999 // argument list. Recognize that this declarator will never have an
6000 // identifier (and remember where it would have been), then call into
6001 // ParseFunctionDeclarator to handle of argument list.
6002 D.SetIdentifier(nullptr, Tok.getLocation());
6004 // Enter function-declaration scope, limiting any declarators to the
6005 // function prototype scope, including parameter declarators.
6006 ParseScope PrototypeScope(this,
6007 Scope::FunctionPrototypeScope | Scope::DeclScope |
6008 (D.isFunctionDeclaratorAFunctionDeclaration()
6009 ? Scope::FunctionDeclarationScope : 0));
6010 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6011 PrototypeScope.Exit();
6014 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6015 /// declarator D up to a paren, which indicates that we are parsing function
6018 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6019 /// immediately after the open paren - they should be considered to be the
6020 /// first argument of a parameter.
6022 /// If RequiresArg is true, then the first argument of the function is required
6023 /// to be present and required to not be an identifier list.
6025 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6026 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6027 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6029 /// [C++11] exception-specification:
6030 /// dynamic-exception-specification
6031 /// noexcept-specification
6033 void Parser::ParseFunctionDeclarator(Declarator &D,
6034 ParsedAttributes &FirstArgAttrs,
6035 BalancedDelimiterTracker &Tracker,
6038 assert(getCurScope()->isFunctionPrototypeScope() &&
6039 "Should call from a Function scope");
6040 // lparen is already consumed!
6041 assert(D.isPastIdentifier() && "Should not call before identifier!");
6043 // This should be true when the function has typed arguments.
6044 // Otherwise, it is treated as a K&R-style function.
6045 bool HasProto = false;
6046 // Build up an array of information about the parsed arguments.
6047 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6048 // Remember where we see an ellipsis, if any.
6049 SourceLocation EllipsisLoc;
6051 DeclSpec DS(AttrFactory);
6052 bool RefQualifierIsLValueRef = true;
6053 SourceLocation RefQualifierLoc;
6054 SourceLocation ConstQualifierLoc;
6055 SourceLocation VolatileQualifierLoc;
6056 SourceLocation RestrictQualifierLoc;
6057 ExceptionSpecificationType ESpecType = EST_None;
6058 SourceRange ESpecRange;
6059 SmallVector<ParsedType, 2> DynamicExceptions;
6060 SmallVector<SourceRange, 2> DynamicExceptionRanges;
6061 ExprResult NoexceptExpr;
6062 CachedTokens *ExceptionSpecTokens = nullptr;
6063 ParsedAttributesWithRange FnAttrs(AttrFactory);
6064 TypeResult TrailingReturnType;
6066 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6067 EndLoc is the end location for the function declarator.
6068 They differ for trailing return types. */
6069 SourceLocation StartLoc, LocalEndLoc, EndLoc;
6070 SourceLocation LParenLoc, RParenLoc;
6071 LParenLoc = Tracker.getOpenLocation();
6072 StartLoc = LParenLoc;
6074 if (isFunctionDeclaratorIdentifierList()) {
6076 Diag(Tok, diag::err_argument_required_after_attribute);
6078 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6080 Tracker.consumeClose();
6081 RParenLoc = Tracker.getCloseLocation();
6082 LocalEndLoc = RParenLoc;
6085 // If there are attributes following the identifier list, parse them and
6087 MaybeParseCXX11Attributes(FnAttrs);
6088 ProhibitAttributes(FnAttrs);
6090 if (Tok.isNot(tok::r_paren))
6091 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6093 else if (RequiresArg)
6094 Diag(Tok, diag::err_argument_required_after_attribute);
6096 HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6097 || getLangOpts().OpenCL;
6099 // If we have the closing ')', eat it.
6100 Tracker.consumeClose();
6101 RParenLoc = Tracker.getCloseLocation();
6102 LocalEndLoc = RParenLoc;
6105 if (getLangOpts().CPlusPlus) {
6106 // FIXME: Accept these components in any order, and produce fixits to
6107 // correct the order if the user gets it wrong. Ideally we should deal
6108 // with the pure-specifier in the same way.
6110 // Parse cv-qualifier-seq[opt].
6111 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6112 /*AtomicAllowed*/ false,
6113 /*IdentifierRequired=*/false,
6114 llvm::function_ref<void()>([&]() {
6115 Actions.CodeCompleteFunctionQualifiers(DS, D);
6117 if (!DS.getSourceRange().getEnd().isInvalid()) {
6118 EndLoc = DS.getSourceRange().getEnd();
6119 ConstQualifierLoc = DS.getConstSpecLoc();
6120 VolatileQualifierLoc = DS.getVolatileSpecLoc();
6121 RestrictQualifierLoc = DS.getRestrictSpecLoc();
6124 // Parse ref-qualifier[opt].
6125 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6126 EndLoc = RefQualifierLoc;
6128 // C++11 [expr.prim.general]p3:
6129 // If a declaration declares a member function or member function
6130 // template of a class X, the expression this is a prvalue of type
6131 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6132 // and the end of the function-definition, member-declarator, or
6134 // FIXME: currently, "static" case isn't handled correctly.
6135 bool IsCXX11MemberFunction =
6136 getLangOpts().CPlusPlus11 &&
6137 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6138 (D.getContext() == DeclaratorContext::MemberContext
6139 ? !D.getDeclSpec().isFriendSpecified()
6140 : D.getContext() == DeclaratorContext::FileContext &&
6141 D.getCXXScopeSpec().isValid() &&
6142 Actions.CurContext->isRecord());
6143 Sema::CXXThisScopeRAII ThisScope(Actions,
6144 dyn_cast<CXXRecordDecl>(Actions.CurContext),
6145 DS.getTypeQualifiers() |
6146 (D.getDeclSpec().isConstexprSpecified() &&
6147 !getLangOpts().CPlusPlus14
6148 ? Qualifiers::Const : 0),
6149 IsCXX11MemberFunction);
6151 // Parse exception-specification[opt].
6152 bool Delayed = D.isFirstDeclarationOfMember() &&
6153 D.isFunctionDeclaratorAFunctionDeclaration();
6154 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6155 GetLookAheadToken(0).is(tok::kw_noexcept) &&
6156 GetLookAheadToken(1).is(tok::l_paren) &&
6157 GetLookAheadToken(2).is(tok::kw_noexcept) &&
6158 GetLookAheadToken(3).is(tok::l_paren) &&
6159 GetLookAheadToken(4).is(tok::identifier) &&
6160 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6161 // HACK: We've got an exception-specification
6162 // noexcept(noexcept(swap(...)))
6164 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6165 // on a 'swap' member function. This is a libstdc++ bug; the lookup
6166 // for 'swap' will only find the function we're currently declaring,
6167 // whereas it expects to find a non-member swap through ADL. Turn off
6168 // delayed parsing to give it a chance to find what it expects.
6171 ESpecType = tryParseExceptionSpecification(Delayed,
6174 DynamicExceptionRanges,
6176 ExceptionSpecTokens);
6177 if (ESpecType != EST_None)
6178 EndLoc = ESpecRange.getEnd();
6180 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6181 // after the exception-specification.
6182 MaybeParseCXX11Attributes(FnAttrs);
6184 // Parse trailing-return-type[opt].
6185 LocalEndLoc = EndLoc;
6186 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6187 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6188 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6189 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6190 LocalEndLoc = Tok.getLocation();
6192 TrailingReturnType =
6193 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6194 EndLoc = Range.getEnd();
6196 } else if (standardAttributesAllowed()) {
6197 MaybeParseCXX11Attributes(FnAttrs);
6201 // Collect non-parameter declarations from the prototype if this is a function
6202 // declaration. They will be moved into the scope of the function. Only do
6203 // this in C and not C++, where the decls will continue to live in the
6204 // surrounding context.
6205 SmallVector<NamedDecl *, 0> DeclsInPrototype;
6206 if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6207 !getLangOpts().CPlusPlus) {
6208 for (Decl *D : getCurScope()->decls()) {
6209 NamedDecl *ND = dyn_cast<NamedDecl>(D);
6210 if (!ND || isa<ParmVarDecl>(ND))
6212 DeclsInPrototype.push_back(ND);
6216 // Remember that we parsed a function type, and remember the attributes.
6217 D.AddTypeInfo(DeclaratorChunk::getFunction(
6218 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6219 ParamInfo.size(), EllipsisLoc, RParenLoc,
6220 DS.getTypeQualifiers(), RefQualifierIsLValueRef,
6221 RefQualifierLoc, ConstQualifierLoc, VolatileQualifierLoc,
6222 RestrictQualifierLoc,
6223 /*MutableLoc=*/SourceLocation(), ESpecType, ESpecRange,
6224 DynamicExceptions.data(), DynamicExceptionRanges.data(),
6225 DynamicExceptions.size(),
6226 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6227 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6228 LocalEndLoc, D, TrailingReturnType),
6229 std::move(FnAttrs), EndLoc);
6232 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6233 /// true if a ref-qualifier is found.
6234 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6235 SourceLocation &RefQualifierLoc) {
6236 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6237 Diag(Tok, getLangOpts().CPlusPlus11 ?
6238 diag::warn_cxx98_compat_ref_qualifier :
6239 diag::ext_ref_qualifier);
6241 RefQualifierIsLValueRef = Tok.is(tok::amp);
6242 RefQualifierLoc = ConsumeToken();
6248 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6249 /// identifier list form for a K&R-style function: void foo(a,b,c)
6251 /// Note that identifier-lists are only allowed for normal declarators, not for
6252 /// abstract-declarators.
6253 bool Parser::isFunctionDeclaratorIdentifierList() {
6254 return !getLangOpts().CPlusPlus
6255 && Tok.is(tok::identifier)
6256 && !TryAltiVecVectorToken()
6257 // K&R identifier lists can't have typedefs as identifiers, per C99
6259 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6260 // Identifier lists follow a really simple grammar: the identifiers can
6261 // be followed *only* by a ", identifier" or ")". However, K&R
6262 // identifier lists are really rare in the brave new modern world, and
6263 // it is very common for someone to typo a type in a non-K&R style
6264 // list. If we are presented with something like: "void foo(intptr x,
6265 // float y)", we don't want to start parsing the function declarator as
6266 // though it is a K&R style declarator just because intptr is an
6269 // To handle this, we check to see if the token after the first
6270 // identifier is a "," or ")". Only then do we parse it as an
6272 && (!Tok.is(tok::eof) &&
6273 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6276 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6277 /// we found a K&R-style identifier list instead of a typed parameter list.
6279 /// After returning, ParamInfo will hold the parsed parameters.
6281 /// identifier-list: [C99 6.7.5]
6283 /// identifier-list ',' identifier
6285 void Parser::ParseFunctionDeclaratorIdentifierList(
6287 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6288 // If there was no identifier specified for the declarator, either we are in
6289 // an abstract-declarator, or we are in a parameter declarator which was found
6290 // to be abstract. In abstract-declarators, identifier lists are not valid:
6292 if (!D.getIdentifier())
6293 Diag(Tok, diag::ext_ident_list_in_param);
6295 // Maintain an efficient lookup of params we have seen so far.
6296 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6299 // If this isn't an identifier, report the error and skip until ')'.
6300 if (Tok.isNot(tok::identifier)) {
6301 Diag(Tok, diag::err_expected) << tok::identifier;
6302 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6303 // Forget we parsed anything.
6308 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6310 // Reject 'typedef int y; int test(x, y)', but continue parsing.
6311 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6312 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6314 // Verify that the argument identifier has not already been mentioned.
6315 if (!ParamsSoFar.insert(ParmII).second) {
6316 Diag(Tok, diag::err_param_redefinition) << ParmII;
6318 // Remember this identifier in ParamInfo.
6319 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6324 // Eat the identifier.
6326 // The list continues if we see a comma.
6327 } while (TryConsumeToken(tok::comma));
6330 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6331 /// after the opening parenthesis. This function will not parse a K&R-style
6332 /// identifier list.
6334 /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
6335 /// caller parsed those arguments immediately after the open paren - they should
6336 /// be considered to be part of the first parameter.
6338 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6339 /// be the location of the ellipsis, if any was parsed.
6341 /// parameter-type-list: [C99 6.7.5]
6343 /// parameter-list ',' '...'
6344 /// [C++] parameter-list '...'
6346 /// parameter-list: [C99 6.7.5]
6347 /// parameter-declaration
6348 /// parameter-list ',' parameter-declaration
6350 /// parameter-declaration: [C99 6.7.5]
6351 /// declaration-specifiers declarator
6352 /// [C++] declaration-specifiers declarator '=' assignment-expression
6353 /// [C++11] initializer-clause
6354 /// [GNU] declaration-specifiers declarator attributes
6355 /// declaration-specifiers abstract-declarator[opt]
6356 /// [C++] declaration-specifiers abstract-declarator[opt]
6357 /// '=' assignment-expression
6358 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
6359 /// [C++11] attribute-specifier-seq parameter-declaration
6361 void Parser::ParseParameterDeclarationClause(
6363 ParsedAttributes &FirstArgAttrs,
6364 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6365 SourceLocation &EllipsisLoc) {
6367 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6368 // before deciding this was a parameter-declaration-clause.
6369 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6372 // Parse the declaration-specifiers.
6373 // Just use the ParsingDeclaration "scope" of the declarator.
6374 DeclSpec DS(AttrFactory);
6376 // Parse any C++11 attributes.
6377 MaybeParseCXX11Attributes(DS.getAttributes());
6379 // Skip any Microsoft attributes before a param.
6380 MaybeParseMicrosoftAttributes(DS.getAttributes());
6382 SourceLocation DSStart = Tok.getLocation();
6384 // If the caller parsed attributes for the first argument, add them now.
6385 // Take them so that we only apply the attributes to the first parameter.
6386 // FIXME: If we can leave the attributes in the token stream somehow, we can
6387 // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6389 DS.takeAttributesFrom(FirstArgAttrs);
6391 ParseDeclarationSpecifiers(DS);
6394 // Parse the declarator. This is "PrototypeContext" or
6395 // "LambdaExprParameterContext", because we must accept either
6396 // 'declarator' or 'abstract-declarator' here.
6397 Declarator ParmDeclarator(
6398 DS, D.getContext() == DeclaratorContext::LambdaExprContext
6399 ? DeclaratorContext::LambdaExprParameterContext
6400 : DeclaratorContext::PrototypeContext);
6401 ParseDeclarator(ParmDeclarator);
6403 // Parse GNU attributes, if present.
6404 MaybeParseGNUAttributes(ParmDeclarator);
6406 // Remember this parsed parameter in ParamInfo.
6407 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6409 // DefArgToks is used when the parsing of default arguments needs
6411 std::unique_ptr<CachedTokens> DefArgToks;
6413 // If no parameter was specified, verify that *something* was specified,
6414 // otherwise we have a missing type and identifier.
6415 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6416 ParmDeclarator.getNumTypeObjects() == 0) {
6417 // Completely missing, emit error.
6418 Diag(DSStart, diag::err_missing_param);
6420 // Otherwise, we have something. Add it and let semantic analysis try
6421 // to grok it and add the result to the ParamInfo we are building.
6423 // Last chance to recover from a misplaced ellipsis in an attempted
6424 // parameter pack declaration.
6425 if (Tok.is(tok::ellipsis) &&
6426 (NextToken().isNot(tok::r_paren) ||
6427 (!ParmDeclarator.getEllipsisLoc().isValid() &&
6428 !Actions.isUnexpandedParameterPackPermitted())) &&
6429 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6430 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6432 // Inform the actions module about the parameter declarator, so it gets
6433 // added to the current scope.
6434 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6435 // Parse the default argument, if any. We parse the default
6436 // arguments in all dialects; the semantic analysis in
6437 // ActOnParamDefaultArgument will reject the default argument in
6439 if (Tok.is(tok::equal)) {
6440 SourceLocation EqualLoc = Tok.getLocation();
6442 // Parse the default argument
6443 if (D.getContext() == DeclaratorContext::MemberContext) {
6444 // If we're inside a class definition, cache the tokens
6445 // corresponding to the default argument. We'll actually parse
6446 // them when we see the end of the class definition.
6447 DefArgToks.reset(new CachedTokens);
6449 SourceLocation ArgStartLoc = NextToken().getLocation();
6450 if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6452 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6454 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6461 // The argument isn't actually potentially evaluated unless it is
6463 EnterExpressionEvaluationContext Eval(
6465 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6468 ExprResult DefArgResult;
6469 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6470 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6471 DefArgResult = ParseBraceInitializer();
6473 DefArgResult = ParseAssignmentExpression();
6474 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6475 if (DefArgResult.isInvalid()) {
6476 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6477 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6479 // Inform the actions module about the default argument
6480 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6481 DefArgResult.get());
6486 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6487 ParmDeclarator.getIdentifierLoc(),
6488 Param, std::move(DefArgToks)));
6491 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6492 if (!getLangOpts().CPlusPlus) {
6493 // We have ellipsis without a preceding ',', which is ill-formed
6494 // in C. Complain and provide the fix.
6495 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6496 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6497 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6498 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6499 // It looks like this was supposed to be a parameter pack. Warn and
6500 // point out where the ellipsis should have gone.
6501 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6502 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6503 << ParmEllipsis.isValid() << ParmEllipsis;
6504 if (ParmEllipsis.isValid()) {
6506 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6508 Diag(ParmDeclarator.getIdentifierLoc(),
6509 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6510 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6512 << !ParmDeclarator.hasName();
6514 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6515 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6518 // We can't have any more parameters after an ellipsis.
6522 // If the next token is a comma, consume it and keep reading arguments.
6523 } while (TryConsumeToken(tok::comma));
6526 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6527 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6528 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6529 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6530 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6531 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6532 /// attribute-specifier-seq[opt]
6533 void Parser::ParseBracketDeclarator(Declarator &D) {
6534 if (CheckProhibitedCXX11Attribute())
6537 BalancedDelimiterTracker T(*this, tok::l_square);
6540 // C array syntax has many features, but by-far the most common is [] and [4].
6541 // This code does a fast path to handle some of the most obvious cases.
6542 if (Tok.getKind() == tok::r_square) {
6544 ParsedAttributes attrs(AttrFactory);
6545 MaybeParseCXX11Attributes(attrs);
6547 // Remember that we parsed the empty array type.
6548 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6549 T.getOpenLocation(),
6550 T.getCloseLocation()),
6551 std::move(attrs), T.getCloseLocation());
6553 } else if (Tok.getKind() == tok::numeric_constant &&
6554 GetLookAheadToken(1).is(tok::r_square)) {
6555 // [4] is very common. Parse the numeric constant expression.
6556 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6560 ParsedAttributes attrs(AttrFactory);
6561 MaybeParseCXX11Attributes(attrs);
6563 // Remember that we parsed a array type, and remember its features.
6564 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6565 T.getOpenLocation(),
6566 T.getCloseLocation()),
6567 std::move(attrs), T.getCloseLocation());
6569 } else if (Tok.getKind() == tok::code_completion) {
6570 Actions.CodeCompleteBracketDeclarator(getCurScope());
6571 return cutOffParsing();
6574 // If valid, this location is the position where we read the 'static' keyword.
6575 SourceLocation StaticLoc;
6576 TryConsumeToken(tok::kw_static, StaticLoc);
6578 // If there is a type-qualifier-list, read it now.
6579 // Type qualifiers in an array subscript are a C99 feature.
6580 DeclSpec DS(AttrFactory);
6581 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6583 // If we haven't already read 'static', check to see if there is one after the
6584 // type-qualifier-list.
6585 if (!StaticLoc.isValid())
6586 TryConsumeToken(tok::kw_static, StaticLoc);
6588 // Handle "direct-declarator [ type-qual-list[opt] * ]".
6589 bool isStar = false;
6590 ExprResult NumElements;
6592 // Handle the case where we have '[*]' as the array size. However, a leading
6593 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
6594 // the token after the star is a ']'. Since stars in arrays are
6595 // infrequent, use of lookahead is not costly here.
6596 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6597 ConsumeToken(); // Eat the '*'.
6599 if (StaticLoc.isValid()) {
6600 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6601 StaticLoc = SourceLocation(); // Drop the static.
6604 } else if (Tok.isNot(tok::r_square)) {
6605 // Note, in C89, this production uses the constant-expr production instead
6606 // of assignment-expr. The only difference is that assignment-expr allows
6607 // things like '=' and '*='. Sema rejects these in C89 mode because they
6608 // are not i-c-e's, so we don't need to distinguish between the two here.
6610 // Parse the constant-expression or assignment-expression now (depending
6612 if (getLangOpts().CPlusPlus) {
6613 NumElements = ParseConstantExpression();
6615 EnterExpressionEvaluationContext Unevaluated(
6616 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6618 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6621 if (StaticLoc.isValid()) {
6622 Diag(StaticLoc, diag::err_unspecified_size_with_static);
6623 StaticLoc = SourceLocation(); // Drop the static.
6627 // If there was an error parsing the assignment-expression, recover.
6628 if (NumElements.isInvalid()) {
6629 D.setInvalidType(true);
6630 // If the expression was invalid, skip it.
6631 SkipUntil(tok::r_square, StopAtSemi);
6637 MaybeParseCXX11Attributes(DS.getAttributes());
6639 // Remember that we parsed a array type, and remember its features.
6641 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6642 isStar, NumElements.get(), T.getOpenLocation(),
6643 T.getCloseLocation()),
6644 std::move(DS.getAttributes()), T.getCloseLocation());
6647 /// Diagnose brackets before an identifier.
6648 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6649 assert(Tok.is(tok::l_square) && "Missing opening bracket");
6650 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6652 SourceLocation StartBracketLoc = Tok.getLocation();
6653 Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6655 while (Tok.is(tok::l_square)) {
6656 ParseBracketDeclarator(TempDeclarator);
6659 // Stuff the location of the start of the brackets into the Declarator.
6660 // The diagnostics from ParseDirectDeclarator will make more sense if
6661 // they use this location instead.
6662 if (Tok.is(tok::semi))
6663 D.getName().EndLocation = StartBracketLoc;
6665 SourceLocation SuggestParenLoc = Tok.getLocation();
6667 // Now that the brackets are removed, try parsing the declarator again.
6668 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6670 // Something went wrong parsing the brackets, in which case,
6671 // ParseBracketDeclarator has emitted an error, and we don't need to emit
6673 if (TempDeclarator.getNumTypeObjects() == 0)
6676 // Determine if parens will need to be suggested in the diagnostic.
6677 bool NeedParens = false;
6678 if (D.getNumTypeObjects() != 0) {
6679 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6680 case DeclaratorChunk::Pointer:
6681 case DeclaratorChunk::Reference:
6682 case DeclaratorChunk::BlockPointer:
6683 case DeclaratorChunk::MemberPointer:
6684 case DeclaratorChunk::Pipe:
6687 case DeclaratorChunk::Array:
6688 case DeclaratorChunk::Function:
6689 case DeclaratorChunk::Paren:
6695 // Create a DeclaratorChunk for the inserted parens.
6696 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6697 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
6701 // Adding back the bracket info to the end of the Declarator.
6702 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6703 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6704 D.AddTypeInfo(Chunk, SourceLocation());
6707 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6708 // If parentheses are required, always suggest them.
6709 if (!D.getIdentifier() && !NeedParens)
6712 SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
6714 // Generate the move bracket error message.
6715 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6716 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
6719 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6720 << getLangOpts().CPlusPlus
6721 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6722 << FixItHint::CreateInsertion(EndLoc, ")")
6723 << FixItHint::CreateInsertionFromRange(
6724 EndLoc, CharSourceRange(BracketRange, true))
6725 << FixItHint::CreateRemoval(BracketRange);
6727 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6728 << getLangOpts().CPlusPlus
6729 << FixItHint::CreateInsertionFromRange(
6730 EndLoc, CharSourceRange(BracketRange, true))
6731 << FixItHint::CreateRemoval(BracketRange);
6735 /// [GNU] typeof-specifier:
6736 /// typeof ( expressions )
6737 /// typeof ( type-name )
6738 /// [GNU/C++] typeof unary-expression
6740 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6741 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6743 SourceLocation StartLoc = ConsumeToken();
6745 const bool hasParens = Tok.is(tok::l_paren);
6747 EnterExpressionEvaluationContext Unevaluated(
6748 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6749 Sema::ReuseLambdaContextDecl);
6753 SourceRange CastRange;
6754 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6755 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6757 DS.setTypeofParensRange(CastRange);
6759 if (CastRange.getEnd().isInvalid())
6760 // FIXME: Not accurate, the range gets one token more than it should.
6761 DS.SetRangeEnd(Tok.getLocation());
6763 DS.SetRangeEnd(CastRange.getEnd());
6767 DS.SetTypeSpecError();
6771 const char *PrevSpec = nullptr;
6773 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6774 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6776 Actions.getASTContext().getPrintingPolicy()))
6777 Diag(StartLoc, DiagID) << PrevSpec;
6781 // If we get here, the operand to the typeof was an expression.
6782 if (Operand.isInvalid()) {
6783 DS.SetTypeSpecError();
6787 // We might need to transform the operand if it is potentially evaluated.
6788 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
6789 if (Operand.isInvalid()) {
6790 DS.SetTypeSpecError();
6794 const char *PrevSpec = nullptr;
6796 // Check for duplicate type specifiers (e.g. "int typeof(int)").
6797 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
6798 DiagID, Operand.get(),
6799 Actions.getASTContext().getPrintingPolicy()))
6800 Diag(StartLoc, DiagID) << PrevSpec;
6803 /// [C11] atomic-specifier:
6804 /// _Atomic ( type-name )
6806 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
6807 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
6808 "Not an atomic specifier");
6810 SourceLocation StartLoc = ConsumeToken();
6811 BalancedDelimiterTracker T(*this, tok::l_paren);
6812 if (T.consumeOpen())
6815 TypeResult Result = ParseTypeName();
6816 if (Result.isInvalid()) {
6817 SkipUntil(tok::r_paren, StopAtSemi);
6824 if (T.getCloseLocation().isInvalid())
6827 DS.setTypeofParensRange(T.getRange());
6828 DS.SetRangeEnd(T.getCloseLocation());
6830 const char *PrevSpec = nullptr;
6832 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
6833 DiagID, Result.get(),
6834 Actions.getASTContext().getPrintingPolicy()))
6835 Diag(StartLoc, DiagID) << PrevSpec;
6838 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
6839 /// from TryAltiVecVectorToken.
6840 bool Parser::TryAltiVecVectorTokenOutOfLine() {
6841 Token Next = NextToken();
6842 switch (Next.getKind()) {
6843 default: return false;
6846 case tok::kw_signed:
6847 case tok::kw_unsigned:
6852 case tok::kw_double:
6854 case tok::kw___bool:
6855 case tok::kw___pixel:
6856 Tok.setKind(tok::kw___vector);
6858 case tok::identifier:
6859 if (Next.getIdentifierInfo() == Ident_pixel) {
6860 Tok.setKind(tok::kw___vector);
6863 if (Next.getIdentifierInfo() == Ident_bool) {
6864 Tok.setKind(tok::kw___vector);
6871 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
6872 const char *&PrevSpec, unsigned &DiagID,
6874 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
6875 if (Tok.getIdentifierInfo() == Ident_vector) {
6876 Token Next = NextToken();
6877 switch (Next.getKind()) {
6880 case tok::kw_signed:
6881 case tok::kw_unsigned:
6886 case tok::kw_double:
6888 case tok::kw___bool:
6889 case tok::kw___pixel:
6890 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
6892 case tok::identifier:
6893 if (Next.getIdentifierInfo() == Ident_pixel) {
6894 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6897 if (Next.getIdentifierInfo() == Ident_bool) {
6898 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
6905 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
6906 DS.isTypeAltiVecVector()) {
6907 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
6909 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
6910 DS.isTypeAltiVecVector()) {
6911 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);