1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Declaration portions of the Parser interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/AddressSpaces.h"
17 #include "clang/Basic/AttributeCommonInfo.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Parse/ParseDiagnostic.h"
22 #include "clang/Parse/Parser.h"
23 #include "clang/Parse/RAIIObjectsForParser.h"
24 #include "clang/Sema/EnterExpressionEvaluationContext.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/SemaDiagnostic.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringSwitch.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // C99 6.7: Declarations.
38 //===----------------------------------------------------------------------===//
41 /// type-name: [C99 6.7.6]
42 /// specifier-qualifier-list abstract-declarator[opt]
44 /// Called type-id in C++.
45 TypeResult Parser::ParseTypeName(SourceRange *Range, DeclaratorContext Context,
46 AccessSpecifier AS, Decl **OwnedType,
47 ParsedAttributes *Attrs) {
48 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49 if (DSC == DeclSpecContext::DSC_normal)
50 DSC = DeclSpecContext::DSC_type_specifier;
52 // Parse the common declaration-specifiers piece.
53 DeclSpec DS(AttrFactory);
55 DS.addAttributes(*Attrs);
56 ParseSpecifierQualifierList(DS, AS, DSC);
58 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
60 // Move declspec attributes to ParsedAttributes
62 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
63 for (ParsedAttr &AL : DS.getAttributes()) {
64 if (AL.isDeclspecAttribute())
65 ToBeMoved.push_back(&AL);
68 for (ParsedAttr *AL : ToBeMoved)
69 Attrs->takeOneFrom(DS.getAttributes(), AL);
72 // Parse the abstract-declarator, if present.
73 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
74 ParseDeclarator(DeclaratorInfo);
76 *Range = DeclaratorInfo.getSourceRange();
78 if (DeclaratorInfo.isInvalidType())
81 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
84 /// Normalizes an attribute name by dropping prefixed and suffixed __.
85 static StringRef normalizeAttrName(StringRef Name) {
86 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
87 return Name.drop_front(2).drop_back(2);
91 /// isAttributeLateParsed - Return true if the attribute has arguments that
92 /// require late parsing.
93 static bool isAttributeLateParsed(const IdentifierInfo &II) {
94 #define CLANG_ATTR_LATE_PARSED_LIST
95 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
96 #include "clang/Parse/AttrParserStringSwitches.inc"
98 #undef CLANG_ATTR_LATE_PARSED_LIST
101 /// Check if the a start and end source location expand to the same macro.
102 static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
103 SourceLocation EndLoc) {
104 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
107 SourceManager &SM = PP.getSourceManager();
108 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
111 bool AttrStartIsInMacro =
112 Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
113 bool AttrEndIsInMacro =
114 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
115 return AttrStartIsInMacro && AttrEndIsInMacro;
118 void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
119 LateParsedAttrList *LateAttrs) {
122 // Assume there's nothing left to parse, but if any attributes are in fact
123 // parsed, loop to ensure all specified attribute combinations are parsed.
125 if (WhichAttrKinds & PAKM_CXX11)
126 MoreToParse |= MaybeParseCXX11Attributes(Attrs);
127 if (WhichAttrKinds & PAKM_GNU)
128 MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
129 if (WhichAttrKinds & PAKM_Declspec)
130 MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
131 } while (MoreToParse);
134 /// ParseGNUAttributes - Parse a non-empty attributes list.
136 /// [GNU] attributes:
138 /// attributes attribute
141 /// '__attribute__' '(' '(' attribute-list ')' ')'
143 /// [GNU] attribute-list:
145 /// attribute_list ',' attrib
150 /// attrib-name '(' identifier ')'
151 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
152 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
154 /// [GNU] attrib-name:
160 /// Whether an attribute takes an 'identifier' is determined by the
161 /// attrib-name. GCC's behavior here is not worth imitating:
163 /// * In C mode, if the attribute argument list starts with an identifier
164 /// followed by a ',' or an ')', and the identifier doesn't resolve to
165 /// a type, it is parsed as an identifier. If the attribute actually
166 /// wanted an expression, it's out of luck (but it turns out that no
167 /// attributes work that way, because C constant expressions are very
169 /// * In C++ mode, if the attribute argument list starts with an identifier,
170 /// and the attribute *wants* an identifier, it is parsed as an identifier.
171 /// At block scope, any additional tokens between the identifier and the
172 /// ',' or ')' are ignored, otherwise they produce a parse error.
174 /// We follow the C++ model, but don't allow junk after the identifier.
175 void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
176 LateParsedAttrList *LateAttrs, Declarator *D) {
177 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
179 SourceLocation StartLoc = Tok.getLocation();
180 SourceLocation EndLoc = StartLoc;
182 while (Tok.is(tok::kw___attribute)) {
183 SourceLocation AttrTokLoc = ConsumeToken();
184 unsigned OldNumAttrs = Attrs.size();
185 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
187 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
189 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
192 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
193 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
196 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
198 // Eat preceeding commas to allow __attribute__((,,,foo))
199 while (TryConsumeToken(tok::comma))
202 // Expect an identifier or declaration specifier (const, int, etc.)
203 if (Tok.isAnnotation())
205 if (Tok.is(tok::code_completion)) {
207 Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
210 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
214 SourceLocation AttrNameLoc = ConsumeToken();
216 if (Tok.isNot(tok::l_paren)) {
217 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
218 ParsedAttr::Form::GNU());
222 // Handle "parameterized" attributes
223 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
224 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
225 SourceLocation(), ParsedAttr::Form::GNU(), D);
229 // Handle attributes with arguments that require late parsing.
230 LateParsedAttribute *LA =
231 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
232 LateAttrs->push_back(LA);
234 // Attributes in a class are parsed at the end of the class, along
235 // with other late-parsed declarations.
236 if (!ClassStack.empty() && !LateAttrs->parseSoon())
237 getCurrentClass().LateParsedDeclarations.push_back(LA);
239 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
240 // recursively consumes balanced parens.
241 LA->Toks.push_back(Tok);
243 // Consume everything up to and including the matching right parens.
244 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
248 Eof.setLocation(Tok.getLocation());
249 LA->Toks.push_back(Eof);
250 } while (Tok.is(tok::comma));
252 if (ExpectAndConsume(tok::r_paren))
253 SkipUntil(tok::r_paren, StopAtSemi);
254 SourceLocation Loc = Tok.getLocation();
255 if (ExpectAndConsume(tok::r_paren))
256 SkipUntil(tok::r_paren, StopAtSemi);
259 // If this was declared in a macro, attach the macro IdentifierInfo to the
261 auto &SM = PP.getSourceManager();
262 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
263 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
264 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
265 StringRef FoundName =
266 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
267 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
269 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
270 Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
273 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
274 (*LateAttrs)[i]->MacroII = MacroII;
279 Attrs.Range = SourceRange(StartLoc, EndLoc);
282 /// Determine whether the given attribute has an identifier argument.
283 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
284 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
285 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
286 #include "clang/Parse/AttrParserStringSwitches.inc"
288 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
291 /// Determine whether the given attribute has a variadic identifier argument.
292 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
293 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
294 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
295 #include "clang/Parse/AttrParserStringSwitches.inc"
297 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
300 /// Determine whether the given attribute treats kw_this as an identifier.
301 static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
302 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
303 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
304 #include "clang/Parse/AttrParserStringSwitches.inc"
306 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
309 /// Determine if an attribute accepts parameter packs.
310 static bool attributeAcceptsExprPack(const IdentifierInfo &II) {
311 #define CLANG_ATTR_ACCEPTS_EXPR_PACK
312 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
313 #include "clang/Parse/AttrParserStringSwitches.inc"
315 #undef CLANG_ATTR_ACCEPTS_EXPR_PACK
318 /// Determine whether the given attribute parses a type argument.
319 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
320 #define CLANG_ATTR_TYPE_ARG_LIST
321 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
322 #include "clang/Parse/AttrParserStringSwitches.inc"
324 #undef CLANG_ATTR_TYPE_ARG_LIST
327 /// Determine whether the given attribute requires parsing its arguments
328 /// in an unevaluated context or not.
329 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
330 #define CLANG_ATTR_ARG_CONTEXT_LIST
331 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
332 #include "clang/Parse/AttrParserStringSwitches.inc"
334 #undef CLANG_ATTR_ARG_CONTEXT_LIST
337 IdentifierLoc *Parser::ParseIdentifierLoc() {
338 assert(Tok.is(tok::identifier) && "expected an identifier");
339 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
341 Tok.getIdentifierInfo());
346 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
347 SourceLocation AttrNameLoc,
348 ParsedAttributes &Attrs,
349 IdentifierInfo *ScopeName,
350 SourceLocation ScopeLoc,
351 ParsedAttr::Form Form) {
352 BalancedDelimiterTracker Parens(*this, tok::l_paren);
353 Parens.consumeOpen();
356 if (Tok.isNot(tok::r_paren))
359 if (Parens.consumeClose())
366 Attrs.addNewTypeAttr(&AttrName,
367 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
368 ScopeName, ScopeLoc, T.get(), Form);
370 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
371 ScopeName, ScopeLoc, nullptr, 0, Form);
374 unsigned Parser::ParseAttributeArgsCommon(
375 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
376 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
377 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
378 // Ignore the left paren location for now.
381 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
382 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
383 bool AttributeHasVariadicIdentifierArg =
384 attributeHasVariadicIdentifierArg(*AttrName);
386 // Interpret "kw_this" as an identifier if the attributed requests it.
387 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
388 Tok.setKind(tok::identifier);
391 if (Tok.is(tok::identifier)) {
392 // If this attribute wants an 'identifier' argument, make it so.
393 bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
394 attributeHasIdentifierArg(*AttrName);
395 ParsedAttr::Kind AttrKind =
396 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
398 // If we don't know how to parse this attribute, but this is the only
399 // token in this argument, assume it's meant to be an identifier.
400 if (AttrKind == ParsedAttr::UnknownAttribute ||
401 AttrKind == ParsedAttr::IgnoredAttribute) {
402 const Token &Next = NextToken();
403 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
407 ArgExprs.push_back(ParseIdentifierLoc());
410 ParsedType TheParsedType;
411 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
413 if (!ArgExprs.empty())
416 if (AttributeIsTypeArgAttr) {
417 // FIXME: Multiple type arguments are not implemented.
418 TypeResult T = ParseTypeName();
420 SkipUntil(tok::r_paren, StopAtSemi);
424 TheParsedType = T.get();
425 } else if (AttributeHasVariadicIdentifierArg) {
426 // Parse variadic identifier arg. This can either consume identifiers or
427 // expressions. Variadic identifier args do not support parameter packs
428 // because those are typically used for attributes with enumeration
429 // arguments, and those enumerations are not something the user could
430 // express via a pack.
432 // Interpret "kw_this" as an identifier if the attributed requests it.
433 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
434 Tok.setKind(tok::identifier);
437 if (Tok.is(tok::identifier)) {
438 ArgExprs.push_back(ParseIdentifierLoc());
440 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
441 EnterExpressionEvaluationContext Unevaluated(
443 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
444 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
447 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
449 if (ArgExpr.isInvalid()) {
450 SkipUntil(tok::r_paren, StopAtSemi);
453 ArgExprs.push_back(ArgExpr.get());
455 // Eat the comma, move to the next argument
456 } while (TryConsumeToken(tok::comma));
458 // General case. Parse all available expressions.
459 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
460 EnterExpressionEvaluationContext Unevaluated(
462 ? Sema::ExpressionEvaluationContext::Unevaluated
463 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
465 ExprVector ParsedExprs;
466 if (ParseExpressionList(ParsedExprs, llvm::function_ref<void()>(),
467 /*FailImmediatelyOnInvalidExpr=*/true,
468 /*EarlyTypoCorrection=*/true)) {
469 SkipUntil(tok::r_paren, StopAtSemi);
473 // Pack expansion must currently be explicitly supported by an attribute.
474 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
475 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
478 if (!attributeAcceptsExprPack(*AttrName)) {
479 Diag(Tok.getLocation(),
480 diag::err_attribute_argument_parm_pack_not_supported)
482 SkipUntil(tok::r_paren, StopAtSemi);
487 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
491 SourceLocation RParen = Tok.getLocation();
492 if (!ExpectAndConsume(tok::r_paren)) {
493 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
495 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
496 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
497 ScopeName, ScopeLoc, TheParsedType, Form);
499 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
500 ArgExprs.data(), ArgExprs.size(), Form);
507 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
510 /// Parse the arguments to a parameterized GNU attribute or
511 /// a C++11 attribute in "gnu" namespace.
512 void Parser::ParseGNUAttributeArgs(
513 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
514 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
515 SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
517 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
519 ParsedAttr::Kind AttrKind =
520 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
522 if (AttrKind == ParsedAttr::AT_Availability) {
523 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
526 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
527 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
528 ScopeName, ScopeLoc, Form);
530 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
531 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
532 ScopeName, ScopeLoc, Form);
534 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
535 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
538 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
539 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
540 ScopeName, ScopeLoc, Form);
542 } else if (attributeIsTypeArgAttr(*AttrName)) {
543 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
548 // These may refer to the function arguments, but need to be parsed early to
549 // participate in determining whether it's a redeclaration.
550 std::optional<ParseScope> PrototypeScope;
551 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
552 D && D->isFunctionDeclarator()) {
553 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
554 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
555 Scope::FunctionDeclarationScope |
557 for (unsigned i = 0; i != FTI.NumParams; ++i) {
558 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
559 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
563 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
567 unsigned Parser::ParseClangAttributeArgs(
568 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
569 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
570 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
571 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
573 ParsedAttr::Kind AttrKind =
574 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
578 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
579 ScopeName, ScopeLoc, Form);
580 case ParsedAttr::AT_ExternalSourceSymbol:
581 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
582 ScopeName, ScopeLoc, Form);
584 case ParsedAttr::AT_Availability:
585 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
588 case ParsedAttr::AT_ObjCBridgeRelated:
589 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
590 ScopeName, ScopeLoc, Form);
592 case ParsedAttr::AT_SwiftNewType:
593 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
596 case ParsedAttr::AT_TypeTagForDatatype:
597 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
598 ScopeName, ScopeLoc, Form);
601 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
604 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
605 SourceLocation AttrNameLoc,
606 ParsedAttributes &Attrs) {
607 unsigned ExistingAttrs = Attrs.size();
609 // If the attribute isn't known, we will not attempt to parse any
611 if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
612 getTargetInfo(), getLangOpts())) {
613 // Eat the left paren, then skip to the ending right paren.
615 SkipUntil(tok::r_paren);
619 SourceLocation OpenParenLoc = Tok.getLocation();
621 if (AttrName->getName() == "property") {
622 // The property declspec is more complex in that it can take one or two
623 // assignment expressions as a parameter, but the lhs of the assignment
624 // must be named get or put.
626 BalancedDelimiterTracker T(*this, tok::l_paren);
627 T.expectAndConsume(diag::err_expected_lparen_after,
628 AttrName->getNameStart(), tok::r_paren);
633 AK_Get = 1 // indices into AccessorNames
635 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
636 bool HasInvalidAccessor = false;
638 // Parse the accessor specifications.
640 // Stop if this doesn't look like an accessor spec.
641 if (!Tok.is(tok::identifier)) {
642 // If the user wrote a completely empty list, use a special diagnostic.
643 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
644 AccessorNames[AK_Put] == nullptr &&
645 AccessorNames[AK_Get] == nullptr) {
646 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
650 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
655 SourceLocation KindLoc = Tok.getLocation();
656 StringRef KindStr = Tok.getIdentifierInfo()->getName();
657 if (KindStr == "get") {
659 } else if (KindStr == "put") {
662 // Recover from the common mistake of using 'set' instead of 'put'.
663 } else if (KindStr == "set") {
664 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
665 << FixItHint::CreateReplacement(KindLoc, "put");
668 // Handle the mistake of forgetting the accessor kind by skipping
670 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
671 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
673 HasInvalidAccessor = true;
674 goto next_property_accessor;
676 // Otherwise, complain about the unknown accessor kind.
678 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
679 HasInvalidAccessor = true;
682 // Try to keep parsing unless it doesn't look like an accessor spec.
683 if (!NextToken().is(tok::equal))
687 // Consume the identifier.
691 if (!TryConsumeToken(tok::equal)) {
692 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
697 // Expect the method name.
698 if (!Tok.is(tok::identifier)) {
699 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
703 if (Kind == AK_Invalid) {
704 // Just drop invalid accessors.
705 } else if (AccessorNames[Kind] != nullptr) {
706 // Complain about the repeated accessor, ignore it, and keep parsing.
707 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
709 AccessorNames[Kind] = Tok.getIdentifierInfo();
713 next_property_accessor:
714 // Keep processing accessors until we run out.
715 if (TryConsumeToken(tok::comma))
718 // If we run into the ')', stop without consuming it.
719 if (Tok.is(tok::r_paren))
722 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
726 // Only add the property attribute if it was well-formed.
727 if (!HasInvalidAccessor)
728 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
729 AccessorNames[AK_Get], AccessorNames[AK_Put],
730 ParsedAttr::Form::Declspec());
732 return !HasInvalidAccessor;
736 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
737 SourceLocation(), ParsedAttr::Form::Declspec());
739 // If this attribute's args were parsed, and it was expected to have
740 // arguments but none were provided, emit a diagnostic.
741 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
742 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
748 /// [MS] decl-specifier:
749 /// __declspec ( extended-decl-modifier-seq )
751 /// [MS] extended-decl-modifier-seq:
752 /// extended-decl-modifier[opt]
753 /// extended-decl-modifier extended-decl-modifier-seq
754 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
755 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
756 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
758 SourceLocation StartLoc = Tok.getLocation();
759 SourceLocation EndLoc = StartLoc;
761 while (Tok.is(tok::kw___declspec)) {
763 BalancedDelimiterTracker T(*this, tok::l_paren);
764 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
768 // An empty declspec is perfectly legal and should not warn. Additionally,
769 // you can specify multiple attributes per declspec.
770 while (Tok.isNot(tok::r_paren)) {
771 // Attribute not present.
772 if (TryConsumeToken(tok::comma))
775 if (Tok.is(tok::code_completion)) {
777 Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Declspec);
781 // We expect either a well-known identifier or a generic string. Anything
782 // else is a malformed declspec.
783 bool IsString = Tok.getKind() == tok::string_literal;
784 if (!IsString && Tok.getKind() != tok::identifier &&
785 Tok.getKind() != tok::kw_restrict) {
786 Diag(Tok, diag::err_ms_declspec_type);
791 IdentifierInfo *AttrName;
792 SourceLocation AttrNameLoc;
794 SmallString<8> StrBuffer;
795 bool Invalid = false;
796 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
801 AttrName = PP.getIdentifierInfo(Str);
802 AttrNameLoc = ConsumeStringToken();
804 AttrName = Tok.getIdentifierInfo();
805 AttrNameLoc = ConsumeToken();
808 bool AttrHandled = false;
810 // Parse attribute arguments.
811 if (Tok.is(tok::l_paren))
812 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
813 else if (AttrName->getName() == "property")
814 // The property attribute must have an argument list.
815 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
816 << AttrName->getName();
819 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
820 ParsedAttr::Form::Declspec());
823 EndLoc = T.getCloseLocation();
826 Attrs.Range = SourceRange(StartLoc, EndLoc);
829 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
830 // Treat these like attributes
832 auto Kind = Tok.getKind();
834 case tok::kw___fastcall:
835 case tok::kw___stdcall:
836 case tok::kw___thiscall:
837 case tok::kw___regcall:
838 case tok::kw___cdecl:
839 case tok::kw___vectorcall:
840 case tok::kw___ptr64:
842 case tok::kw___ptr32:
844 case tok::kw___uptr: {
845 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
846 SourceLocation AttrNameLoc = ConsumeToken();
847 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
857 void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
858 assert(Tok.is(tok::kw___funcref));
859 SourceLocation StartLoc = Tok.getLocation();
860 if (!getTargetInfo().getTriple().isWasm()) {
862 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
866 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
867 SourceLocation AttrNameLoc = ConsumeToken();
868 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
869 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
873 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
874 SourceLocation StartLoc = Tok.getLocation();
875 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
877 if (EndLoc.isValid()) {
878 SourceRange Range(StartLoc, EndLoc);
879 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
883 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
884 SourceLocation EndLoc;
887 switch (Tok.getKind()) {
889 case tok::kw_volatile:
890 case tok::kw___fastcall:
891 case tok::kw___stdcall:
892 case tok::kw___thiscall:
893 case tok::kw___cdecl:
894 case tok::kw___vectorcall:
895 case tok::kw___ptr32:
896 case tok::kw___ptr64:
898 case tok::kw___unaligned:
901 EndLoc = ConsumeToken();
909 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
910 // Treat these like attributes
911 while (Tok.is(tok::kw___pascal)) {
912 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
913 SourceLocation AttrNameLoc = ConsumeToken();
914 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
919 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
920 // Treat these like attributes
921 while (Tok.is(tok::kw___kernel)) {
922 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
923 SourceLocation AttrNameLoc = ConsumeToken();
924 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
929 void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
930 while (Tok.is(tok::kw___noinline__)) {
931 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
932 SourceLocation AttrNameLoc = ConsumeToken();
933 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
934 tok::kw___noinline__);
938 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
939 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
940 SourceLocation AttrNameLoc = Tok.getLocation();
941 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
945 bool Parser::isHLSLQualifier(const Token &Tok) const {
946 return Tok.is(tok::kw_groupshared);
949 void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
950 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
951 auto Kind = Tok.getKind();
952 SourceLocation AttrNameLoc = ConsumeToken();
953 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
956 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
957 // Treat these like attributes, even though they're type specifiers.
959 auto Kind = Tok.getKind();
961 case tok::kw__Nonnull:
962 case tok::kw__Nullable:
963 case tok::kw__Nullable_result:
964 case tok::kw__Null_unspecified: {
965 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
966 SourceLocation AttrNameLoc = ConsumeToken();
967 if (!getLangOpts().ObjC)
968 Diag(AttrNameLoc, diag::ext_nullability)
970 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
980 static bool VersionNumberSeparator(const char Separator) {
981 return (Separator == '.' || Separator == '_');
984 /// Parse a version number.
988 /// simple-integer '.' simple-integer
989 /// simple-integer '_' simple-integer
990 /// simple-integer '.' simple-integer '.' simple-integer
991 /// simple-integer '_' simple-integer '_' simple-integer
992 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
993 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
995 if (!Tok.is(tok::numeric_constant)) {
996 Diag(Tok, diag::err_expected_version);
997 SkipUntil(tok::comma, tok::r_paren,
998 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
999 return VersionTuple();
1002 // Parse the major (and possibly minor and subminor) versions, which
1003 // are stored in the numeric constant. We utilize a quirk of the
1004 // lexer, which is that it handles something like 1.2.3 as a single
1005 // numeric constant, rather than two separate tokens.
1006 SmallString<512> Buffer;
1007 Buffer.resize(Tok.getLength()+1);
1008 const char *ThisTokBegin = &Buffer[0];
1010 // Get the spelling of the token, which eliminates trigraphs, etc.
1011 bool Invalid = false;
1012 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1014 return VersionTuple();
1016 // Parse the major version.
1017 unsigned AfterMajor = 0;
1019 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1020 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1024 if (AfterMajor == 0) {
1025 Diag(Tok, diag::err_expected_version);
1026 SkipUntil(tok::comma, tok::r_paren,
1027 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1028 return VersionTuple();
1031 if (AfterMajor == ActualLength) {
1034 // We only had a single version component.
1036 Diag(Tok, diag::err_zero_version);
1037 return VersionTuple();
1040 return VersionTuple(Major);
1043 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1044 if (!VersionNumberSeparator(AfterMajorSeparator)
1045 || (AfterMajor + 1 == ActualLength)) {
1046 Diag(Tok, diag::err_expected_version);
1047 SkipUntil(tok::comma, tok::r_paren,
1048 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1049 return VersionTuple();
1052 // Parse the minor version.
1053 unsigned AfterMinor = AfterMajor + 1;
1055 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1056 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1060 if (AfterMinor == ActualLength) {
1063 // We had major.minor.
1064 if (Major == 0 && Minor == 0) {
1065 Diag(Tok, diag::err_zero_version);
1066 return VersionTuple();
1069 return VersionTuple(Major, Minor);
1072 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1073 // If what follows is not a '.' or '_', we have a problem.
1074 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1075 Diag(Tok, diag::err_expected_version);
1076 SkipUntil(tok::comma, tok::r_paren,
1077 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1078 return VersionTuple();
1081 // Warn if separators, be it '.' or '_', do not match.
1082 if (AfterMajorSeparator != AfterMinorSeparator)
1083 Diag(Tok, diag::warn_expected_consistent_version_separator);
1085 // Parse the subminor version.
1086 unsigned AfterSubminor = AfterMinor + 1;
1087 unsigned Subminor = 0;
1088 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1089 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1093 if (AfterSubminor != ActualLength) {
1094 Diag(Tok, diag::err_expected_version);
1095 SkipUntil(tok::comma, tok::r_paren,
1096 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1097 return VersionTuple();
1100 return VersionTuple(Major, Minor, Subminor);
1103 /// Parse the contents of the "availability" attribute.
1105 /// availability-attribute:
1106 /// 'availability' '(' platform ',' opt-strict version-arg-list,
1107 /// opt-replacement, opt-message')'
1115 /// version-arg-list:
1117 /// version-arg ',' version-arg-list
1120 /// 'introduced' '=' version
1121 /// 'deprecated' '=' version
1122 /// 'obsoleted' = version
1124 /// opt-replacement:
1125 /// 'replacement' '=' <string>
1127 /// 'message' '=' <string>
1128 void Parser::ParseAvailabilityAttribute(
1129 IdentifierInfo &Availability, SourceLocation AvailabilityLoc,
1130 ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName,
1131 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1132 enum { Introduced, Deprecated, Obsoleted, Unknown };
1133 AvailabilityChange Changes[Unknown];
1134 ExprResult MessageExpr, ReplacementExpr;
1137 BalancedDelimiterTracker T(*this, tok::l_paren);
1138 if (T.consumeOpen()) {
1139 Diag(Tok, diag::err_expected) << tok::l_paren;
1143 // Parse the platform name.
1144 if (Tok.isNot(tok::identifier)) {
1145 Diag(Tok, diag::err_availability_expected_platform);
1146 SkipUntil(tok::r_paren, StopAtSemi);
1149 IdentifierLoc *Platform = ParseIdentifierLoc();
1150 if (const IdentifierInfo *const Ident = Platform->Ident) {
1151 // Canonicalize platform name from "macosx" to "macos".
1152 if (Ident->getName() == "macosx")
1153 Platform->Ident = PP.getIdentifierInfo("macos");
1154 // Canonicalize platform name from "macosx_app_extension" to
1155 // "macos_app_extension".
1156 else if (Ident->getName() == "macosx_app_extension")
1157 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1159 Platform->Ident = PP.getIdentifierInfo(
1160 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1163 // Parse the ',' following the platform name.
1164 if (ExpectAndConsume(tok::comma)) {
1165 SkipUntil(tok::r_paren, StopAtSemi);
1169 // If we haven't grabbed the pointers for the identifiers
1170 // "introduced", "deprecated", and "obsoleted", do so now.
1171 if (!Ident_introduced) {
1172 Ident_introduced = PP.getIdentifierInfo("introduced");
1173 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1174 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1175 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1176 Ident_message = PP.getIdentifierInfo("message");
1177 Ident_strict = PP.getIdentifierInfo("strict");
1178 Ident_replacement = PP.getIdentifierInfo("replacement");
1181 // Parse the optional "strict", the optional "replacement" and the set of
1182 // introductions/deprecations/removals.
1183 SourceLocation UnavailableLoc, StrictLoc;
1185 if (Tok.isNot(tok::identifier)) {
1186 Diag(Tok, diag::err_availability_expected_change);
1187 SkipUntil(tok::r_paren, StopAtSemi);
1190 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1191 SourceLocation KeywordLoc = ConsumeToken();
1193 if (Keyword == Ident_strict) {
1194 if (StrictLoc.isValid()) {
1195 Diag(KeywordLoc, diag::err_availability_redundant)
1196 << Keyword << SourceRange(StrictLoc);
1198 StrictLoc = KeywordLoc;
1202 if (Keyword == Ident_unavailable) {
1203 if (UnavailableLoc.isValid()) {
1204 Diag(KeywordLoc, diag::err_availability_redundant)
1205 << Keyword << SourceRange(UnavailableLoc);
1207 UnavailableLoc = KeywordLoc;
1211 if (Keyword == Ident_deprecated && Platform->Ident &&
1212 Platform->Ident->isStr("swift")) {
1213 // For swift, we deprecate for all versions.
1214 if (Changes[Deprecated].KeywordLoc.isValid()) {
1215 Diag(KeywordLoc, diag::err_availability_redundant)
1217 << SourceRange(Changes[Deprecated].KeywordLoc);
1220 Changes[Deprecated].KeywordLoc = KeywordLoc;
1221 // Use a fake version here.
1222 Changes[Deprecated].Version = VersionTuple(1);
1226 if (Tok.isNot(tok::equal)) {
1227 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1228 SkipUntil(tok::r_paren, StopAtSemi);
1232 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1233 if (Tok.isNot(tok::string_literal)) {
1234 Diag(Tok, diag::err_expected_string_literal)
1235 << /*Source='availability attribute'*/2;
1236 SkipUntil(tok::r_paren, StopAtSemi);
1239 if (Keyword == Ident_message)
1240 MessageExpr = ParseStringLiteralExpression();
1242 ReplacementExpr = ParseStringLiteralExpression();
1243 // Also reject wide string literals.
1244 if (StringLiteral *MessageStringLiteral =
1245 cast_or_null<StringLiteral>(MessageExpr.get())) {
1246 if (!MessageStringLiteral->isOrdinary()) {
1247 Diag(MessageStringLiteral->getSourceRange().getBegin(),
1248 diag::err_expected_string_literal)
1249 << /*Source='availability attribute'*/ 2;
1250 SkipUntil(tok::r_paren, StopAtSemi);
1254 if (Keyword == Ident_message)
1260 // Special handling of 'NA' only when applied to introduced or
1262 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1263 Tok.is(tok::identifier)) {
1264 IdentifierInfo *NA = Tok.getIdentifierInfo();
1265 if (NA->getName() == "NA") {
1267 if (Keyword == Ident_introduced)
1268 UnavailableLoc = KeywordLoc;
1273 SourceRange VersionRange;
1274 VersionTuple Version = ParseVersionTuple(VersionRange);
1276 if (Version.empty()) {
1277 SkipUntil(tok::r_paren, StopAtSemi);
1282 if (Keyword == Ident_introduced)
1284 else if (Keyword == Ident_deprecated)
1286 else if (Keyword == Ident_obsoleted)
1291 if (Index < Unknown) {
1292 if (!Changes[Index].KeywordLoc.isInvalid()) {
1293 Diag(KeywordLoc, diag::err_availability_redundant)
1295 << SourceRange(Changes[Index].KeywordLoc,
1296 Changes[Index].VersionRange.getEnd());
1299 Changes[Index].KeywordLoc = KeywordLoc;
1300 Changes[Index].Version = Version;
1301 Changes[Index].VersionRange = VersionRange;
1303 Diag(KeywordLoc, diag::err_availability_unknown_change)
1304 << Keyword << VersionRange;
1307 } while (TryConsumeToken(tok::comma));
1310 if (T.consumeClose())
1314 *endLoc = T.getCloseLocation();
1316 // The 'unavailable' availability cannot be combined with any other
1317 // availability changes. Make sure that hasn't happened.
1318 if (UnavailableLoc.isValid()) {
1319 bool Complained = false;
1320 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1321 if (Changes[Index].KeywordLoc.isValid()) {
1323 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1324 << SourceRange(Changes[Index].KeywordLoc,
1325 Changes[Index].VersionRange.getEnd());
1329 // Clear out the availability.
1330 Changes[Index] = AvailabilityChange();
1335 // Record this attribute
1336 attrs.addNew(&Availability,
1337 SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName,
1338 ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated],
1339 Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Form,
1340 StrictLoc, ReplacementExpr.get());
1343 /// Parse the contents of the "external_source_symbol" attribute.
1345 /// external-source-symbol-attribute:
1346 /// 'external_source_symbol' '(' keyword-arg-list ')'
1348 /// keyword-arg-list:
1350 /// keyword-arg ',' keyword-arg-list
1353 /// 'language' '=' <string>
1354 /// 'defined_in' '=' <string>
1355 /// 'USR' '=' <string>
1356 /// 'generated_declaration'
1357 void Parser::ParseExternalSourceSymbolAttribute(
1358 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1359 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1360 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1362 BalancedDelimiterTracker T(*this, tok::l_paren);
1363 if (T.expectAndConsume())
1366 // Initialize the pointers for the keyword identifiers when required.
1367 if (!Ident_language) {
1368 Ident_language = PP.getIdentifierInfo("language");
1369 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1370 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1371 Ident_USR = PP.getIdentifierInfo("USR");
1374 ExprResult Language;
1375 bool HasLanguage = false;
1376 ExprResult DefinedInExpr;
1377 bool HasDefinedIn = false;
1378 IdentifierLoc *GeneratedDeclaration = nullptr;
1380 bool HasUSR = false;
1382 // Parse the language/defined_in/generated_declaration keywords
1384 if (Tok.isNot(tok::identifier)) {
1385 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1386 SkipUntil(tok::r_paren, StopAtSemi);
1390 SourceLocation KeywordLoc = Tok.getLocation();
1391 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1392 if (Keyword == Ident_generated_declaration) {
1393 if (GeneratedDeclaration) {
1394 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1395 SkipUntil(tok::r_paren, StopAtSemi);
1398 GeneratedDeclaration = ParseIdentifierLoc();
1402 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1403 Keyword != Ident_USR) {
1404 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1405 SkipUntil(tok::r_paren, StopAtSemi);
1410 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1411 Keyword->getName())) {
1412 SkipUntil(tok::r_paren, StopAtSemi);
1416 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1418 if (Keyword == Ident_language)
1420 else if (Keyword == Ident_USR)
1423 HasDefinedIn = true;
1425 if (Tok.isNot(tok::string_literal)) {
1426 Diag(Tok, diag::err_expected_string_literal)
1427 << /*Source='external_source_symbol attribute'*/ 3
1428 << /*language | source container | USR*/ (
1429 Keyword == Ident_language
1431 : (Keyword == Ident_defined_in ? 1 : 2));
1432 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1435 if (Keyword == Ident_language) {
1437 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1439 ParseStringLiteralExpression();
1442 Language = ParseStringLiteralExpression();
1443 } else if (Keyword == Ident_USR) {
1445 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1447 ParseStringLiteralExpression();
1450 USR = ParseStringLiteralExpression();
1452 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1454 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1456 ParseStringLiteralExpression();
1459 DefinedInExpr = ParseStringLiteralExpression();
1461 } while (TryConsumeToken(tok::comma));
1464 if (T.consumeClose())
1467 *EndLoc = T.getCloseLocation();
1469 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1471 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1472 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1475 /// Parse the contents of the "objc_bridge_related" attribute.
1476 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1480 /// opt-class_method:
1481 /// Identifier: | <empty>
1483 /// opt-instance_method:
1484 /// Identifier | <empty>
1486 void Parser::ParseObjCBridgeRelatedAttribute(
1487 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1488 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1489 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1491 BalancedDelimiterTracker T(*this, tok::l_paren);
1492 if (T.consumeOpen()) {
1493 Diag(Tok, diag::err_expected) << tok::l_paren;
1497 // Parse the related class name.
1498 if (Tok.isNot(tok::identifier)) {
1499 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1500 SkipUntil(tok::r_paren, StopAtSemi);
1503 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1504 if (ExpectAndConsume(tok::comma)) {
1505 SkipUntil(tok::r_paren, StopAtSemi);
1509 // Parse class method name. It's non-optional in the sense that a trailing
1510 // comma is required, but it can be the empty string, and then we record a
1512 IdentifierLoc *ClassMethod = nullptr;
1513 if (Tok.is(tok::identifier)) {
1514 ClassMethod = ParseIdentifierLoc();
1515 if (!TryConsumeToken(tok::colon)) {
1516 Diag(Tok, diag::err_objcbridge_related_selector_name);
1517 SkipUntil(tok::r_paren, StopAtSemi);
1521 if (!TryConsumeToken(tok::comma)) {
1522 if (Tok.is(tok::colon))
1523 Diag(Tok, diag::err_objcbridge_related_selector_name);
1525 Diag(Tok, diag::err_expected) << tok::comma;
1526 SkipUntil(tok::r_paren, StopAtSemi);
1530 // Parse instance method name. Also non-optional but empty string is
1532 IdentifierLoc *InstanceMethod = nullptr;
1533 if (Tok.is(tok::identifier))
1534 InstanceMethod = ParseIdentifierLoc();
1535 else if (Tok.isNot(tok::r_paren)) {
1536 Diag(Tok, diag::err_expected) << tok::r_paren;
1537 SkipUntil(tok::r_paren, StopAtSemi);
1542 if (T.consumeClose())
1546 *EndLoc = T.getCloseLocation();
1548 // Record this attribute
1549 Attrs.addNew(&ObjCBridgeRelated,
1550 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1551 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1555 void Parser::ParseSwiftNewTypeAttribute(
1556 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1557 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1558 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1559 BalancedDelimiterTracker T(*this, tok::l_paren);
1562 if (T.consumeOpen()) {
1563 Diag(Tok, diag::err_expected) << tok::l_paren;
1567 if (Tok.is(tok::r_paren)) {
1568 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1572 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1573 Diag(Tok, diag::warn_attribute_type_not_supported)
1574 << &AttrName << Tok.getIdentifierInfo();
1575 if (!isTokenSpecial())
1581 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1582 Tok.getIdentifierInfo());
1586 if (T.consumeClose())
1589 *EndLoc = T.getCloseLocation();
1591 ArgsUnion Args[] = {SwiftType};
1592 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1593 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1596 void Parser::ParseTypeTagForDatatypeAttribute(
1597 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1598 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1599 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1600 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1602 BalancedDelimiterTracker T(*this, tok::l_paren);
1605 if (Tok.isNot(tok::identifier)) {
1606 Diag(Tok, diag::err_expected) << tok::identifier;
1610 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1612 if (ExpectAndConsume(tok::comma)) {
1617 SourceRange MatchingCTypeRange;
1618 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1619 if (MatchingCType.isInvalid()) {
1624 bool LayoutCompatible = false;
1625 bool MustBeNull = false;
1626 while (TryConsumeToken(tok::comma)) {
1627 if (Tok.isNot(tok::identifier)) {
1628 Diag(Tok, diag::err_expected) << tok::identifier;
1632 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1633 if (Flag->isStr("layout_compatible"))
1634 LayoutCompatible = true;
1635 else if (Flag->isStr("must_be_null"))
1638 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1642 ConsumeToken(); // consume flag
1645 if (!T.consumeClose()) {
1646 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1647 ArgumentKind, MatchingCType.get(),
1648 LayoutCompatible, MustBeNull, Form);
1652 *EndLoc = T.getCloseLocation();
1655 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1656 /// of a C++11 attribute-specifier in a location where an attribute is not
1657 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1660 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1661 /// this doesn't appear to actually be an attribute-specifier, and the caller
1662 /// should try to parse it.
1663 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1664 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1666 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1667 case CAK_NotAttributeSpecifier:
1668 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1671 case CAK_InvalidAttributeSpecifier:
1672 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1675 case CAK_AttributeSpecifier:
1676 // Parse and discard the attributes.
1677 SourceLocation BeginLoc = ConsumeBracket();
1679 SkipUntil(tok::r_square);
1680 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1681 SourceLocation EndLoc = ConsumeBracket();
1682 Diag(BeginLoc, diag::err_attributes_not_allowed)
1683 << SourceRange(BeginLoc, EndLoc);
1686 llvm_unreachable("All cases handled above.");
1689 /// We have found the opening square brackets of a C++11
1690 /// attribute-specifier in a location where an attribute is not permitted, but
1691 /// we know where the attributes ought to be written. Parse them anyway, and
1692 /// provide a fixit moving them to the right place.
1693 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1694 SourceLocation CorrectLocation) {
1695 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1696 Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute());
1698 // Consume the attributes.
1700 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
1701 SourceLocation Loc = Tok.getLocation();
1702 ParseCXX11Attributes(Attrs);
1703 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1704 // FIXME: use err_attributes_misplaced
1705 (Keyword ? Diag(Loc, diag::err_keyword_not_allowed) << Keyword
1706 : Diag(Loc, diag::err_attributes_not_allowed))
1707 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1708 << FixItHint::CreateRemoval(AttrRange);
1711 void Parser::DiagnoseProhibitedAttributes(
1712 const ParsedAttributesView &Attrs, const SourceLocation CorrectLocation) {
1713 auto *FirstAttr = Attrs.empty() ? nullptr : &Attrs.front();
1714 if (CorrectLocation.isValid()) {
1715 CharSourceRange AttrRange(Attrs.Range, true);
1716 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1717 ? Diag(CorrectLocation, diag::err_keyword_misplaced) << FirstAttr
1718 : Diag(CorrectLocation, diag::err_attributes_misplaced))
1719 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1720 << FixItHint::CreateRemoval(AttrRange);
1722 const SourceRange &Range = Attrs.Range;
1723 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1724 ? Diag(Range.getBegin(), diag::err_keyword_not_allowed) << FirstAttr
1725 : Diag(Range.getBegin(), diag::err_attributes_not_allowed))
1730 void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs,
1731 unsigned AttrDiagID,
1732 unsigned KeywordDiagID,
1733 bool DiagnoseEmptyAttrs,
1734 bool WarnOnUnknownAttrs) {
1736 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1737 // An attribute list has been parsed, but it was empty.
1738 // This is the case for [[]].
1739 const auto &LangOpts = getLangOpts();
1740 auto &SM = PP.getSourceManager();
1742 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1744 if (FirstLSquare.is(tok::l_square)) {
1745 std::optional<Token> SecondLSquare =
1746 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1748 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1749 // The attribute range starts with [[, but is empty. So this must
1750 // be [[]], which we are supposed to diagnose because
1751 // DiagnoseEmptyAttrs is true.
1752 Diag(Attrs.Range.getBegin(), AttrDiagID) << Attrs.Range;
1758 for (const ParsedAttr &AL : Attrs) {
1759 if (AL.isRegularKeywordAttribute()) {
1760 Diag(AL.getLoc(), KeywordDiagID) << AL;
1764 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1766 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1767 if (WarnOnUnknownAttrs)
1768 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1769 << AL << AL.getRange();
1771 Diag(AL.getLoc(), AttrDiagID) << AL;
1777 void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1778 for (const ParsedAttr &PA : Attrs) {
1779 if (PA.isCXX11Attribute() || PA.isC2xAttribute() ||
1780 PA.isRegularKeywordAttribute())
1781 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement)
1782 << PA << PA.isRegularKeywordAttribute() << PA.getRange();
1786 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1787 // applies to var, not the type Foo.
1788 // As an exception to the rule, __declspec(align(...)) before the
1789 // class-key affects the type instead of the variable.
1790 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1792 // This function moves attributes that should apply to the type off DS to Attrs.
1793 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1795 Sema::TagUseKind TUK) {
1796 if (TUK == Sema::TUK_Reference)
1799 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1801 for (ParsedAttr &AL : DS.getAttributes()) {
1802 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1803 AL.isDeclspecAttribute()) ||
1804 AL.isMicrosoftAttribute())
1805 ToBeMoved.push_back(&AL);
1808 for (ParsedAttr *AL : ToBeMoved) {
1809 DS.getAttributes().remove(AL);
1814 /// ParseDeclaration - Parse a full 'declaration', which consists of
1815 /// declaration-specifiers, some number of declarators, and a semicolon.
1816 /// 'Context' should be a DeclaratorContext value. This returns the
1817 /// location of the semicolon in DeclEnd.
1819 /// declaration: [C99 6.7]
1820 /// block-declaration ->
1821 /// simple-declaration
1823 /// [C++] template-declaration
1824 /// [C++] namespace-definition
1825 /// [C++] using-directive
1826 /// [C++] using-declaration
1827 /// [C++11/C11] static_assert-declaration
1828 /// others... [FIXME]
1830 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1831 SourceLocation &DeclEnd,
1832 ParsedAttributes &DeclAttrs,
1833 ParsedAttributes &DeclSpecAttrs,
1834 SourceLocation *DeclSpecStart) {
1835 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1836 // Must temporarily exit the objective-c container scope for
1837 // parsing c none objective-c decls.
1838 ObjCDeclContextSwitch ObjCDC(*this);
1840 Decl *SingleDecl = nullptr;
1841 switch (Tok.getKind()) {
1842 case tok::kw_template:
1843 case tok::kw_export:
1844 ProhibitAttributes(DeclAttrs);
1845 ProhibitAttributes(DeclSpecAttrs);
1847 ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1849 case tok::kw_inline:
1850 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1851 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1852 ProhibitAttributes(DeclAttrs);
1853 ProhibitAttributes(DeclSpecAttrs);
1854 SourceLocation InlineLoc = ConsumeToken();
1855 return ParseNamespace(Context, DeclEnd, InlineLoc);
1857 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1858 true, nullptr, DeclSpecStart);
1860 case tok::kw_cbuffer:
1861 case tok::kw_tbuffer:
1862 SingleDecl = ParseHLSLBuffer(DeclEnd);
1864 case tok::kw_namespace:
1865 ProhibitAttributes(DeclAttrs);
1866 ProhibitAttributes(DeclSpecAttrs);
1867 return ParseNamespace(Context, DeclEnd);
1868 case tok::kw_using: {
1869 ParsedAttributes Attrs(AttrFactory);
1870 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
1871 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1874 case tok::kw_static_assert:
1875 case tok::kw__Static_assert:
1876 ProhibitAttributes(DeclAttrs);
1877 ProhibitAttributes(DeclSpecAttrs);
1878 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1881 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1882 true, nullptr, DeclSpecStart);
1885 // This routine returns a DeclGroup, if the thing we parsed only contains a
1886 // single decl, convert it now.
1887 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1890 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1891 /// declaration-specifiers init-declarator-list[opt] ';'
1892 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1893 /// init-declarator-list ';'
1894 ///[C90/C++]init-declarator-list ';' [TODO]
1895 /// [OMP] threadprivate-directive
1896 /// [OMP] allocate-directive [TODO]
1898 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1899 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1901 /// If RequireSemi is false, this does not check for a ';' at the end of the
1902 /// declaration. If it is true, it checks for and eats it.
1904 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1905 /// of a simple-declaration. If we find that we are, we also parse the
1906 /// for-range-initializer, and place it here.
1908 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1909 /// the Declaration. The SourceLocation for this Decl is set to
1910 /// DeclSpecStart if DeclSpecStart is non-null.
1911 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1912 DeclaratorContext Context, SourceLocation &DeclEnd,
1913 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1914 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
1915 // Need to retain these for diagnostics before we add them to the DeclSepc.
1916 ParsedAttributesView OriginalDeclSpecAttrs;
1917 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
1918 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1920 // Parse the common declaration-specifiers piece.
1921 ParsingDeclSpec DS(*this);
1922 DS.takeAttributesFrom(DeclSpecAttrs);
1924 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1925 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1927 // If we had a free-standing type definition with a missing semicolon, we
1928 // may get this far before the problem becomes obvious.
1929 if (DS.hasTagDefinition() &&
1930 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1933 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1934 // declaration-specifiers init-declarator-list[opt] ';'
1935 if (Tok.is(tok::semi)) {
1936 ProhibitAttributes(DeclAttrs);
1937 DeclEnd = Tok.getLocation();
1938 if (RequireSemi) ConsumeToken();
1939 RecordDecl *AnonRecord = nullptr;
1940 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1941 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1942 DS.complete(TheDecl);
1944 Decl* decls[] = {AnonRecord, TheDecl};
1945 return Actions.BuildDeclaratorGroup(decls);
1947 return Actions.ConvertDeclToDeclGroup(TheDecl);
1951 DS.SetRangeStart(*DeclSpecStart);
1953 return ParseDeclGroup(DS, Context, DeclAttrs, &DeclEnd, FRI);
1956 /// Returns true if this might be the start of a declarator, or a common typo
1957 /// for a declarator.
1958 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1959 switch (Tok.getKind()) {
1960 case tok::annot_cxxscope:
1961 case tok::annot_template_id:
1963 case tok::code_completion:
1964 case tok::coloncolon:
1966 case tok::kw___attribute:
1967 case tok::kw_operator:
1974 return getLangOpts().CPlusPlus;
1976 case tok::l_square: // Might be an attribute on an unnamed bit-field.
1977 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1978 NextToken().is(tok::l_square);
1980 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1981 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
1983 case tok::identifier:
1984 switch (NextToken().getKind()) {
1985 case tok::code_completion:
1986 case tok::coloncolon:
1989 case tok::equalequal: // Might be a typo for '='.
1990 case tok::kw_alignas:
1992 case tok::kw___attribute:
2004 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
2005 // and in block scope it's probably a label. Inside a class definition,
2006 // this is a bit-field.
2007 return Context == DeclaratorContext::Member ||
2008 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
2010 case tok::identifier: // Possible virt-specifier.
2011 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
2014 return Tok.isRegularKeywordAttribute();
2018 return Tok.isRegularKeywordAttribute();
2022 /// Skip until we reach something which seems like a sensible place to pick
2023 /// up parsing after a malformed declaration. This will sometimes stop sooner
2024 /// than SkipUntil(tok::r_brace) would, but will never stop later.
2025 void Parser::SkipMalformedDecl() {
2027 switch (Tok.getKind()) {
2029 // Skip until matching }, then stop. We've probably skipped over
2030 // a malformed class or function definition or similar.
2032 SkipUntil(tok::r_brace);
2033 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2034 // This declaration isn't over yet. Keep skipping.
2037 TryConsumeToken(tok::semi);
2042 SkipUntil(tok::r_square);
2047 SkipUntil(tok::r_paren);
2057 case tok::kw_inline:
2058 // 'inline namespace' at the start of a line is almost certainly
2059 // a good place to pick back up parsing, except in an Objective-C
2060 // @interface context.
2061 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2062 (!ParsingInObjCContainer || CurParsedObjCImpl))
2066 case tok::kw_namespace:
2067 // 'namespace' at the start of a line is almost certainly a good
2068 // place to pick back up parsing, except in an Objective-C
2069 // @interface context.
2070 if (Tok.isAtStartOfLine() &&
2071 (!ParsingInObjCContainer || CurParsedObjCImpl))
2076 // @end is very much like } in Objective-C contexts.
2077 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2078 ParsingInObjCContainer)
2084 // - and + probably start new method declarations in Objective-C contexts.
2085 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2090 case tok::annot_module_begin:
2091 case tok::annot_module_end:
2092 case tok::annot_module_include:
2093 case tok::annot_repl_input_end:
2104 /// ParseDeclGroup - Having concluded that this is either a function
2105 /// definition or a group of object declarations, actually parse the
2107 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2108 DeclaratorContext Context,
2109 ParsedAttributes &Attrs,
2110 SourceLocation *DeclEnd,
2111 ForRangeInit *FRI) {
2112 // Parse the first declarator.
2113 // Consume all of the attributes from `Attrs` by moving them to our own local
2114 // list. This ensures that we will not attempt to interpret them as statement
2115 // attributes higher up the callchain.
2116 ParsedAttributes LocalAttrs(AttrFactory);
2117 LocalAttrs.takeAllFrom(Attrs);
2118 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2121 // Bail out if the first declarator didn't seem well-formed.
2122 if (!D.hasName() && !D.mayOmitIdentifier()) {
2123 SkipMalformedDecl();
2127 if (getLangOpts().HLSL)
2128 MaybeParseHLSLSemantics(D);
2130 if (Tok.is(tok::kw_requires))
2131 ParseTrailingRequiresClause(D);
2133 // Save late-parsed attributes for now; they need to be parsed in the
2134 // appropriate function scope after the function Decl has been constructed.
2135 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2136 LateParsedAttrList LateParsedAttrs(true);
2137 if (D.isFunctionDeclarator()) {
2138 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2140 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2141 // attribute. If we find the keyword here, tell the user to put it
2142 // at the start instead.
2143 if (Tok.is(tok::kw__Noreturn)) {
2144 SourceLocation Loc = ConsumeToken();
2145 const char *PrevSpec;
2148 // We can offer a fixit if it's valid to mark this function as _Noreturn
2149 // and we don't have any other declarators in this declaration.
2150 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2151 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2152 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2154 Diag(Loc, diag::err_c11_noreturn_misplaced)
2155 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2156 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2160 // Check to see if we have a function *definition* which must have a body.
2161 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2163 Actions.CodeCompleteAfterFunctionEquals(D);
2166 // We're at the point where the parsing of function declarator is finished.
2168 // A common error is that users accidently add a virtual specifier
2169 // (e.g. override) in an out-line method definition.
2170 // We attempt to recover by stripping all these specifiers coming after
2172 while (auto Specifier = isCXX11VirtSpecifier()) {
2173 Diag(Tok, diag::err_virt_specifier_outside_class)
2174 << VirtSpecifiers::getSpecifierName(Specifier)
2175 << FixItHint::CreateRemoval(Tok.getLocation());
2178 // Look at the next token to make sure that this isn't a function
2179 // declaration. We have to check this because __attribute__ might be the
2180 // start of a function definition in GCC-extended K&R C.
2181 if (!isDeclarationAfterDeclarator()) {
2183 // Function definitions are only allowed at file scope and in C++ classes.
2184 // The C++ inline method definition case is handled elsewhere, so we only
2185 // need to handle the file scope definition case.
2186 if (Context == DeclaratorContext::File) {
2187 if (isStartOfFunctionDefinition(D)) {
2188 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2189 Diag(Tok, diag::err_function_declared_typedef);
2191 // Recover by treating the 'typedef' as spurious.
2192 DS.ClearStorageClassSpecs();
2195 Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2197 return Actions.ConvertDeclToDeclGroup(TheDecl);
2200 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2201 Tok.is(tok::kw_namespace)) {
2202 // If there is an invalid declaration specifier or a namespace
2203 // definition right after the function prototype, then we must be in a
2204 // missing semicolon case where this isn't actually a body. Just fall
2205 // through into the code that handles it as a prototype, and let the
2206 // top-level code handle the erroneous declspec where it would
2207 // otherwise expect a comma or semicolon. Note that
2208 // isDeclarationSpecifier already covers 'inline namespace', since
2209 // 'inline' can be a declaration specifier.
2211 Diag(Tok, diag::err_expected_fn_body);
2212 SkipUntil(tok::semi);
2216 if (Tok.is(tok::l_brace)) {
2217 Diag(Tok, diag::err_function_definition_not_allowed);
2218 SkipMalformedDecl();
2225 if (ParseAsmAttributesAfterDeclarator(D))
2228 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2229 // must parse and analyze the for-range-initializer before the declaration is
2232 // Handle the Objective-C for-in loop variable similarly, although we
2233 // don't need to parse the container in advance.
2234 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2235 bool IsForRangeLoop = false;
2236 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2237 IsForRangeLoop = true;
2238 if (getLangOpts().OpenMP)
2239 Actions.startOpenMPCXXRangeFor();
2240 if (Tok.is(tok::l_brace))
2241 FRI->RangeExpr = ParseBraceInitializer();
2243 FRI->RangeExpr = ParseExpression();
2246 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2247 if (IsForRangeLoop) {
2248 Actions.ActOnCXXForRangeDecl(ThisDecl);
2251 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2252 VD->setObjCForDecl(true);
2254 Actions.FinalizeDeclaration(ThisDecl);
2255 D.complete(ThisDecl);
2256 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2259 SmallVector<Decl *, 8> DeclsInGroup;
2260 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2261 D, ParsedTemplateInfo(), FRI);
2262 if (LateParsedAttrs.size() > 0)
2263 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2264 D.complete(FirstDecl);
2266 DeclsInGroup.push_back(FirstDecl);
2268 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2270 // If we don't have a comma, it is either the end of the list (a ';') or an
2272 SourceLocation CommaLoc;
2273 while (TryConsumeToken(tok::comma, CommaLoc)) {
2274 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2275 // This comma was followed by a line-break and something which can't be
2276 // the start of a declarator. The comma was probably a typo for a
2278 Diag(CommaLoc, diag::err_expected_semi_declaration)
2279 << FixItHint::CreateReplacement(CommaLoc, ";");
2284 // Parse the next declarator.
2286 D.setCommaLoc(CommaLoc);
2288 // Accept attributes in an init-declarator. In the first declarator in a
2289 // declaration, these would be part of the declspec. In subsequent
2290 // declarators, they become part of the declarator itself, so that they
2291 // don't apply to declarators after *this* one. Examples:
2292 // short __attribute__((common)) var; -> declspec
2293 // short var __attribute__((common)); -> declarator
2294 // short x, __attribute__((common)) var; -> declarator
2295 MaybeParseGNUAttributes(D);
2297 // MSVC parses but ignores qualifiers after the comma as an extension.
2298 if (getLangOpts().MicrosoftExt)
2299 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2303 if (getLangOpts().HLSL)
2304 MaybeParseHLSLSemantics(D);
2306 if (!D.isInvalidType()) {
2307 // C++2a [dcl.decl]p1
2309 // declarator initializer[opt]
2310 // declarator requires-clause
2311 if (Tok.is(tok::kw_requires))
2312 ParseTrailingRequiresClause(D);
2313 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2314 D.complete(ThisDecl);
2316 DeclsInGroup.push_back(ThisDecl);
2321 *DeclEnd = Tok.getLocation();
2323 if (ExpectSemi && ExpectAndConsumeSemi(
2324 Context == DeclaratorContext::File
2325 ? diag::err_invalid_token_after_toplevel_declarator
2326 : diag::err_expected_semi_declaration)) {
2327 // Okay, there was no semicolon and one was expected. If we see a
2328 // declaration specifier, just assume it was missing and continue parsing.
2329 // Otherwise things are very confused and we skip to recover.
2330 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2331 SkipMalformedDecl();
2334 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2337 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2338 /// declarator. Returns true on an error.
2339 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2340 // If a simple-asm-expr is present, parse it.
2341 if (Tok.is(tok::kw_asm)) {
2343 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2344 if (AsmLabel.isInvalid()) {
2345 SkipUntil(tok::semi, StopBeforeMatch);
2349 D.setAsmLabel(AsmLabel.get());
2353 MaybeParseGNUAttributes(D);
2357 /// Parse 'declaration' after parsing 'declaration-specifiers
2358 /// declarator'. This method parses the remainder of the declaration
2359 /// (including any attributes or initializer, among other things) and
2360 /// finalizes the declaration.
2362 /// init-declarator: [C99 6.7]
2364 /// declarator '=' initializer
2365 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2366 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2367 /// [C++] declarator initializer[opt]
2369 /// [C++] initializer:
2370 /// [C++] '=' initializer-clause
2371 /// [C++] '(' expression-list ')'
2372 /// [C++0x] '=' 'default' [TODO]
2373 /// [C++0x] '=' 'delete'
2374 /// [C++0x] braced-init-list
2376 /// According to the standard grammar, =default and =delete are function
2377 /// definitions, but that definitely doesn't fit with the parser here.
2379 Decl *Parser::ParseDeclarationAfterDeclarator(
2380 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2381 if (ParseAsmAttributesAfterDeclarator(D))
2384 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2387 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2388 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2389 // RAII type used to track whether we're inside an initializer.
2390 struct InitializerScopeRAII {
2395 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2396 : P(P), D(D), ThisDecl(ThisDecl) {
2397 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2399 if (D.getCXXScopeSpec().isSet()) {
2401 S = P.getCurScope();
2403 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2406 ~InitializerScopeRAII() { pop(); }
2408 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2410 if (D.getCXXScopeSpec().isSet())
2411 S = P.getCurScope();
2412 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2420 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2421 InitKind TheInitKind;
2422 // If a '==' or '+=' is found, suggest a fixit to '='.
2423 if (isTokenEqualOrEqualTypo())
2424 TheInitKind = InitKind::Equal;
2425 else if (Tok.is(tok::l_paren))
2426 TheInitKind = InitKind::CXXDirect;
2427 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2428 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2429 TheInitKind = InitKind::CXXBraced;
2431 TheInitKind = InitKind::Uninitialized;
2432 if (TheInitKind != InitKind::Uninitialized)
2433 D.setHasInitializer();
2435 // Inform Sema that we just parsed this declarator.
2436 Decl *ThisDecl = nullptr;
2437 Decl *OuterDecl = nullptr;
2438 switch (TemplateInfo.Kind) {
2439 case ParsedTemplateInfo::NonTemplate:
2440 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2443 case ParsedTemplateInfo::Template:
2444 case ParsedTemplateInfo::ExplicitSpecialization: {
2445 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2446 *TemplateInfo.TemplateParams,
2448 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2449 // Re-direct this decl to refer to the templated decl so that we can
2451 ThisDecl = VT->getTemplatedDecl();
2456 case ParsedTemplateInfo::ExplicitInstantiation: {
2457 if (Tok.is(tok::semi)) {
2458 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2459 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2460 if (ThisRes.isInvalid()) {
2461 SkipUntil(tok::semi, StopBeforeMatch);
2464 ThisDecl = ThisRes.get();
2466 // FIXME: This check should be for a variable template instantiation only.
2468 // Check that this is a valid instantiation
2469 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2470 // If the declarator-id is not a template-id, issue a diagnostic and
2471 // recover by ignoring the 'template' keyword.
2472 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2473 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2474 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2476 SourceLocation LAngleLoc =
2477 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2478 Diag(D.getIdentifierLoc(),
2479 diag::err_explicit_instantiation_with_definition)
2480 << SourceRange(TemplateInfo.TemplateLoc)
2481 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2483 // Recover as if it were an explicit specialization.
2484 TemplateParameterLists FakedParamLists;
2485 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2486 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2487 std::nullopt, LAngleLoc, nullptr));
2490 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2497 switch (TheInitKind) {
2498 // Parse declarator '=' initializer.
2499 case InitKind::Equal: {
2500 SourceLocation EqualLoc = ConsumeToken();
2502 if (Tok.is(tok::kw_delete)) {
2503 if (D.isFunctionDeclarator())
2504 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2507 Diag(ConsumeToken(), diag::err_deleted_non_function);
2508 } else if (Tok.is(tok::kw_default)) {
2509 if (D.isFunctionDeclarator())
2510 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2513 Diag(ConsumeToken(), diag::err_default_special_members)
2514 << getLangOpts().CPlusPlus20;
2516 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2518 if (Tok.is(tok::code_completion)) {
2520 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2521 Actions.FinalizeDeclaration(ThisDecl);
2525 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2526 ExprResult Init = ParseInitializer();
2528 // If this is the only decl in (possibly) range based for statement,
2529 // our best guess is that the user meant ':' instead of '='.
2530 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2531 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2532 << FixItHint::CreateReplacement(EqualLoc, ":");
2533 // We are trying to stop parser from looking for ';' in this for
2534 // statement, therefore preventing spurious errors to be issued.
2535 FRI->ColonLoc = EqualLoc;
2537 FRI->RangeExpr = Init;
2542 if (Init.isInvalid()) {
2543 SmallVector<tok::TokenKind, 2> StopTokens;
2544 StopTokens.push_back(tok::comma);
2545 if (D.getContext() == DeclaratorContext::ForInit ||
2546 D.getContext() == DeclaratorContext::SelectionInit)
2547 StopTokens.push_back(tok::r_paren);
2548 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2549 Actions.ActOnInitializerError(ThisDecl);
2551 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2552 /*DirectInit=*/false);
2556 case InitKind::CXXDirect: {
2557 // Parse C++ direct initializer: '(' expression-list ')'
2558 BalancedDelimiterTracker T(*this, tok::l_paren);
2563 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2565 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2566 auto RunSignatureHelp = [&]() {
2567 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2568 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2569 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2571 CalledSignatureHelp = true;
2572 return PreferredType;
2574 auto SetPreferredType = [&] {
2575 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2578 llvm::function_ref<void()> ExpressionStarts;
2580 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2581 // VarDecl. This is an error and it is reported in a call to
2582 // Actions.ActOnInitializerError(). However, we call
2583 // ProduceConstructorSignatureHelp only on VarDecls.
2584 ExpressionStarts = SetPreferredType;
2586 if (ParseExpressionList(Exprs, ExpressionStarts)) {
2587 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2588 Actions.ProduceConstructorSignatureHelp(
2589 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2590 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2592 CalledSignatureHelp = true;
2594 Actions.ActOnInitializerError(ThisDecl);
2595 SkipUntil(tok::r_paren, StopAtSemi);
2601 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2602 T.getCloseLocation(),
2604 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2605 /*DirectInit=*/true);
2609 case InitKind::CXXBraced: {
2610 // Parse C++0x braced-init-list.
2611 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2613 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2615 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2616 ExprResult Init(ParseBraceInitializer());
2620 if (Init.isInvalid()) {
2621 Actions.ActOnInitializerError(ThisDecl);
2623 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2626 case InitKind::Uninitialized: {
2627 Actions.ActOnUninitializedDecl(ThisDecl);
2632 Actions.FinalizeDeclaration(ThisDecl);
2633 return OuterDecl ? OuterDecl : ThisDecl;
2636 /// ParseSpecifierQualifierList
2637 /// specifier-qualifier-list:
2638 /// type-specifier specifier-qualifier-list[opt]
2639 /// type-qualifier specifier-qualifier-list[opt]
2640 /// [GNU] attributes specifier-qualifier-list[opt]
2642 void Parser::ParseSpecifierQualifierList(
2643 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2644 AccessSpecifier AS, DeclSpecContext DSC) {
2645 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2646 /// parse declaration-specifiers and complain about extra stuff.
2647 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2648 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC, nullptr,
2649 AllowImplicitTypename);
2651 // Validate declspec for type-name.
2652 unsigned Specs = DS.getParsedSpecifiers();
2653 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2654 Diag(Tok, diag::err_expected_type);
2655 DS.SetTypeSpecError();
2656 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2657 Diag(Tok, diag::err_typename_requires_specqual);
2658 if (!DS.hasTypeSpecifier())
2659 DS.SetTypeSpecError();
2662 // Issue diagnostic and remove storage class if present.
2663 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2664 if (DS.getStorageClassSpecLoc().isValid())
2665 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2667 Diag(DS.getThreadStorageClassSpecLoc(),
2668 diag::err_typename_invalid_storageclass);
2669 DS.ClearStorageClassSpecs();
2672 // Issue diagnostic and remove function specifier if present.
2673 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2674 if (DS.isInlineSpecified())
2675 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2676 if (DS.isVirtualSpecified())
2677 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2678 if (DS.hasExplicitSpecifier())
2679 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2680 if (DS.isNoreturnSpecified())
2681 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2682 DS.ClearFunctionSpecs();
2685 // Issue diagnostic and remove constexpr specifier if present.
2686 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2687 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2688 << static_cast<int>(DS.getConstexprSpecifier());
2689 DS.ClearConstexprSpec();
2693 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2694 /// specified token is valid after the identifier in a declarator which
2695 /// immediately follows the declspec. For example, these things are valid:
2697 /// int x [ 4]; // direct-declarator
2698 /// int x ( int y); // direct-declarator
2699 /// int(int x ) // direct-declarator
2700 /// int x ; // simple-declaration
2701 /// int x = 17; // init-declarator-list
2702 /// int x , y; // init-declarator-list
2703 /// int x __asm__ ("foo"); // init-declarator-list
2704 /// int x : 4; // struct-declarator
2705 /// int x { 5}; // C++'0x unified initializers
2707 /// This is not, because 'x' does not immediately follow the declspec (though
2708 /// ')' happens to be valid anyway).
2711 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2712 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2713 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2717 /// ParseImplicitInt - This method is called when we have an non-typename
2718 /// identifier in a declspec (which normally terminates the decl spec) when
2719 /// the declspec has no type specifier. In this case, the declspec is either
2720 /// malformed or is "implicit int" (in K&R and C89).
2722 /// This method handles diagnosing this prettily and returns false if the
2723 /// declspec is done being processed. If it recovers and thinks there may be
2724 /// other pieces of declspec after it, it returns true.
2726 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2727 const ParsedTemplateInfo &TemplateInfo,
2728 AccessSpecifier AS, DeclSpecContext DSC,
2729 ParsedAttributes &Attrs) {
2730 assert(Tok.is(tok::identifier) && "should have identifier");
2732 SourceLocation Loc = Tok.getLocation();
2733 // If we see an identifier that is not a type name, we normally would
2734 // parse it as the identifier being declared. However, when a typename
2735 // is typo'd or the definition is not included, this will incorrectly
2736 // parse the typename as the identifier name and fall over misparsing
2737 // later parts of the diagnostic.
2739 // As such, we try to do some look-ahead in cases where this would
2740 // otherwise be an "implicit-int" case to see if this is invalid. For
2741 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2742 // an identifier with implicit int, we'd get a parse error because the
2743 // next token is obviously invalid for a type. Parse these as a case
2744 // with an invalid type specifier.
2745 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2747 // Since we know that this either implicit int (which is rare) or an
2748 // error, do lookahead to try to do better recovery. This never applies
2749 // within a type specifier. Outside of C++, we allow this even if the
2750 // language doesn't "officially" support implicit int -- we support
2751 // implicit int as an extension in some language modes.
2752 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2753 isValidAfterIdentifierInDeclarator(NextToken())) {
2754 // If this token is valid for implicit int, e.g. "static x = 4", then
2755 // we just avoid eating the identifier, so it will be parsed as the
2756 // identifier in the declarator.
2760 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2761 // for incomplete declarations such as `pipe p`.
2762 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2765 if (getLangOpts().CPlusPlus &&
2766 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2767 // Don't require a type specifier if we have the 'auto' storage class
2768 // specifier in C++98 -- we'll promote it to a type specifier.
2770 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2774 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2775 getLangOpts().MSVCCompat) {
2776 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2777 // Give Sema a chance to recover if we are in a template with dependent base
2779 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2780 *Tok.getIdentifierInfo(), Tok.getLocation(),
2781 DSC == DeclSpecContext::DSC_template_type_arg)) {
2782 const char *PrevSpec;
2784 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2785 Actions.getASTContext().getPrintingPolicy());
2786 DS.SetRangeEnd(Tok.getLocation());
2792 // Otherwise, if we don't consume this token, we are going to emit an
2793 // error anyway. Try to recover from various common problems. Check
2794 // to see if this was a reference to a tag name without a tag specified.
2795 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2797 // C++ doesn't need this, and isTagName doesn't take SS.
2798 if (SS == nullptr) {
2799 const char *TagName = nullptr, *FixitTagName = nullptr;
2800 tok::TokenKind TagKind = tok::unknown;
2802 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2804 case DeclSpec::TST_enum:
2805 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2806 case DeclSpec::TST_union:
2807 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2808 case DeclSpec::TST_struct:
2809 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2810 case DeclSpec::TST_interface:
2811 TagName="__interface"; FixitTagName = "__interface ";
2812 TagKind=tok::kw___interface;break;
2813 case DeclSpec::TST_class:
2814 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2818 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2819 LookupResult R(Actions, TokenName, SourceLocation(),
2820 Sema::LookupOrdinaryName);
2822 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2823 << TokenName << TagName << getLangOpts().CPlusPlus
2824 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2826 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2827 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2829 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2830 << TokenName << TagName;
2833 // Parse this as a tag as if the missing tag were present.
2834 if (TagKind == tok::kw_enum)
2835 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2836 DeclSpecContext::DSC_normal);
2838 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2839 /*EnteringContext*/ false,
2840 DeclSpecContext::DSC_normal, Attrs);
2845 // Determine whether this identifier could plausibly be the name of something
2846 // being declared (with a missing type).
2847 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2848 DSC == DeclSpecContext::DSC_class)) {
2849 // Look ahead to the next token to try to figure out what this declaration
2850 // was supposed to be.
2851 switch (NextToken().getKind()) {
2852 case tok::l_paren: {
2853 // static x(4); // 'x' is not a type
2854 // x(int n); // 'x' is not a type
2855 // x (*p)[]; // 'x' is a type
2857 // Since we're in an error case, we can afford to perform a tentative
2858 // parse to determine which case we're in.
2859 TentativeParsingAction PA(*this);
2861 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2864 if (TPR != TPResult::False) {
2865 // The identifier is followed by a parenthesized declarator.
2866 // It's supposed to be a type.
2870 // If we're in a context where we could be declaring a constructor,
2871 // check whether this is a constructor declaration with a bogus name.
2872 if (DSC == DeclSpecContext::DSC_class ||
2873 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2874 IdentifierInfo *II = Tok.getIdentifierInfo();
2875 if (Actions.isCurrentClassNameTypo(II, SS)) {
2876 Diag(Loc, diag::err_constructor_bad_name)
2877 << Tok.getIdentifierInfo() << II
2878 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2879 Tok.setIdentifierInfo(II);
2891 // This looks like a variable or function declaration. The type is
2892 // probably missing. We're done parsing decl-specifiers.
2893 // But only if we are not in a function prototype scope.
2894 if (getCurScope()->isFunctionPrototypeScope())
2897 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2901 // This is probably supposed to be a type. This includes cases like:
2903 // struct S { unsigned : 4; };
2908 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2909 // and attempt to recover.
2911 IdentifierInfo *II = Tok.getIdentifierInfo();
2912 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2913 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2916 // The action has suggested that the type T could be used. Set that as
2917 // the type in the declaration specifiers, consume the would-be type
2918 // name token, and we're done.
2919 const char *PrevSpec;
2921 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2922 Actions.getASTContext().getPrintingPolicy());
2923 DS.SetRangeEnd(Tok.getLocation());
2925 // There may be other declaration specifiers after this.
2927 } else if (II != Tok.getIdentifierInfo()) {
2928 // If no type was suggested, the correction is to a keyword
2929 Tok.setKind(II->getTokenID());
2930 // There may be other declaration specifiers after this.
2934 // Otherwise, the action had no suggestion for us. Mark this as an error.
2935 DS.SetTypeSpecError();
2936 DS.SetRangeEnd(Tok.getLocation());
2939 // Eat any following template arguments.
2940 if (IsTemplateName) {
2941 SourceLocation LAngle, RAngle;
2942 TemplateArgList Args;
2943 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2946 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2947 // avoid rippling error messages on subsequent uses of the same type,
2948 // could be useful if #include was forgotten.
2952 /// Determine the declaration specifier context from the declarator
2955 /// \param Context the declarator context, which is one of the
2956 /// DeclaratorContext enumerator values.
2957 Parser::DeclSpecContext
2958 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2960 case DeclaratorContext::Member:
2961 return DeclSpecContext::DSC_class;
2962 case DeclaratorContext::File:
2963 return DeclSpecContext::DSC_top_level;
2964 case DeclaratorContext::TemplateParam:
2965 return DeclSpecContext::DSC_template_param;
2966 case DeclaratorContext::TemplateArg:
2967 return DeclSpecContext::DSC_template_arg;
2968 case DeclaratorContext::TemplateTypeArg:
2969 return DeclSpecContext::DSC_template_type_arg;
2970 case DeclaratorContext::TrailingReturn:
2971 case DeclaratorContext::TrailingReturnVar:
2972 return DeclSpecContext::DSC_trailing;
2973 case DeclaratorContext::AliasDecl:
2974 case DeclaratorContext::AliasTemplate:
2975 return DeclSpecContext::DSC_alias_declaration;
2976 case DeclaratorContext::Association:
2977 return DeclSpecContext::DSC_association;
2978 case DeclaratorContext::TypeName:
2979 return DeclSpecContext::DSC_type_specifier;
2980 case DeclaratorContext::Condition:
2981 return DeclSpecContext::DSC_condition;
2982 case DeclaratorContext::ConversionId:
2983 return DeclSpecContext::DSC_conv_operator;
2984 case DeclaratorContext::CXXNew:
2985 return DeclSpecContext::DSC_new;
2986 case DeclaratorContext::Prototype:
2987 case DeclaratorContext::ObjCResult:
2988 case DeclaratorContext::ObjCParameter:
2989 case DeclaratorContext::KNRTypeList:
2990 case DeclaratorContext::FunctionalCast:
2991 case DeclaratorContext::Block:
2992 case DeclaratorContext::ForInit:
2993 case DeclaratorContext::SelectionInit:
2994 case DeclaratorContext::CXXCatch:
2995 case DeclaratorContext::ObjCCatch:
2996 case DeclaratorContext::BlockLiteral:
2997 case DeclaratorContext::LambdaExpr:
2998 case DeclaratorContext::LambdaExprParameter:
2999 case DeclaratorContext::RequiresExpr:
3000 return DeclSpecContext::DSC_normal;
3003 llvm_unreachable("Missing DeclaratorContext case");
3006 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
3009 /// [C11] constant-expression
3010 /// [C++0x] type-id ...[opt]
3011 /// [C++0x] assignment-expression ...[opt]
3012 ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3013 SourceLocation &EllipsisLoc, bool &IsType,
3014 ParsedType &TypeResult) {
3016 if (isTypeIdInParens()) {
3017 SourceLocation TypeLoc = Tok.getLocation();
3018 ParsedType Ty = ParseTypeName().get();
3019 SourceRange TypeRange(Start, Tok.getLocation());
3020 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3025 ER = ParseConstantExpression();
3029 if (getLangOpts().CPlusPlus11)
3030 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3035 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3036 /// attribute to Attrs.
3038 /// alignment-specifier:
3039 /// [C11] '_Alignas' '(' type-id ')'
3040 /// [C11] '_Alignas' '(' constant-expression ')'
3041 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
3042 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3043 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3044 SourceLocation *EndLoc) {
3045 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3046 "Not an alignment-specifier!");
3048 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3049 auto Kind = KWTok.getKind();
3050 SourceLocation KWLoc = ConsumeToken();
3052 BalancedDelimiterTracker T(*this, tok::l_paren);
3053 if (T.expectAndConsume())
3057 ParsedType TypeResult;
3058 SourceLocation EllipsisLoc;
3059 ExprResult ArgExpr =
3060 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3061 EllipsisLoc, IsType, TypeResult);
3062 if (ArgExpr.isInvalid()) {
3069 *EndLoc = T.getCloseLocation();
3072 Attrs.addNewTypeAttr(KWName, KWLoc, nullptr, KWLoc, TypeResult, Kind,
3075 ArgsVector ArgExprs;
3076 ArgExprs.push_back(ArgExpr.get());
3077 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3082 ExprResult Parser::ParseExtIntegerArgument() {
3083 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3084 "Not an extended int type");
3087 BalancedDelimiterTracker T(*this, tok::l_paren);
3088 if (T.expectAndConsume())
3091 ExprResult ER = ParseConstantExpression();
3092 if (ER.isInvalid()) {
3097 if(T.consumeClose())
3102 /// Determine whether we're looking at something that might be a declarator
3103 /// in a simple-declaration. If it can't possibly be a declarator, maybe
3104 /// diagnose a missing semicolon after a prior tag definition in the decl
3107 /// \return \c true if an error occurred and this can't be any kind of
3110 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3111 DeclSpecContext DSContext,
3112 LateParsedAttrList *LateAttrs) {
3113 assert(DS.hasTagDefinition() && "shouldn't call this");
3115 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3116 DSContext == DeclSpecContext::DSC_top_level);
3118 if (getLangOpts().CPlusPlus &&
3119 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3120 tok::annot_template_id) &&
3121 TryAnnotateCXXScopeToken(EnteringContext)) {
3122 SkipMalformedDecl();
3126 bool HasScope = Tok.is(tok::annot_cxxscope);
3127 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3128 Token AfterScope = HasScope ? NextToken() : Tok;
3130 // Determine whether the following tokens could possibly be a
3132 bool MightBeDeclarator = true;
3133 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3134 // A declarator-id can't start with 'typename'.
3135 MightBeDeclarator = false;
3136 } else if (AfterScope.is(tok::annot_template_id)) {
3137 // If we have a type expressed as a template-id, this cannot be a
3138 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3139 TemplateIdAnnotation *Annot =
3140 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3141 if (Annot->Kind == TNK_Type_template)
3142 MightBeDeclarator = false;
3143 } else if (AfterScope.is(tok::identifier)) {
3144 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3146 // These tokens cannot come after the declarator-id in a
3147 // simple-declaration, and are likely to come after a type-specifier.
3148 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3149 tok::annot_cxxscope, tok::coloncolon)) {
3150 // Missing a semicolon.
3151 MightBeDeclarator = false;
3152 } else if (HasScope) {
3153 // If the declarator-id has a scope specifier, it must redeclare a
3154 // previously-declared entity. If that's a type (and this is not a
3155 // typedef), that's an error.
3157 Actions.RestoreNestedNameSpecifierAnnotation(
3158 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3159 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3160 Sema::NameClassification Classification = Actions.ClassifyName(
3161 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3163 switch (Classification.getKind()) {
3164 case Sema::NC_Error:
3165 SkipMalformedDecl();
3168 case Sema::NC_Keyword:
3169 llvm_unreachable("typo correction is not possible here");
3172 case Sema::NC_TypeTemplate:
3173 case Sema::NC_UndeclaredNonType:
3174 case Sema::NC_UndeclaredTemplate:
3175 // Not a previously-declared non-type entity.
3176 MightBeDeclarator = false;
3179 case Sema::NC_Unknown:
3180 case Sema::NC_NonType:
3181 case Sema::NC_DependentNonType:
3182 case Sema::NC_OverloadSet:
3183 case Sema::NC_VarTemplate:
3184 case Sema::NC_FunctionTemplate:
3185 case Sema::NC_Concept:
3186 // Might be a redeclaration of a prior entity.
3192 if (MightBeDeclarator)
3195 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3196 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
3197 diag::err_expected_after)
3198 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3200 // Try to recover from the typo, by dropping the tag definition and parsing
3201 // the problematic tokens as a type.
3203 // FIXME: Split the DeclSpec into pieces for the standalone
3204 // declaration and pieces for the following declaration, instead
3205 // of assuming that all the other pieces attach to new declaration,
3206 // and call ParsedFreeStandingDeclSpec as appropriate.
3207 DS.ClearTypeSpecType();
3208 ParsedTemplateInfo NotATemplate;
3209 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3213 // Choose the apprpriate diagnostic error for why fixed point types are
3214 // disabled, set the previous specifier, and mark as invalid.
3215 static void SetupFixedPointError(const LangOptions &LangOpts,
3216 const char *&PrevSpec, unsigned &DiagID,
3218 assert(!LangOpts.FixedPoint);
3219 DiagID = diag::err_fixed_point_not_enabled;
3220 PrevSpec = ""; // Not used by diagnostic
3224 /// ParseDeclarationSpecifiers
3225 /// declaration-specifiers: [C99 6.7]
3226 /// storage-class-specifier declaration-specifiers[opt]
3227 /// type-specifier declaration-specifiers[opt]
3228 /// [C99] function-specifier declaration-specifiers[opt]
3229 /// [C11] alignment-specifier declaration-specifiers[opt]
3230 /// [GNU] attributes declaration-specifiers[opt]
3231 /// [Clang] '__module_private__' declaration-specifiers[opt]
3232 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3234 /// storage-class-specifier: [C99 6.7.1]
3241 /// [C++11] 'thread_local'
3242 /// [C11] '_Thread_local'
3243 /// [GNU] '__thread'
3244 /// function-specifier: [C99 6.7.4]
3247 /// [C++] 'explicit'
3248 /// [OpenCL] '__kernel'
3249 /// 'friend': [C++ dcl.friend]
3250 /// 'constexpr': [C++0x dcl.constexpr]
3251 void Parser::ParseDeclarationSpecifiers(
3252 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3253 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3254 ImplicitTypenameContext AllowImplicitTypename) {
3255 if (DS.getSourceRange().isInvalid()) {
3256 // Start the range at the current token but make the end of the range
3257 // invalid. This will make the entire range invalid unless we successfully
3259 DS.SetRangeStart(Tok.getLocation());
3260 DS.SetRangeEnd(SourceLocation());
3263 // If we are in a operator context, convert it back into a type specifier
3264 // context for better error handling later on.
3265 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3266 // No implicit typename here.
3267 AllowImplicitTypename = ImplicitTypenameContext::No;
3268 DSContext = DeclSpecContext::DSC_type_specifier;
3271 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3272 DSContext == DeclSpecContext::DSC_top_level);
3273 bool AttrsLastTime = false;
3274 ParsedAttributes attrs(AttrFactory);
3275 // We use Sema's policy to get bool macros right.
3276 PrintingPolicy Policy = Actions.getPrintingPolicy();
3278 bool isInvalid = false;
3279 bool isStorageClass = false;
3280 const char *PrevSpec = nullptr;
3281 unsigned DiagID = 0;
3283 // This value needs to be set to the location of the last token if the last
3284 // token of the specifier is already consumed.
3285 SourceLocation ConsumedEnd;
3287 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3288 // implementation for VS2013 uses _Atomic as an identifier for one of the
3289 // classes in <atomic>.
3291 // A typedef declaration containing _Atomic<...> is among the places where
3292 // the class is used. If we are currently parsing such a declaration, treat
3293 // the token as an identifier.
3294 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3295 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3296 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3297 Tok.setKind(tok::identifier);
3299 SourceLocation Loc = Tok.getLocation();
3301 // Helper for image types in OpenCL.
3302 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3303 // Check if the image type is supported and otherwise turn the keyword into an identifier
3304 // because image types from extensions are not reserved identifiers.
3305 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3306 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3307 Tok.setKind(tok::identifier);
3310 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3314 // Turn off usual access checking for template specializations and
3316 bool IsTemplateSpecOrInst =
3317 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3318 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3320 switch (Tok.getKind()) {
3322 if (Tok.isRegularKeywordAttribute())
3327 ProhibitAttributes(attrs);
3329 // Reject C++11 / C2x attributes that aren't type attributes.
3330 for (const ParsedAttr &PA : attrs) {
3331 if (!PA.isCXX11Attribute() && !PA.isC2xAttribute() &&
3332 !PA.isRegularKeywordAttribute())
3334 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3335 // We will warn about the unknown attribute elsewhere (in
3336 // SemaDeclAttr.cpp)
3338 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3339 // syntax, so we do the same.
3340 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3341 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3345 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3346 // are type attributes, because we historically haven't allowed these
3347 // to be used as type attributes in C++11 / C2x syntax.
3348 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3349 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3351 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3352 << PA << PA.isRegularKeywordAttribute();
3356 DS.takeAttributesFrom(attrs);
3359 // If this is not a declaration specifier token, we're done reading decl
3360 // specifiers. First verify that DeclSpec's are consistent.
3361 DS.Finish(Actions, Policy);
3365 case tok::kw_alignas:
3366 if (!isAllowedCXX11AttributeSpecifier())
3367 goto DoneWithDeclSpec;
3370 ProhibitAttributes(attrs);
3371 // FIXME: It would be good to recover by accepting the attributes,
3372 // but attempting to do that now would cause serious
3373 // madness in terms of diagnostics.
3375 attrs.Range = SourceRange();
3377 ParseCXX11Attributes(attrs);
3378 AttrsLastTime = true;
3381 case tok::code_completion: {
3382 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3383 if (DS.hasTypeSpecifier()) {
3384 bool AllowNonIdentifiers
3385 = (getCurScope()->getFlags() & (Scope::ControlScope |
3387 Scope::TemplateParamScope |
3388 Scope::FunctionPrototypeScope |
3389 Scope::AtCatchScope)) == 0;
3390 bool AllowNestedNameSpecifiers
3391 = DSContext == DeclSpecContext::DSC_top_level ||
3392 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3395 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3396 AllowNonIdentifiers,
3397 AllowNestedNameSpecifiers);
3401 // Class context can appear inside a function/block, so prioritise that.
3402 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3403 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3404 : Sema::PCC_Template;
3405 else if (DSContext == DeclSpecContext::DSC_class)
3406 CCC = Sema::PCC_Class;
3407 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3408 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3409 else if (CurParsedObjCImpl)
3410 CCC = Sema::PCC_ObjCImplementation;
3413 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3417 case tok::coloncolon: // ::foo::bar
3418 // C++ scope specifier. Annotate and loop, or bail out on error.
3419 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3420 if (!DS.hasTypeSpecifier())
3421 DS.SetTypeSpecError();
3422 goto DoneWithDeclSpec;
3424 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3425 goto DoneWithDeclSpec;
3428 case tok::annot_cxxscope: {
3429 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3430 goto DoneWithDeclSpec;
3433 if (TemplateInfo.TemplateParams)
3434 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3435 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3436 Tok.getAnnotationRange(),
3439 // We are looking for a qualified typename.
3440 Token Next = NextToken();
3442 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3443 ? takeTemplateIdAnnotation(Next)
3445 if (TemplateId && TemplateId->hasInvalidName()) {
3446 // We found something like 'T::U<Args> x', but U is not a template.
3447 // Assume it was supposed to be a type.
3448 DS.SetTypeSpecError();
3449 ConsumeAnnotationToken();
3453 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3454 // We have a qualified template-id, e.g., N::A<int>
3456 // If this would be a valid constructor declaration with template
3457 // arguments, we will reject the attempt to form an invalid type-id
3458 // referring to the injected-class-name when we annotate the token,
3459 // per C++ [class.qual]p2.
3461 // To improve diagnostics for this case, parse the declaration as a
3462 // constructor (and reject the extra template arguments later).
3463 if ((DSContext == DeclSpecContext::DSC_top_level ||
3464 DSContext == DeclSpecContext::DSC_class) &&
3466 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3467 isConstructorDeclarator(/*Unqualified=*/false,
3468 /*DeductionGuide=*/false,
3469 DS.isFriendSpecified())) {
3470 // The user meant this to be an out-of-line constructor
3471 // definition, but template arguments are not allowed
3472 // there. Just allow this as a constructor; we'll
3473 // complain about it later.
3474 goto DoneWithDeclSpec;
3477 DS.getTypeSpecScope() = SS;
3478 ConsumeAnnotationToken(); // The C++ scope.
3479 assert(Tok.is(tok::annot_template_id) &&
3480 "ParseOptionalCXXScopeSpecifier not working");
3481 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3485 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3486 DS.getTypeSpecScope() = SS;
3487 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3488 // auto ... Consume the scope annotation and continue to consume the
3489 // template-id as a placeholder-specifier. Let the next iteration
3490 // diagnose a missing auto.
3491 ConsumeAnnotationToken();
3495 if (Next.is(tok::annot_typename)) {
3496 DS.getTypeSpecScope() = SS;
3497 ConsumeAnnotationToken(); // The C++ scope.
3498 TypeResult T = getTypeAnnotation(Tok);
3499 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3500 Tok.getAnnotationEndLoc(),
3501 PrevSpec, DiagID, T, Policy);
3504 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3505 ConsumeAnnotationToken(); // The typename
3508 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3509 Next.is(tok::annot_template_id) &&
3510 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3511 ->Kind == TNK_Dependent_template_name) {
3512 DS.getTypeSpecScope() = SS;
3513 ConsumeAnnotationToken(); // The C++ scope.
3514 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3518 if (Next.isNot(tok::identifier))
3519 goto DoneWithDeclSpec;
3521 // Check whether this is a constructor declaration. If we're in a
3522 // context where the identifier could be a class name, and it has the
3523 // shape of a constructor declaration, process it as one.
3524 if ((DSContext == DeclSpecContext::DSC_top_level ||
3525 DSContext == DeclSpecContext::DSC_class) &&
3526 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3528 isConstructorDeclarator(/*Unqualified=*/false,
3529 /*DeductionGuide=*/false,
3530 DS.isFriendSpecified(),
3532 goto DoneWithDeclSpec;
3534 // C++20 [temp.spec] 13.9/6.
3535 // This disables the access checking rules for function template explicit
3536 // instantiation and explicit specialization:
3538 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3540 ParsedType TypeRep = Actions.getTypeName(
3541 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3542 false, false, nullptr,
3543 /*IsCtorOrDtorName=*/false,
3544 /*WantNontrivialTypeSourceInfo=*/true,
3545 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3547 if (IsTemplateSpecOrInst)
3550 // If the referenced identifier is not a type, then this declspec is
3551 // erroneous: We already checked about that it has no type specifier, and
3552 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3555 if (TryAnnotateTypeConstraint())
3556 goto DoneWithDeclSpec;
3557 if (Tok.isNot(tok::annot_cxxscope) ||
3558 NextToken().isNot(tok::identifier))
3560 // Eat the scope spec so the identifier is current.
3561 ConsumeAnnotationToken();
3562 ParsedAttributes Attrs(AttrFactory);
3563 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3564 if (!Attrs.empty()) {
3565 AttrsLastTime = true;
3566 attrs.takeAllFrom(Attrs);
3570 goto DoneWithDeclSpec;
3573 DS.getTypeSpecScope() = SS;
3574 ConsumeAnnotationToken(); // The C++ scope.
3576 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3577 DiagID, TypeRep, Policy);
3581 DS.SetRangeEnd(Tok.getLocation());
3582 ConsumeToken(); // The typename.
3587 case tok::annot_typename: {
3588 // If we've previously seen a tag definition, we were almost surely
3589 // missing a semicolon after it.
3590 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3591 goto DoneWithDeclSpec;
3593 TypeResult T = getTypeAnnotation(Tok);
3594 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3599 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3600 ConsumeAnnotationToken(); // The typename
3605 case tok::kw___is_signed:
3606 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3607 // typically treats it as a trait. If we see __is_signed as it appears
3608 // in libstdc++, e.g.,
3610 // static const bool __is_signed;
3612 // then treat __is_signed as an identifier rather than as a keyword.
3613 if (DS.getTypeSpecType() == TST_bool &&
3614 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3615 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3616 TryKeywordIdentFallback(true);
3618 // We're done with the declaration-specifiers.
3619 goto DoneWithDeclSpec;
3622 case tok::kw___super:
3623 case tok::kw_decltype:
3624 case tok::identifier:
3626 // This identifier can only be a typedef name if we haven't already seen
3627 // a type-specifier. Without this check we misparse:
3628 // typedef int X; struct Y { short X; }; as 'short int'.
3629 if (DS.hasTypeSpecifier())
3630 goto DoneWithDeclSpec;
3632 // If the token is an identifier named "__declspec" and Microsoft
3633 // extensions are not enabled, it is likely that there will be cascading
3634 // parse errors if this really is a __declspec attribute. Attempt to
3635 // recognize that scenario and recover gracefully.
3636 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3637 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3638 Diag(Loc, diag::err_ms_attributes_not_enabled);
3640 // The next token should be an open paren. If it is, eat the entire
3641 // attribute declaration and continue.
3642 if (NextToken().is(tok::l_paren)) {
3643 // Consume the __declspec identifier.
3646 // Eat the parens and everything between them.
3647 BalancedDelimiterTracker T(*this, tok::l_paren);
3648 if (T.consumeOpen()) {
3649 assert(false && "Not a left paren?");
3657 // In C++, check to see if this is a scope specifier like foo::bar::, if
3658 // so handle it as such. This is important for ctor parsing.
3659 if (getLangOpts().CPlusPlus) {
3660 // C++20 [temp.spec] 13.9/6.
3661 // This disables the access checking rules for function template
3662 // explicit instantiation and explicit specialization:
3664 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3666 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3668 if (IsTemplateSpecOrInst)
3672 if (IsTemplateSpecOrInst)
3674 DS.SetTypeSpecError();
3675 goto DoneWithDeclSpec;
3678 if (!Tok.is(tok::identifier))
3682 // Check for need to substitute AltiVec keyword tokens.
3683 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3686 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3687 // allow the use of a typedef name as a type specifier.
3688 if (DS.isTypeAltiVecVector())
3689 goto DoneWithDeclSpec;
3691 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3692 isObjCInstancetype()) {
3693 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3695 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3696 DiagID, TypeRep, Policy);
3700 DS.SetRangeEnd(Loc);
3705 // If we're in a context where the identifier could be a class name,
3706 // check whether this is a constructor declaration.
3707 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3708 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3709 isConstructorDeclarator(/*Unqualified=*/true,
3710 /*DeductionGuide=*/false,
3711 DS.isFriendSpecified()))
3712 goto DoneWithDeclSpec;
3714 ParsedType TypeRep = Actions.getTypeName(
3715 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3716 false, false, nullptr, false, false,
3717 isClassTemplateDeductionContext(DSContext));
3719 // If this is not a typedef name, don't parse it as part of the declspec,
3720 // it must be an implicit int or an error.
3722 if (TryAnnotateTypeConstraint())
3723 goto DoneWithDeclSpec;
3724 if (Tok.isNot(tok::identifier))
3726 ParsedAttributes Attrs(AttrFactory);
3727 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3728 if (!Attrs.empty()) {
3729 AttrsLastTime = true;
3730 attrs.takeAllFrom(Attrs);
3734 goto DoneWithDeclSpec;
3737 // Likewise, if this is a context where the identifier could be a template
3738 // name, check whether this is a deduction guide declaration.
3740 if (getLangOpts().CPlusPlus17 &&
3741 (DSContext == DeclSpecContext::DSC_class ||
3742 DSContext == DeclSpecContext::DSC_top_level) &&
3743 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3744 Tok.getLocation(), SS) &&
3745 isConstructorDeclarator(/*Unqualified*/ true,
3746 /*DeductionGuide*/ true))
3747 goto DoneWithDeclSpec;
3749 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3750 DiagID, TypeRep, Policy);
3754 DS.SetRangeEnd(Tok.getLocation());
3755 ConsumeToken(); // The identifier
3757 // Objective-C supports type arguments and protocol references
3758 // following an Objective-C object or object pointer
3759 // type. Handle either one of them.
3760 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3761 SourceLocation NewEndLoc;
3762 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3763 Loc, TypeRep, /*consumeLastToken=*/true,
3765 if (NewTypeRep.isUsable()) {
3766 DS.UpdateTypeRep(NewTypeRep.get());
3767 DS.SetRangeEnd(NewEndLoc);
3771 // Need to support trailing type qualifiers (e.g. "id<p> const").
3772 // If a type specifier follows, it will be diagnosed elsewhere.
3776 // type-name or placeholder-specifier
3777 case tok::annot_template_id: {
3778 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3780 if (TemplateId->hasInvalidName()) {
3781 DS.SetTypeSpecError();
3785 if (TemplateId->Kind == TNK_Concept_template) {
3786 // If we've already diagnosed that this type-constraint has invalid
3787 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3788 if (TemplateId->hasInvalidArgs())
3789 TemplateId = nullptr;
3791 // Any of the following tokens are likely the start of the user
3792 // forgetting 'auto' or 'decltype(auto)', so diagnose.
3793 // Note: if updating this list, please make sure we update
3794 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3796 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3797 tok::kw_volatile, tok::kw_restrict, tok::amp,
3799 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3800 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3801 // Attempt to continue as if 'auto' was placed here.
3802 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3803 TemplateId, Policy);
3806 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3807 goto DoneWithDeclSpec;
3809 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
3810 TemplateId = nullptr;
3812 ConsumeAnnotationToken();
3813 SourceLocation AutoLoc = Tok.getLocation();
3814 if (TryConsumeToken(tok::kw_decltype)) {
3815 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3816 if (Tracker.consumeOpen()) {
3817 // Something like `void foo(Iterator decltype i)`
3818 Diag(Tok, diag::err_expected) << tok::l_paren;
3820 if (!TryConsumeToken(tok::kw_auto)) {
3821 // Something like `void foo(Iterator decltype(int) i)`
3822 Tracker.skipToEnd();
3823 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3824 << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3828 Tracker.consumeClose();
3831 ConsumedEnd = Tok.getLocation();
3832 DS.setTypeArgumentRange(Tracker.getRange());
3833 // Even if something went wrong above, continue as if we've seen
3834 // `decltype(auto)`.
3835 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3836 DiagID, TemplateId, Policy);
3838 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3839 TemplateId, Policy);
3844 if (TemplateId->Kind != TNK_Type_template &&
3845 TemplateId->Kind != TNK_Undeclared_template) {
3846 // This template-id does not refer to a type name, so we're
3847 // done with the type-specifiers.
3848 goto DoneWithDeclSpec;
3851 // If we're in a context where the template-id could be a
3852 // constructor name or specialization, check whether this is a
3853 // constructor declaration.
3854 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3855 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3856 isConstructorDeclarator(/*Unqualified=*/true,
3857 /*DeductionGuide=*/false,
3858 DS.isFriendSpecified()))
3859 goto DoneWithDeclSpec;
3861 // Turn the template-id annotation token into a type annotation
3862 // token, then try again to parse it as a type-specifier.
3864 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3868 // Attributes support.
3869 case tok::kw___attribute:
3870 case tok::kw___declspec:
3871 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
3874 // Microsoft single token adornments.
3875 case tok::kw___forceinline: {
3876 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3877 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3878 SourceLocation AttrNameLoc = Tok.getLocation();
3879 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3880 nullptr, 0, tok::kw___forceinline);
3884 case tok::kw___unaligned:
3885 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3889 case tok::kw___sptr:
3890 case tok::kw___uptr:
3891 case tok::kw___ptr64:
3892 case tok::kw___ptr32:
3894 case tok::kw___cdecl:
3895 case tok::kw___stdcall:
3896 case tok::kw___fastcall:
3897 case tok::kw___thiscall:
3898 case tok::kw___regcall:
3899 case tok::kw___vectorcall:
3900 ParseMicrosoftTypeAttributes(DS.getAttributes());
3903 case tok::kw___funcref:
3904 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
3907 // Borland single token adornments.
3908 case tok::kw___pascal:
3909 ParseBorlandTypeAttributes(DS.getAttributes());
3912 // OpenCL single token adornments.
3913 case tok::kw___kernel:
3914 ParseOpenCLKernelAttributes(DS.getAttributes());
3917 // CUDA/HIP single token adornments.
3918 case tok::kw___noinline__:
3919 ParseCUDAFunctionAttributes(DS.getAttributes());
3922 // Nullability type specifiers.
3923 case tok::kw__Nonnull:
3924 case tok::kw__Nullable:
3925 case tok::kw__Nullable_result:
3926 case tok::kw__Null_unspecified:
3927 ParseNullabilityTypeSpecifiers(DS.getAttributes());
3930 // Objective-C 'kindof' types.
3931 case tok::kw___kindof:
3932 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3933 nullptr, 0, tok::kw___kindof);
3934 (void)ConsumeToken();
3937 // storage-class-specifier
3938 case tok::kw_typedef:
3939 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3940 PrevSpec, DiagID, Policy);
3941 isStorageClass = true;
3943 case tok::kw_extern:
3944 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3945 Diag(Tok, diag::ext_thread_before) << "extern";
3946 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3947 PrevSpec, DiagID, Policy);
3948 isStorageClass = true;
3950 case tok::kw___private_extern__:
3951 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3952 Loc, PrevSpec, DiagID, Policy);
3953 isStorageClass = true;
3955 case tok::kw_static:
3956 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3957 Diag(Tok, diag::ext_thread_before) << "static";
3958 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3959 PrevSpec, DiagID, Policy);
3960 isStorageClass = true;
3963 if (getLangOpts().CPlusPlus11) {
3964 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3965 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3966 PrevSpec, DiagID, Policy);
3968 Diag(Tok, diag::ext_auto_storage_class)
3969 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3971 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3974 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3975 PrevSpec, DiagID, Policy);
3976 isStorageClass = true;
3978 case tok::kw___auto_type:
3979 Diag(Tok, diag::ext_auto_type);
3980 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3983 case tok::kw_register:
3984 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3985 PrevSpec, DiagID, Policy);
3986 isStorageClass = true;
3988 case tok::kw_mutable:
3989 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3990 PrevSpec, DiagID, Policy);
3991 isStorageClass = true;
3993 case tok::kw___thread:
3994 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3996 isStorageClass = true;
3998 case tok::kw_thread_local:
3999 if (getLangOpts().C2x)
4000 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4001 // We map thread_local to _Thread_local in C23 mode so it retains the C
4002 // semantics rather than getting the C++ semantics.
4003 // FIXME: diagnostics will show _Thread_local when the user wrote
4004 // thread_local in source in C23 mode; we need some general way to
4005 // identify which way the user spelled the keyword in source.
4006 isInvalid = DS.SetStorageClassSpecThread(
4007 getLangOpts().C2x ? DeclSpec::TSCS__Thread_local
4008 : DeclSpec::TSCS_thread_local,
4009 Loc, PrevSpec, DiagID);
4010 isStorageClass = true;
4012 case tok::kw__Thread_local:
4013 if (!getLangOpts().C11)
4014 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4015 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
4016 Loc, PrevSpec, DiagID);
4017 isStorageClass = true;
4020 // function-specifier
4021 case tok::kw_inline:
4022 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4024 case tok::kw_virtual:
4025 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4026 // function pointers restricted in OpenCL v2.0 s6.9.a.
4027 if (getLangOpts().OpenCLCPlusPlus &&
4028 !getActions().getOpenCLOptions().isAvailableOption(
4029 "__cl_clang_function_pointers", getLangOpts())) {
4030 DiagID = diag::err_openclcxx_virtual_function;
4031 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4034 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4037 case tok::kw_explicit: {
4038 SourceLocation ExplicitLoc = Loc;
4039 SourceLocation CloseParenLoc;
4040 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
4041 ConsumedEnd = ExplicitLoc;
4042 ConsumeToken(); // kw_explicit
4043 if (Tok.is(tok::l_paren)) {
4044 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4045 Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
4046 ? diag::warn_cxx17_compat_explicit_bool
4047 : diag::ext_explicit_bool);
4049 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4050 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4051 Tracker.consumeOpen();
4052 ExplicitExpr = ParseConstantExpression();
4053 ConsumedEnd = Tok.getLocation();
4054 if (ExplicitExpr.isUsable()) {
4055 CloseParenLoc = Tok.getLocation();
4056 Tracker.consumeClose();
4058 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4060 Tracker.skipToEnd();
4062 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4065 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4066 ExplicitSpec, CloseParenLoc);
4069 case tok::kw__Noreturn:
4070 if (!getLangOpts().C11)
4071 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4072 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4075 // alignment-specifier
4076 case tok::kw__Alignas:
4077 if (!getLangOpts().C11)
4078 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4079 ParseAlignmentSpecifier(DS.getAttributes());
4083 case tok::kw_friend:
4084 if (DSContext == DeclSpecContext::DSC_class)
4085 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4087 PrevSpec = ""; // not actually used by the diagnostic
4088 DiagID = diag::err_friend_invalid_in_context;
4094 case tok::kw___module_private__:
4095 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4098 // constexpr, consteval, constinit specifiers
4099 case tok::kw_constexpr:
4100 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
4103 case tok::kw_consteval:
4104 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
4107 case tok::kw_constinit:
4108 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
4114 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
4118 if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
4119 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
4122 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4123 PrevSpec, DiagID, Policy);
4125 case tok::kw___int64:
4126 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4127 PrevSpec, DiagID, Policy);
4129 case tok::kw_signed:
4131 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4133 case tok::kw_unsigned:
4134 isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
4137 case tok::kw__Complex:
4138 if (!getLangOpts().C99)
4139 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4140 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
4143 case tok::kw__Imaginary:
4144 if (!getLangOpts().C99)
4145 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4146 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
4150 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4154 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4158 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4161 case tok::kw__ExtInt:
4162 case tok::kw__BitInt: {
4163 DiagnoseBitIntUse(Tok);
4164 ExprResult ER = ParseExtIntegerArgument();
4167 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4168 ConsumedEnd = PrevTokLocation;
4171 case tok::kw___int128:
4172 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
4176 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4179 case tok::kw___bf16:
4180 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
4184 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4187 case tok::kw_double:
4188 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
4191 case tok::kw__Float16:
4192 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
4195 case tok::kw__Accum:
4196 if (!getLangOpts().FixedPoint) {
4197 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4199 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
4203 case tok::kw__Fract:
4204 if (!getLangOpts().FixedPoint) {
4205 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4207 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
4212 if (!getLangOpts().FixedPoint) {
4213 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4215 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4218 case tok::kw___float128:
4219 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
4222 case tok::kw___ibm128:
4223 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
4226 case tok::kw_wchar_t:
4227 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4230 case tok::kw_char8_t:
4231 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4234 case tok::kw_char16_t:
4235 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
4238 case tok::kw_char32_t:
4239 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
4243 if (getLangOpts().C2x)
4244 Diag(Tok, diag::warn_c2x_compat_keyword) << Tok.getName();
4247 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4248 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4250 if (Tok.is(tok::kw_bool) &&
4251 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
4252 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
4253 PrevSpec = ""; // Not used by the diagnostic.
4254 DiagID = diag::err_bool_redeclaration;
4255 // For better error recovery.
4256 Tok.setKind(tok::identifier);
4259 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4263 case tok::kw__Decimal32:
4264 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
4267 case tok::kw__Decimal64:
4268 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
4271 case tok::kw__Decimal128:
4272 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
4275 case tok::kw___vector:
4276 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4278 case tok::kw___pixel:
4279 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4281 case tok::kw___bool:
4282 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4285 if (!getLangOpts().OpenCL ||
4286 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4287 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4288 // should support the "pipe" word as identifier.
4289 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
4290 Tok.setKind(tok::identifier);
4291 goto DoneWithDeclSpec;
4292 } else if (!getLangOpts().OpenCLPipes) {
4293 DiagID = diag::err_opencl_unknown_type_specifier;
4294 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4297 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4299 // We only need to enumerate each image type once.
4300 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4301 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
4302 #define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4303 case tok::kw_##ImgType##_t: \
4304 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4305 goto DoneWithDeclSpec; \
4307 #include "clang/Basic/OpenCLImageTypes.def"
4308 case tok::kw___unknown_anytype:
4309 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
4310 PrevSpec, DiagID, Policy);
4315 case tok::kw_struct:
4316 case tok::kw___interface:
4317 case tok::kw_union: {
4318 tok::TokenKind Kind = Tok.getKind();
4321 // These are attributes following class specifiers.
4322 // To produce better diagnostic, we parse them when
4323 // parsing class specifier.
4324 ParsedAttributes Attributes(AttrFactory);
4325 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4326 EnteringContext, DSContext, Attributes);
4328 // If there are attributes following class specifier,
4329 // take them over and handle them here.
4330 if (!Attributes.empty()) {
4331 AttrsLastTime = true;
4332 attrs.takeAllFrom(Attributes);
4340 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4345 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4348 case tok::kw_volatile:
4349 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4352 case tok::kw_restrict:
4353 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4357 // C++ typename-specifier:
4358 case tok::kw_typename:
4359 if (TryAnnotateTypeOrScopeToken()) {
4360 DS.SetTypeSpecError();
4361 goto DoneWithDeclSpec;
4363 if (!Tok.is(tok::kw_typename))
4367 // C2x/GNU typeof support.
4368 case tok::kw_typeof:
4369 case tok::kw_typeof_unqual:
4370 ParseTypeofSpecifier(DS);
4373 case tok::annot_decltype:
4374 ParseDecltypeSpecifier(DS);
4377 case tok::annot_pragma_pack:
4381 case tok::annot_pragma_ms_pragma:
4382 HandlePragmaMSPragma();
4385 case tok::annot_pragma_ms_vtordisp:
4386 HandlePragmaMSVtorDisp();
4389 case tok::annot_pragma_ms_pointers_to_members:
4390 HandlePragmaMSPointersToMembers();
4393 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4394 #include "clang/Basic/TransformTypeTraits.def"
4395 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4396 // work around this by expecting all transform type traits to be suffixed
4397 // with '('. They're an identifier otherwise.
4398 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4399 goto ParseIdentifier;
4402 case tok::kw__Atomic:
4404 // If the _Atomic keyword is immediately followed by a left parenthesis,
4405 // it is interpreted as a type specifier (with a type name), not as a
4407 if (!getLangOpts().C11)
4408 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4410 if (NextToken().is(tok::l_paren)) {
4411 ParseAtomicSpecifier(DS);
4414 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4418 // OpenCL address space qualifiers:
4419 case tok::kw___generic:
4420 // generic address space is introduced only in OpenCL v2.0
4421 // see OpenCL C Spec v2.0 s6.5.5
4422 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4423 // feature macro to indicate if generic address space is supported
4424 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4425 DiagID = diag::err_opencl_unknown_type_specifier;
4426 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4431 case tok::kw_private:
4432 // It's fine (but redundant) to check this for __generic on the
4433 // fallthrough path; we only form the __generic token in OpenCL mode.
4434 if (!getLangOpts().OpenCL)
4435 goto DoneWithDeclSpec;
4437 case tok::kw___private:
4438 case tok::kw___global:
4439 case tok::kw___local:
4440 case tok::kw___constant:
4441 // OpenCL access qualifiers:
4442 case tok::kw___read_only:
4443 case tok::kw___write_only:
4444 case tok::kw___read_write:
4445 ParseOpenCLQualifiers(DS.getAttributes());
4448 case tok::kw_groupshared:
4449 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4450 ParseHLSLQualifiers(DS.getAttributes());
4454 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4455 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4456 // but we support it.
4457 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4458 goto DoneWithDeclSpec;
4460 SourceLocation StartLoc = Tok.getLocation();
4461 SourceLocation EndLoc;
4462 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4463 if (Type.isUsable()) {
4464 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4465 PrevSpec, DiagID, Type.get(),
4466 Actions.getASTContext().getPrintingPolicy()))
4467 Diag(StartLoc, DiagID) << PrevSpec;
4469 DS.SetRangeEnd(EndLoc);
4471 DS.SetTypeSpecError();
4474 // Need to support trailing type qualifiers (e.g. "id<p> const").
4475 // If a type specifier follows, it will be diagnosed elsewhere.
4479 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4481 // If the specifier wasn't legal, issue a diagnostic.
4483 assert(PrevSpec && "Method did not return previous specifier!");
4486 if (DiagID == diag::ext_duplicate_declspec ||
4487 DiagID == diag::ext_warn_duplicate_declspec ||
4488 DiagID == diag::err_duplicate_declspec)
4489 Diag(Loc, DiagID) << PrevSpec
4490 << FixItHint::CreateRemoval(
4491 SourceRange(Loc, DS.getEndLoc()));
4492 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4493 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4496 Diag(Loc, DiagID) << PrevSpec;
4499 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4500 // After an error the next token can be an annotation token.
4503 AttrsLastTime = false;
4507 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4510 /// Note that a struct declaration refers to a declaration in a struct,
4511 /// not to the declaration of a struct.
4513 /// struct-declaration:
4514 /// [C2x] attributes-specifier-seq[opt]
4515 /// specifier-qualifier-list struct-declarator-list
4516 /// [GNU] __extension__ struct-declaration
4517 /// [GNU] specifier-qualifier-list
4518 /// struct-declarator-list:
4519 /// struct-declarator
4520 /// struct-declarator-list ',' struct-declarator
4521 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4522 /// struct-declarator:
4524 /// [GNU] declarator attributes[opt]
4525 /// declarator[opt] ':' constant-expression
4526 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4528 void Parser::ParseStructDeclaration(
4529 ParsingDeclSpec &DS,
4530 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4532 if (Tok.is(tok::kw___extension__)) {
4533 // __extension__ silences extension warnings in the subexpression.
4534 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4536 return ParseStructDeclaration(DS, FieldsCallback);
4539 // Parse leading attributes.
4540 ParsedAttributes Attrs(AttrFactory);
4541 MaybeParseCXX11Attributes(Attrs);
4543 // Parse the common specifier-qualifiers-list piece.
4544 ParseSpecifierQualifierList(DS);
4546 // If there are no declarators, this is a free-standing declaration
4547 // specifier. Let the actions module cope with it.
4548 if (Tok.is(tok::semi)) {
4549 // C2x 6.7.2.1p9 : "The optional attribute specifier sequence in a
4550 // member declaration appertains to each of the members declared by the
4551 // member declarator list; it shall not appear if the optional member
4552 // declarator list is omitted."
4553 ProhibitAttributes(Attrs);
4554 RecordDecl *AnonRecord = nullptr;
4555 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4556 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4557 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4558 DS.complete(TheDecl);
4562 // Read struct-declarators until we find the semicolon.
4563 bool FirstDeclarator = true;
4564 SourceLocation CommaLoc;
4566 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4567 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4569 // Attributes are only allowed here on successive declarators.
4570 if (!FirstDeclarator) {
4571 // However, this does not apply for [[]] attributes (which could show up
4572 // before or after the __attribute__ attributes).
4573 DiagnoseAndSkipCXX11Attributes();
4574 MaybeParseGNUAttributes(DeclaratorInfo.D);
4575 DiagnoseAndSkipCXX11Attributes();
4578 /// struct-declarator: declarator
4579 /// struct-declarator: declarator[opt] ':' constant-expression
4580 if (Tok.isNot(tok::colon)) {
4581 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4582 ColonProtectionRAIIObject X(*this);
4583 ParseDeclarator(DeclaratorInfo.D);
4585 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4587 if (TryConsumeToken(tok::colon)) {
4588 ExprResult Res(ParseConstantExpression());
4589 if (Res.isInvalid())
4590 SkipUntil(tok::semi, StopBeforeMatch);
4592 DeclaratorInfo.BitfieldSize = Res.get();
4595 // If attributes exist after the declarator, parse them.
4596 MaybeParseGNUAttributes(DeclaratorInfo.D);
4598 // We're done with this declarator; invoke the callback.
4599 FieldsCallback(DeclaratorInfo);
4601 // If we don't have a comma, it is either the end of the list (a ';')
4602 // or an error, bail out.
4603 if (!TryConsumeToken(tok::comma, CommaLoc))
4606 FirstDeclarator = false;
4610 /// ParseStructUnionBody
4611 /// struct-contents:
4612 /// struct-declaration-list
4614 /// [GNU] "struct-declaration-list" without terminating ';'
4615 /// struct-declaration-list:
4616 /// struct-declaration
4617 /// struct-declaration-list struct-declaration
4618 /// [OBC] '@' 'defs' '(' class-name ')'
4620 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4621 DeclSpec::TST TagType, RecordDecl *TagDecl) {
4622 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4623 "parsing struct/union body");
4624 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4626 BalancedDelimiterTracker T(*this, tok::l_brace);
4627 if (T.consumeOpen())
4630 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4631 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4633 // While we still have something to read, read the declarations in the struct.
4634 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4635 Tok.isNot(tok::eof)) {
4636 // Each iteration of this loop reads one struct-declaration.
4638 // Check for extraneous top-level semicolon.
4639 if (Tok.is(tok::semi)) {
4640 ConsumeExtraSemi(InsideStruct, TagType);
4644 // Parse _Static_assert declaration.
4645 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4646 SourceLocation DeclEnd;
4647 ParseStaticAssertDeclaration(DeclEnd);
4651 if (Tok.is(tok::annot_pragma_pack)) {
4656 if (Tok.is(tok::annot_pragma_align)) {
4657 HandlePragmaAlign();
4661 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4662 // Result can be ignored, because it must be always empty.
4663 AccessSpecifier AS = AS_none;
4664 ParsedAttributes Attrs(AttrFactory);
4665 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4669 if (tok::isPragmaAnnotation(Tok.getKind())) {
4670 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4671 << DeclSpec::getSpecifierName(
4672 TagType, Actions.getASTContext().getPrintingPolicy());
4673 ConsumeAnnotationToken();
4677 if (!Tok.is(tok::at)) {
4678 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4679 // Install the declarator into the current TagDecl.
4681 Actions.ActOnField(getCurScope(), TagDecl,
4682 FD.D.getDeclSpec().getSourceRange().getBegin(),
4683 FD.D, FD.BitfieldSize);
4687 // Parse all the comma separated declarators.
4688 ParsingDeclSpec DS(*this);
4689 ParseStructDeclaration(DS, CFieldCallback);
4690 } else { // Handle @defs
4692 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4693 Diag(Tok, diag::err_unexpected_at);
4694 SkipUntil(tok::semi);
4698 ExpectAndConsume(tok::l_paren);
4699 if (!Tok.is(tok::identifier)) {
4700 Diag(Tok, diag::err_expected) << tok::identifier;
4701 SkipUntil(tok::semi);
4704 SmallVector<Decl *, 16> Fields;
4705 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4706 Tok.getIdentifierInfo(), Fields);
4708 ExpectAndConsume(tok::r_paren);
4711 if (TryConsumeToken(tok::semi))
4714 if (Tok.is(tok::r_brace)) {
4715 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4719 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4720 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4721 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4722 // If we stopped at a ';', eat it.
4723 TryConsumeToken(tok::semi);
4728 ParsedAttributes attrs(AttrFactory);
4729 // If attributes exist after struct contents, parse them.
4730 MaybeParseGNUAttributes(attrs);
4732 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
4734 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4735 T.getOpenLocation(), T.getCloseLocation(), attrs);
4737 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4740 /// ParseEnumSpecifier
4741 /// enum-specifier: [C99 6.7.2.2]
4742 /// 'enum' identifier[opt] '{' enumerator-list '}'
4743 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4744 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4745 /// '}' attributes[opt]
4746 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4748 /// 'enum' identifier
4749 /// [GNU] 'enum' attributes[opt] identifier
4751 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4752 /// [C++11] enum-head '{' enumerator-list ',' '}'
4754 /// enum-head: [C++11]
4755 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4756 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4757 /// identifier enum-base[opt]
4759 /// enum-key: [C++11]
4764 /// enum-base: [C++11]
4765 /// ':' type-specifier-seq
4767 /// [C++] elaborated-type-specifier:
4768 /// [C++] 'enum' nested-name-specifier[opt] identifier
4770 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4771 const ParsedTemplateInfo &TemplateInfo,
4772 AccessSpecifier AS, DeclSpecContext DSC) {
4773 // Parse the tag portion of this.
4774 if (Tok.is(tok::code_completion)) {
4775 // Code completion for an enum name.
4777 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4778 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4782 // If attributes exist after tag, parse them.
4783 ParsedAttributes attrs(AttrFactory);
4784 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4786 SourceLocation ScopedEnumKWLoc;
4787 bool IsScopedUsingClassTag = false;
4789 // In C++11, recognize 'enum class' and 'enum struct'.
4790 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
4791 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4792 : diag::ext_scoped_enum);
4793 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4794 ScopedEnumKWLoc = ConsumeToken();
4796 // Attributes are not allowed between these keywords. Diagnose,
4797 // but then just treat them like they appeared in the right place.
4798 ProhibitAttributes(attrs);
4800 // They are allowed afterwards, though.
4801 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4804 // C++11 [temp.explicit]p12:
4805 // The usual access controls do not apply to names used to specify
4806 // explicit instantiations.
4807 // We extend this to also cover explicit specializations. Note that
4808 // we don't suppress if this turns out to be an elaborated type
4810 bool shouldDelayDiagsInTag =
4811 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4812 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4813 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4815 // Determine whether this declaration is permitted to have an enum-base.
4816 AllowDefiningTypeSpec AllowEnumSpecifier =
4817 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
4818 bool CanBeOpaqueEnumDeclaration =
4819 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4820 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4821 getLangOpts().MicrosoftExt) &&
4822 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4823 CanBeOpaqueEnumDeclaration);
4825 CXXScopeSpec &SS = DS.getTypeSpecScope();
4826 if (getLangOpts().CPlusPlus) {
4827 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4828 ColonProtectionRAIIObject X(*this);
4831 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4832 /*ObjectHasErrors=*/false,
4833 /*EnteringContext=*/true))
4836 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4837 Diag(Tok, diag::err_expected) << tok::identifier;
4838 DS.SetTypeSpecError();
4839 if (Tok.isNot(tok::l_brace)) {
4840 // Has no name and is not a definition.
4841 // Skip the rest of this declarator, up until the comma or semicolon.
4842 SkipUntil(tok::comma, StopAtSemi);
4850 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4851 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4852 Tok.isNot(tok::colon)) {
4853 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4855 DS.SetTypeSpecError();
4856 // Skip the rest of this declarator, up until the comma or semicolon.
4857 SkipUntil(tok::comma, StopAtSemi);
4861 // If an identifier is present, consume and remember it.
4862 IdentifierInfo *Name = nullptr;
4863 SourceLocation NameLoc;
4864 if (Tok.is(tok::identifier)) {
4865 Name = Tok.getIdentifierInfo();
4866 NameLoc = ConsumeToken();
4869 if (!Name && ScopedEnumKWLoc.isValid()) {
4870 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4871 // declaration of a scoped enumeration.
4872 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4873 ScopedEnumKWLoc = SourceLocation();
4874 IsScopedUsingClassTag = false;
4877 // Okay, end the suppression area. We'll decide whether to emit the
4878 // diagnostics in a second.
4879 if (shouldDelayDiagsInTag)
4880 diagsFromTag.done();
4882 TypeResult BaseType;
4883 SourceRange BaseRange;
4885 bool CanBeBitfield =
4886 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
4888 // Parse the fixed underlying type.
4889 if (Tok.is(tok::colon)) {
4890 // This might be an enum-base or part of some unrelated enclosing context.
4892 // 'enum E : base' is permitted in two circumstances:
4894 // 1) As a defining-type-specifier, when followed by '{'.
4895 // 2) As the sole constituent of a complete declaration -- when DS is empty
4896 // and the next token is ';'.
4898 // The restriction to defining-type-specifiers is important to allow parsing
4899 // a ? new enum E : int{}
4900 // _Generic(a, enum E : int{})
4903 // One additional consideration applies:
4905 // C++ [dcl.enum]p1:
4906 // A ':' following "enum nested-name-specifier[opt] identifier" within
4907 // the decl-specifier-seq of a member-declaration is parsed as part of
4910 // Other language modes supporting enumerations with fixed underlying types
4911 // do not have clear rules on this, so we disambiguate to determine whether
4912 // the tokens form a bit-field width or an enum-base.
4914 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4915 // Outside C++11, do not interpret the tokens as an enum-base if they do
4916 // not make sense as one. In C++11, it's an error if this happens.
4917 if (getLangOpts().CPlusPlus11)
4918 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4919 } else if (CanHaveEnumBase || !ColonIsSacred) {
4920 SourceLocation ColonLoc = ConsumeToken();
4922 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4923 // because under -fms-extensions,
4925 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4926 DeclSpec DS(AttrFactory);
4927 // enum-base is not assumed to be a type and therefore requires the
4928 // typename keyword [p0634r3].
4929 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
4930 DeclSpecContext::DSC_type_specifier);
4931 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4932 DeclaratorContext::TypeName);
4933 BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4935 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4937 if (!getLangOpts().ObjC) {
4938 if (getLangOpts().CPlusPlus11)
4939 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4941 else if (getLangOpts().CPlusPlus)
4942 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4944 else if (getLangOpts().MicrosoftExt)
4945 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4948 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4954 // There are four options here. If we have 'friend enum foo;' then this is a
4955 // friend declaration, and cannot have an accompanying definition. If we have
4956 // 'enum foo;', then this is a forward declaration. If we have
4957 // 'enum foo {...' then this is a definition. Otherwise we have something
4958 // like 'enum foo xyz', a reference.
4960 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4961 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4962 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4964 Sema::TagUseKind TUK;
4965 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4966 TUK = Sema::TUK_Reference;
4967 else if (Tok.is(tok::l_brace)) {
4968 if (DS.isFriendSpecified()) {
4969 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4970 << SourceRange(DS.getFriendSpecLoc());
4972 SkipUntil(tok::r_brace, StopAtSemi);
4973 // Discard any other definition-only pieces.
4975 ScopedEnumKWLoc = SourceLocation();
4976 IsScopedUsingClassTag = false;
4977 BaseType = TypeResult();
4978 TUK = Sema::TUK_Friend;
4980 TUK = Sema::TUK_Definition;
4982 } else if (!isTypeSpecifier(DSC) &&
4983 (Tok.is(tok::semi) ||
4984 (Tok.isAtStartOfLine() &&
4985 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4986 // An opaque-enum-declaration is required to be standalone (no preceding or
4987 // following tokens in the declaration). Sema enforces this separately by
4988 // diagnosing anything else in the DeclSpec.
4989 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4990 if (Tok.isNot(tok::semi)) {
4991 // A semicolon was missing after this declaration. Diagnose and recover.
4992 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4993 PP.EnterToken(Tok, /*IsReinject=*/true);
4994 Tok.setKind(tok::semi);
4997 TUK = Sema::TUK_Reference;
5000 bool IsElaboratedTypeSpecifier =
5001 TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
5003 // If this is an elaborated type specifier nested in a larger declaration,
5004 // and we delayed diagnostics before, just merge them into the current pool.
5005 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
5006 diagsFromTag.redelay();
5009 MultiTemplateParamsArg TParams;
5010 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
5011 TUK != Sema::TUK_Reference) {
5012 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5013 // Skip the rest of this declarator, up until the comma or semicolon.
5014 Diag(Tok, diag::err_enum_template);
5015 SkipUntil(tok::comma, StopAtSemi);
5019 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
5020 // Enumerations can't be explicitly instantiated.
5021 DS.SetTypeSpecError();
5022 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5026 assert(TemplateInfo.TemplateParams && "no template parameters");
5027 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5028 TemplateInfo.TemplateParams->size());
5029 SS.setTemplateParamLists(TParams);
5032 if (!Name && TUK != Sema::TUK_Definition) {
5033 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5035 DS.SetTypeSpecError();
5036 // Skip the rest of this declarator, up until the comma or semicolon.
5037 SkipUntil(tok::comma, StopAtSemi);
5041 // An elaborated-type-specifier has a much more constrained grammar:
5043 // 'enum' nested-name-specifier[opt] identifier
5045 // If we parsed any other bits, reject them now.
5047 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5048 // or opaque-enum-declaration anywhere.
5049 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5050 !getLangOpts().ObjC) {
5051 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5052 diag::err_keyword_not_allowed,
5053 /*DiagnoseEmptyAttrs=*/true);
5054 if (BaseType.isUsable())
5055 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5056 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5057 else if (ScopedEnumKWLoc.isValid())
5058 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5059 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5062 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5064 Sema::SkipBodyInfo SkipBody;
5065 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
5066 NextToken().is(tok::identifier))
5067 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5068 NextToken().getIdentifierInfo(),
5069 NextToken().getLocation());
5072 bool IsDependent = false;
5073 const char *PrevSpec = nullptr;
5076 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5077 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5078 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5079 IsScopedUsingClassTag,
5080 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5081 DSC == DeclSpecContext::DSC_template_param ||
5082 DSC == DeclSpecContext::DSC_template_type_arg,
5083 OffsetOfState, &SkipBody).get();
5085 if (SkipBody.ShouldSkip) {
5086 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
5088 BalancedDelimiterTracker T(*this, tok::l_brace);
5092 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5093 NameLoc.isValid() ? NameLoc : StartLoc,
5094 PrevSpec, DiagID, TagDecl, Owned,
5095 Actions.getASTContext().getPrintingPolicy()))
5096 Diag(StartLoc, DiagID) << PrevSpec;
5101 // This enum has a dependent nested-name-specifier. Handle it as a
5104 DS.SetTypeSpecError();
5105 Diag(Tok, diag::err_expected_type_name_after_typename);
5109 TypeResult Type = Actions.ActOnDependentTag(
5110 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5111 if (Type.isInvalid()) {
5112 DS.SetTypeSpecError();
5116 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5117 NameLoc.isValid() ? NameLoc : StartLoc,
5118 PrevSpec, DiagID, Type.get(),
5119 Actions.getASTContext().getPrintingPolicy()))
5120 Diag(StartLoc, DiagID) << PrevSpec;
5126 // The action failed to produce an enumeration tag. If this is a
5127 // definition, consume the entire definition.
5128 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5130 SkipUntil(tok::r_brace, StopAtSemi);
5133 DS.SetTypeSpecError();
5137 if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5138 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5139 ParseEnumBody(StartLoc, D);
5140 if (SkipBody.CheckSameAsPrevious &&
5141 !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5142 DS.SetTypeSpecError();
5147 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5148 NameLoc.isValid() ? NameLoc : StartLoc,
5149 PrevSpec, DiagID, TagDecl, Owned,
5150 Actions.getASTContext().getPrintingPolicy()))
5151 Diag(StartLoc, DiagID) << PrevSpec;
5154 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
5155 /// enumerator-list:
5157 /// enumerator-list ',' enumerator
5159 /// enumeration-constant attributes[opt]
5160 /// enumeration-constant attributes[opt] '=' constant-expression
5161 /// enumeration-constant:
5164 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5165 // Enter the scope of the enum body and start the definition.
5166 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5167 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
5169 BalancedDelimiterTracker T(*this, tok::l_brace);
5172 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5173 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5174 Diag(Tok, diag::err_empty_enum);
5176 SmallVector<Decl *, 32> EnumConstantDecls;
5177 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5179 Decl *LastEnumConstDecl = nullptr;
5181 // Parse the enumerator-list.
5182 while (Tok.isNot(tok::r_brace)) {
5183 // Parse enumerator. If failed, try skipping till the start of the next
5184 // enumerator definition.
5185 if (Tok.isNot(tok::identifier)) {
5186 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5187 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5188 TryConsumeToken(tok::comma))
5192 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5193 SourceLocation IdentLoc = ConsumeToken();
5195 // If attributes exist after the enumerator, parse them.
5196 ParsedAttributes attrs(AttrFactory);
5197 MaybeParseGNUAttributes(attrs);
5198 if (isAllowedCXX11AttributeSpecifier()) {
5199 if (getLangOpts().CPlusPlus)
5200 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
5201 ? diag::warn_cxx14_compat_ns_enum_attribute
5202 : diag::ext_ns_enum_attribute)
5203 << 1 /*enumerator*/;
5204 ParseCXX11Attributes(attrs);
5207 SourceLocation EqualLoc;
5208 ExprResult AssignedVal;
5209 EnumAvailabilityDiags.emplace_back(*this);
5211 EnterExpressionEvaluationContext ConstantEvaluated(
5212 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5213 if (TryConsumeToken(tok::equal, EqualLoc)) {
5214 AssignedVal = ParseConstantExpressionInExprEvalContext();
5215 if (AssignedVal.isInvalid())
5216 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5219 // Install the enumerator constant into EnumDecl.
5220 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5221 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5222 EqualLoc, AssignedVal.get());
5223 EnumAvailabilityDiags.back().done();
5225 EnumConstantDecls.push_back(EnumConstDecl);
5226 LastEnumConstDecl = EnumConstDecl;
5228 if (Tok.is(tok::identifier)) {
5229 // We're missing a comma between enumerators.
5230 SourceLocation Loc = getEndOfPreviousToken();
5231 Diag(Loc, diag::err_enumerator_list_missing_comma)
5232 << FixItHint::CreateInsertion(Loc, ", ");
5236 // Emumerator definition must be finished, only comma or r_brace are
5238 SourceLocation CommaLoc;
5239 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5240 if (EqualLoc.isValid())
5241 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5244 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5245 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5246 if (TryConsumeToken(tok::comma, CommaLoc))
5253 // If comma is followed by r_brace, emit appropriate warning.
5254 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5255 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
5256 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5257 diag::ext_enumerator_list_comma_cxx :
5258 diag::ext_enumerator_list_comma_c)
5259 << FixItHint::CreateRemoval(CommaLoc);
5260 else if (getLangOpts().CPlusPlus11)
5261 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5262 << FixItHint::CreateRemoval(CommaLoc);
5270 // If attributes exist after the identifier list, parse them.
5271 ParsedAttributes attrs(AttrFactory);
5272 MaybeParseGNUAttributes(attrs);
5274 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5275 getCurScope(), attrs);
5277 // Now handle enum constant availability diagnostics.
5278 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5279 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5280 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
5281 EnumAvailabilityDiags[i].redelay();
5282 PD.complete(EnumConstantDecls[i]);
5286 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5288 // The next token must be valid after an enum definition. If not, a ';'
5289 // was probably forgotten.
5290 bool CanBeBitfield = getCurScope()->isClassScope();
5291 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5292 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5293 // Push this token back into the preprocessor and change our current token
5294 // to ';' so that the rest of the code recovers as though there were an
5295 // ';' after the definition.
5296 PP.EnterToken(Tok, /*IsReinject=*/true);
5297 Tok.setKind(tok::semi);
5301 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5302 /// is definitely a type-specifier. Return false if it isn't part of a type
5303 /// specifier or if we're not sure.
5304 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5305 switch (Tok.getKind()) {
5306 default: return false;
5310 case tok::kw___int64:
5311 case tok::kw___int128:
5312 case tok::kw_signed:
5313 case tok::kw_unsigned:
5314 case tok::kw__Complex:
5315 case tok::kw__Imaginary:
5318 case tok::kw_wchar_t:
5319 case tok::kw_char8_t:
5320 case tok::kw_char16_t:
5321 case tok::kw_char32_t:
5323 case tok::kw__ExtInt:
5324 case tok::kw__BitInt:
5325 case tok::kw___bf16:
5328 case tok::kw_double:
5329 case tok::kw__Accum:
5330 case tok::kw__Fract:
5331 case tok::kw__Float16:
5332 case tok::kw___float128:
5333 case tok::kw___ibm128:
5336 case tok::kw__Decimal32:
5337 case tok::kw__Decimal64:
5338 case tok::kw__Decimal128:
5339 case tok::kw___vector:
5340 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5341 #include "clang/Basic/OpenCLImageTypes.def"
5343 // struct-or-union-specifier (C99) or class-specifier (C++)
5345 case tok::kw_struct:
5346 case tok::kw___interface:
5352 case tok::annot_typename:
5357 /// isTypeSpecifierQualifier - Return true if the current token could be the
5358 /// start of a specifier-qualifier-list.
5359 bool Parser::isTypeSpecifierQualifier() {
5360 switch (Tok.getKind()) {
5361 default: return false;
5363 case tok::identifier: // foo::bar
5364 if (TryAltiVecVectorToken())
5367 case tok::kw_typename: // typename T::type
5368 // Annotate typenames and C++ scope specifiers. If we get one, just
5369 // recurse to handle whatever we get.
5370 if (TryAnnotateTypeOrScopeToken())
5372 if (Tok.is(tok::identifier))
5374 return isTypeSpecifierQualifier();
5376 case tok::coloncolon: // ::foo::bar
5377 if (NextToken().is(tok::kw_new) || // ::new
5378 NextToken().is(tok::kw_delete)) // ::delete
5381 if (TryAnnotateTypeOrScopeToken())
5383 return isTypeSpecifierQualifier();
5385 // GNU attributes support.
5386 case tok::kw___attribute:
5387 // C2x/GNU typeof support.
5388 case tok::kw_typeof:
5389 case tok::kw_typeof_unqual:
5394 case tok::kw___int64:
5395 case tok::kw___int128:
5396 case tok::kw_signed:
5397 case tok::kw_unsigned:
5398 case tok::kw__Complex:
5399 case tok::kw__Imaginary:
5402 case tok::kw_wchar_t:
5403 case tok::kw_char8_t:
5404 case tok::kw_char16_t:
5405 case tok::kw_char32_t:
5407 case tok::kw__ExtInt:
5408 case tok::kw__BitInt:
5410 case tok::kw___bf16:
5412 case tok::kw_double:
5413 case tok::kw__Accum:
5414 case tok::kw__Fract:
5415 case tok::kw__Float16:
5416 case tok::kw___float128:
5417 case tok::kw___ibm128:
5420 case tok::kw__Decimal32:
5421 case tok::kw__Decimal64:
5422 case tok::kw__Decimal128:
5423 case tok::kw___vector:
5424 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5425 #include "clang/Basic/OpenCLImageTypes.def"
5427 // struct-or-union-specifier (C99) or class-specifier (C++)
5429 case tok::kw_struct:
5430 case tok::kw___interface:
5437 case tok::kw_volatile:
5438 case tok::kw_restrict:
5441 // Debugger support.
5442 case tok::kw___unknown_anytype:
5445 case tok::annot_typename:
5448 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5450 return getLangOpts().ObjC;
5452 case tok::kw___cdecl:
5453 case tok::kw___stdcall:
5454 case tok::kw___fastcall:
5455 case tok::kw___thiscall:
5456 case tok::kw___regcall:
5457 case tok::kw___vectorcall:
5459 case tok::kw___ptr64:
5460 case tok::kw___ptr32:
5461 case tok::kw___pascal:
5462 case tok::kw___unaligned:
5464 case tok::kw__Nonnull:
5465 case tok::kw__Nullable:
5466 case tok::kw__Nullable_result:
5467 case tok::kw__Null_unspecified:
5469 case tok::kw___kindof:
5471 case tok::kw___private:
5472 case tok::kw___local:
5473 case tok::kw___global:
5474 case tok::kw___constant:
5475 case tok::kw___generic:
5476 case tok::kw___read_only:
5477 case tok::kw___read_write:
5478 case tok::kw___write_only:
5479 case tok::kw___funcref:
5480 case tok::kw_groupshared:
5483 case tok::kw_private:
5484 return getLangOpts().OpenCL;
5487 case tok::kw__Atomic:
5492 Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5493 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5495 // Parse a top-level-stmt.
5496 Parser::StmtVector Stmts;
5497 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5498 Actions.PushFunctionScope();
5499 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5500 Actions.PopFunctionScopeInfo();
5504 SmallVector<Decl *, 2> DeclsInGroup;
5505 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(R.get()));
5507 if (Tok.is(tok::annot_repl_input_end) &&
5508 Tok.getAnnotationValue() != nullptr) {
5509 ConsumeAnnotationToken();
5510 cast<TopLevelStmtDecl>(DeclsInGroup.back())->setSemiMissing();
5513 // Currently happens for things like -fms-extensions and use `__if_exists`.
5514 for (Stmt *S : Stmts)
5515 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(S));
5517 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5520 /// isDeclarationSpecifier() - Return true if the current token is part of a
5521 /// declaration specifier.
5523 /// \param AllowImplicitTypename whether this is a context where T::type [T
5524 /// dependent] can appear.
5525 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5526 /// this check is to disambiguate between an expression and a declaration.
5527 bool Parser::isDeclarationSpecifier(
5528 ImplicitTypenameContext AllowImplicitTypename,
5529 bool DisambiguatingWithExpression) {
5530 switch (Tok.getKind()) {
5531 default: return false;
5533 // OpenCL 2.0 and later define this keyword.
5535 return getLangOpts().OpenCL &&
5536 getLangOpts().getOpenCLCompatibleVersion() >= 200;
5538 case tok::identifier: // foo::bar
5539 // Unfortunate hack to support "Class.factoryMethod" notation.
5540 if (getLangOpts().ObjC && NextToken().is(tok::period))
5542 if (TryAltiVecVectorToken())
5545 case tok::kw_decltype: // decltype(T())::type
5546 case tok::kw_typename: // typename T::type
5547 // Annotate typenames and C++ scope specifiers. If we get one, just
5548 // recurse to handle whatever we get.
5549 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5551 if (TryAnnotateTypeConstraint())
5553 if (Tok.is(tok::identifier))
5556 // If we're in Objective-C and we have an Objective-C class type followed
5557 // by an identifier and then either ':' or ']', in a place where an
5558 // expression is permitted, then this is probably a class message send
5559 // missing the initial '['. In this case, we won't consider this to be
5560 // the start of a declaration.
5561 if (DisambiguatingWithExpression &&
5562 isStartOfObjCClassMessageMissingOpenBracket())
5565 return isDeclarationSpecifier(AllowImplicitTypename);
5567 case tok::coloncolon: // ::foo::bar
5568 if (!getLangOpts().CPlusPlus)
5570 if (NextToken().is(tok::kw_new) || // ::new
5571 NextToken().is(tok::kw_delete)) // ::delete
5574 // Annotate typenames and C++ scope specifiers. If we get one, just
5575 // recurse to handle whatever we get.
5576 if (TryAnnotateTypeOrScopeToken())
5578 return isDeclarationSpecifier(ImplicitTypenameContext::No);
5580 // storage-class-specifier
5581 case tok::kw_typedef:
5582 case tok::kw_extern:
5583 case tok::kw___private_extern__:
5584 case tok::kw_static:
5586 case tok::kw___auto_type:
5587 case tok::kw_register:
5588 case tok::kw___thread:
5589 case tok::kw_thread_local:
5590 case tok::kw__Thread_local:
5593 case tok::kw___module_private__:
5596 case tok::kw___unknown_anytype:
5601 case tok::kw___int64:
5602 case tok::kw___int128:
5603 case tok::kw_signed:
5604 case tok::kw_unsigned:
5605 case tok::kw__Complex:
5606 case tok::kw__Imaginary:
5609 case tok::kw_wchar_t:
5610 case tok::kw_char8_t:
5611 case tok::kw_char16_t:
5612 case tok::kw_char32_t:
5615 case tok::kw__ExtInt:
5616 case tok::kw__BitInt:
5618 case tok::kw___bf16:
5620 case tok::kw_double:
5621 case tok::kw__Accum:
5622 case tok::kw__Fract:
5623 case tok::kw__Float16:
5624 case tok::kw___float128:
5625 case tok::kw___ibm128:
5628 case tok::kw__Decimal32:
5629 case tok::kw__Decimal64:
5630 case tok::kw__Decimal128:
5631 case tok::kw___vector:
5633 // struct-or-union-specifier (C99) or class-specifier (C++)
5635 case tok::kw_struct:
5637 case tok::kw___interface:
5643 case tok::kw_volatile:
5644 case tok::kw_restrict:
5647 // function-specifier
5648 case tok::kw_inline:
5649 case tok::kw_virtual:
5650 case tok::kw_explicit:
5651 case tok::kw__Noreturn:
5653 // alignment-specifier
5654 case tok::kw__Alignas:
5657 case tok::kw_friend:
5659 // static_assert-declaration
5660 case tok::kw_static_assert:
5661 case tok::kw__Static_assert:
5663 // C2x/GNU typeof support.
5664 case tok::kw_typeof:
5665 case tok::kw_typeof_unqual:
5668 case tok::kw___attribute:
5670 // C++11 decltype and constexpr.
5671 case tok::annot_decltype:
5672 case tok::kw_constexpr:
5674 // C++20 consteval and constinit.
5675 case tok::kw_consteval:
5676 case tok::kw_constinit:
5679 case tok::kw__Atomic:
5682 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5684 return getLangOpts().ObjC;
5687 case tok::annot_typename:
5688 return !DisambiguatingWithExpression ||
5689 !isStartOfObjCClassMessageMissingOpenBracket();
5691 // placeholder-type-specifier
5692 case tok::annot_template_id: {
5693 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5694 if (TemplateId->hasInvalidName())
5696 // FIXME: What about type templates that have only been annotated as
5697 // annot_template_id, not as annot_typename?
5698 return isTypeConstraintAnnotation() &&
5699 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5702 case tok::annot_cxxscope: {
5703 TemplateIdAnnotation *TemplateId =
5704 NextToken().is(tok::annot_template_id)
5705 ? takeTemplateIdAnnotation(NextToken())
5707 if (TemplateId && TemplateId->hasInvalidName())
5709 // FIXME: What about type templates that have only been annotated as
5710 // annot_template_id, not as annot_typename?
5711 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5713 return isTypeConstraintAnnotation() &&
5714 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5717 case tok::kw___declspec:
5718 case tok::kw___cdecl:
5719 case tok::kw___stdcall:
5720 case tok::kw___fastcall:
5721 case tok::kw___thiscall:
5722 case tok::kw___regcall:
5723 case tok::kw___vectorcall:
5725 case tok::kw___sptr:
5726 case tok::kw___uptr:
5727 case tok::kw___ptr64:
5728 case tok::kw___ptr32:
5729 case tok::kw___forceinline:
5730 case tok::kw___pascal:
5731 case tok::kw___unaligned:
5733 case tok::kw__Nonnull:
5734 case tok::kw__Nullable:
5735 case tok::kw__Nullable_result:
5736 case tok::kw__Null_unspecified:
5738 case tok::kw___kindof:
5740 case tok::kw___private:
5741 case tok::kw___local:
5742 case tok::kw___global:
5743 case tok::kw___constant:
5744 case tok::kw___generic:
5745 case tok::kw___read_only:
5746 case tok::kw___read_write:
5747 case tok::kw___write_only:
5748 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5749 #include "clang/Basic/OpenCLImageTypes.def"
5751 case tok::kw___funcref:
5752 case tok::kw_groupshared:
5755 case tok::kw_private:
5756 return getLangOpts().OpenCL;
5760 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
5761 DeclSpec::FriendSpecified IsFriend,
5762 const ParsedTemplateInfo *TemplateInfo) {
5763 TentativeParsingAction TPA(*this);
5765 // Parse the C++ scope specifier.
5767 if (TemplateInfo && TemplateInfo->TemplateParams)
5768 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
5770 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5771 /*ObjectHasErrors=*/false,
5772 /*EnteringContext=*/true)) {
5777 // Parse the constructor name.
5778 if (Tok.is(tok::identifier)) {
5779 // We already know that we have a constructor name; just consume
5782 } else if (Tok.is(tok::annot_template_id)) {
5783 ConsumeAnnotationToken();
5789 // There may be attributes here, appertaining to the constructor name or type
5790 // we just stepped past.
5791 SkipCXX11Attributes();
5793 // Current class name must be followed by a left parenthesis.
5794 if (Tok.isNot(tok::l_paren)) {
5800 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5801 // that we have a constructor.
5802 if (Tok.is(tok::r_paren) ||
5803 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5808 // A C++11 attribute here signals that we have a constructor, and is an
5809 // attribute on the first constructor parameter.
5810 if (getLangOpts().CPlusPlus11 &&
5811 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5812 /*OuterMightBeMessageSend*/ true)) {
5817 // If we need to, enter the specified scope.
5818 DeclaratorScopeObj DeclScopeObj(*this, SS);
5819 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5820 DeclScopeObj.EnterDeclaratorScope();
5822 // Optionally skip Microsoft attributes.
5823 ParsedAttributes Attrs(AttrFactory);
5824 MaybeParseMicrosoftAttributes(Attrs);
5826 // Check whether the next token(s) are part of a declaration
5827 // specifier, in which case we have the start of a parameter and,
5828 // therefore, we know that this is a constructor.
5829 // Due to an ambiguity with implicit typename, the above is not enough.
5830 // Additionally, check to see if we are a friend.
5831 // If we parsed a scope specifier as well as friend,
5832 // we might be parsing a friend constructor.
5833 bool IsConstructor = false;
5834 if (isDeclarationSpecifier(IsFriend && !SS.isSet()
5835 ? ImplicitTypenameContext::No
5836 : ImplicitTypenameContext::Yes))
5837 IsConstructor = true;
5838 else if (Tok.is(tok::identifier) ||
5839 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5840 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5841 // This might be a parenthesized member name, but is more likely to
5842 // be a constructor declaration with an invalid argument type. Keep
5844 if (Tok.is(tok::annot_cxxscope))
5845 ConsumeAnnotationToken();
5848 // If this is not a constructor, we must be parsing a declarator,
5849 // which must have one of the following syntactic forms (see the
5850 // grammar extract at the start of ParseDirectDeclarator):
5851 switch (Tok.getKind()) {
5856 // C(X [ [attribute]]);
5857 case tok::coloncolon:
5860 // Assume this isn't a constructor, rather than assuming it's a
5861 // constructor with an unnamed parameter of an ill-formed type.
5867 // Skip past the right-paren and any following attributes to get to
5868 // the function body or trailing-return-type.
5870 SkipCXX11Attributes();
5872 if (DeductionGuide) {
5873 // C(X) -> ... is a deduction guide.
5874 IsConstructor = Tok.is(tok::arrow);
5877 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5878 // Assume these were meant to be constructors:
5879 // C(X) : (the name of a bit-field cannot be parenthesized).
5880 // C(X) try (this is otherwise ill-formed).
5881 IsConstructor = true;
5883 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5884 // If we have a constructor name within the class definition,
5885 // assume these were meant to be constructors:
5888 // ... because otherwise we would be declaring a non-static data
5889 // member that is ill-formed because it's of the same type as its
5890 // surrounding class.
5892 // FIXME: We can actually do this whether or not the name is qualified,
5893 // because if it is qualified in this context it must be being used as
5894 // a constructor name.
5895 // currently, so we're somewhat conservative here.
5896 IsConstructor = IsUnqualified;
5901 IsConstructor = true;
5907 return IsConstructor;
5910 /// ParseTypeQualifierListOpt
5911 /// type-qualifier-list: [C99 6.7.5]
5913 /// [vendor] attributes
5914 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5915 /// type-qualifier-list type-qualifier
5916 /// [vendor] type-qualifier-list attributes
5917 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5918 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5919 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5920 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5921 /// AttrRequirements bitmask values.
5922 void Parser::ParseTypeQualifierListOpt(
5923 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5924 bool IdentifierRequired,
5925 std::optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5926 if ((AttrReqs & AR_CXX11AttributesParsed) &&
5927 isAllowedCXX11AttributeSpecifier()) {
5928 ParsedAttributes Attrs(AttrFactory);
5929 ParseCXX11Attributes(Attrs);
5930 DS.takeAttributesFrom(Attrs);
5933 SourceLocation EndLoc;
5936 bool isInvalid = false;
5937 const char *PrevSpec = nullptr;
5938 unsigned DiagID = 0;
5939 SourceLocation Loc = Tok.getLocation();
5941 switch (Tok.getKind()) {
5942 case tok::code_completion:
5944 if (CodeCompletionHandler)
5945 (*CodeCompletionHandler)();
5947 Actions.CodeCompleteTypeQualifiers(DS);
5951 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5954 case tok::kw_volatile:
5955 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5958 case tok::kw_restrict:
5959 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5962 case tok::kw__Atomic:
5964 goto DoneWithTypeQuals;
5965 if (!getLangOpts().C11)
5966 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5967 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5971 // OpenCL qualifiers:
5972 case tok::kw_private:
5973 if (!getLangOpts().OpenCL)
5974 goto DoneWithTypeQuals;
5976 case tok::kw___private:
5977 case tok::kw___global:
5978 case tok::kw___local:
5979 case tok::kw___constant:
5980 case tok::kw___generic:
5981 case tok::kw___read_only:
5982 case tok::kw___write_only:
5983 case tok::kw___read_write:
5984 ParseOpenCLQualifiers(DS.getAttributes());
5987 case tok::kw_groupshared:
5988 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
5989 ParseHLSLQualifiers(DS.getAttributes());
5992 case tok::kw___unaligned:
5993 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5996 case tok::kw___uptr:
5997 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5998 // with the MS modifier keyword.
5999 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6000 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6001 if (TryKeywordIdentFallback(false))
6005 case tok::kw___sptr:
6007 case tok::kw___ptr64:
6008 case tok::kw___ptr32:
6009 case tok::kw___cdecl:
6010 case tok::kw___stdcall:
6011 case tok::kw___fastcall:
6012 case tok::kw___thiscall:
6013 case tok::kw___regcall:
6014 case tok::kw___vectorcall:
6015 if (AttrReqs & AR_DeclspecAttributesParsed) {
6016 ParseMicrosoftTypeAttributes(DS.getAttributes());
6019 goto DoneWithTypeQuals;
6021 case tok::kw___funcref:
6022 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6024 goto DoneWithTypeQuals;
6026 case tok::kw___pascal:
6027 if (AttrReqs & AR_VendorAttributesParsed) {
6028 ParseBorlandTypeAttributes(DS.getAttributes());
6031 goto DoneWithTypeQuals;
6033 // Nullability type specifiers.
6034 case tok::kw__Nonnull:
6035 case tok::kw__Nullable:
6036 case tok::kw__Nullable_result:
6037 case tok::kw__Null_unspecified:
6038 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6041 // Objective-C 'kindof' types.
6042 case tok::kw___kindof:
6043 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
6044 nullptr, 0, tok::kw___kindof);
6045 (void)ConsumeToken();
6048 case tok::kw___attribute:
6049 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6050 // When GNU attributes are expressly forbidden, diagnose their usage.
6051 Diag(Tok, diag::err_attributes_not_allowed);
6053 // Parse the attributes even if they are rejected to ensure that error
6054 // recovery is graceful.
6055 if (AttrReqs & AR_GNUAttributesParsed ||
6056 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6057 ParseGNUAttributes(DS.getAttributes());
6058 continue; // do *not* consume the next token!
6060 // otherwise, FALL THROUGH!
6064 // If this is not a type-qualifier token, we're done reading type
6065 // qualifiers. First verify that DeclSpec's are consistent.
6066 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6067 if (EndLoc.isValid())
6068 DS.SetRangeEnd(EndLoc);
6072 // If the specifier combination wasn't legal, issue a diagnostic.
6074 assert(PrevSpec && "Method did not return previous specifier!");
6075 Diag(Tok, DiagID) << PrevSpec;
6077 EndLoc = ConsumeToken();
6081 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
6082 void Parser::ParseDeclarator(Declarator &D) {
6083 /// This implements the 'declarator' production in the C grammar, then checks
6084 /// for well-formedness and issues diagnostics.
6085 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6086 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6090 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6091 DeclaratorContext TheContext) {
6092 if (Kind == tok::star || Kind == tok::caret)
6095 // OpenCL 2.0 and later define this keyword.
6096 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6097 Lang.getOpenCLCompatibleVersion() >= 200)
6100 if (!Lang.CPlusPlus)
6103 if (Kind == tok::amp)
6106 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6107 // But we must not parse them in conversion-type-ids and new-type-ids, since
6108 // those can be legitimately followed by a && operator.
6109 // (The same thing can in theory happen after a trailing-return-type, but
6110 // since those are a C++11 feature, there is no rejects-valid issue there.)
6111 if (Kind == tok::ampamp)
6112 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6113 TheContext != DeclaratorContext::CXXNew);
6118 // Indicates whether the given declarator is a pipe declarator.
6119 static bool isPipeDeclarator(const Declarator &D) {
6120 const unsigned NumTypes = D.getNumTypeObjects();
6122 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6123 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
6129 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
6130 /// is parsed by the function passed to it. Pass null, and the direct-declarator
6131 /// isn't parsed at all, making this function effectively parse the C++
6132 /// ptr-operator production.
6134 /// If the grammar of this construct is extended, matching changes must also be
6135 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
6136 /// isConstructorDeclarator.
6138 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
6139 /// [C] pointer[opt] direct-declarator
6140 /// [C++] direct-declarator
6141 /// [C++] ptr-operator declarator
6143 /// pointer: [C99 6.7.5]
6144 /// '*' type-qualifier-list[opt]
6145 /// '*' type-qualifier-list[opt] pointer
6148 /// '*' cv-qualifier-seq[opt]
6151 /// [GNU] '&' restrict[opt] attributes[opt]
6152 /// [GNU?] '&&' restrict[opt] attributes[opt]
6153 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
6154 void Parser::ParseDeclaratorInternal(Declarator &D,
6155 DirectDeclParseFunction DirectDeclParser) {
6156 if (Diags.hasAllExtensionsSilenced())
6159 // C++ member pointers start with a '::' or a nested-name.
6160 // Member pointers get special handling, since there's no place for the
6161 // scope spec in the generic path below.
6162 if (getLangOpts().CPlusPlus &&
6163 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
6164 (Tok.is(tok::identifier) &&
6165 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6166 Tok.is(tok::annot_cxxscope))) {
6167 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6168 D.getContext() == DeclaratorContext::Member;
6170 SS.setTemplateParamLists(D.getTemplateParameterLists());
6171 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6172 /*ObjectHasErrors=*/false, EnteringContext);
6174 if (SS.isNotEmpty()) {
6175 if (Tok.isNot(tok::star)) {
6176 // The scope spec really belongs to the direct-declarator.
6177 if (D.mayHaveIdentifier())
6178 D.getCXXScopeSpec() = SS;
6180 AnnotateScopeToken(SS, true);
6182 if (DirectDeclParser)
6183 (this->*DirectDeclParser)(D);
6188 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6189 CompoundToken::MemberPtr);
6192 SourceLocation StarLoc = ConsumeToken();
6193 D.SetRangeEnd(StarLoc);
6194 DeclSpec DS(AttrFactory);
6195 ParseTypeQualifierListOpt(DS);
6196 D.ExtendWithDeclSpec(DS);
6198 // Recurse to parse whatever is left.
6199 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6200 ParseDeclaratorInternal(D, DirectDeclParser);
6203 // Sema will have to catch (syntactically invalid) pointers into global
6204 // scope. It has to catch pointers into namespace scope anyway.
6205 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
6206 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6207 std::move(DS.getAttributes()),
6208 /* Don't replace range end. */ SourceLocation());
6213 tok::TokenKind Kind = Tok.getKind();
6215 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6216 DeclSpec DS(AttrFactory);
6217 ParseTypeQualifierListOpt(DS);
6220 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
6221 std::move(DS.getAttributes()), SourceLocation());
6224 // Not a pointer, C++ reference, or block.
6225 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6226 if (DirectDeclParser)
6227 (this->*DirectDeclParser)(D);
6231 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6232 // '&&' -> rvalue reference
6233 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6236 if (Kind == tok::star || Kind == tok::caret) {
6238 DeclSpec DS(AttrFactory);
6240 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6241 // C++11 attributes are allowed.
6242 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6243 ((D.getContext() != DeclaratorContext::CXXNew)
6244 ? AR_GNUAttributesParsed
6245 : AR_GNUAttributesParsedAndRejected);
6246 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
6247 D.ExtendWithDeclSpec(DS);
6249 // Recursively parse the declarator.
6250 Actions.runWithSufficientStackSpace(
6251 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6252 if (Kind == tok::star)
6253 // Remember that we parsed a pointer type, and remember the type-quals.
6254 D.AddTypeInfo(DeclaratorChunk::getPointer(
6255 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
6256 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
6257 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
6258 std::move(DS.getAttributes()), SourceLocation());
6260 // Remember that we parsed a Block type, and remember the type-quals.
6262 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
6263 std::move(DS.getAttributes()), SourceLocation());
6266 DeclSpec DS(AttrFactory);
6268 // Complain about rvalue references in C++03, but then go on and build
6270 if (Kind == tok::ampamp)
6271 Diag(Loc, getLangOpts().CPlusPlus11 ?
6272 diag::warn_cxx98_compat_rvalue_reference :
6273 diag::ext_rvalue_reference);
6275 // GNU-style and C++11 attributes are allowed here, as is restrict.
6276 ParseTypeQualifierListOpt(DS);
6277 D.ExtendWithDeclSpec(DS);
6279 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6280 // cv-qualifiers are introduced through the use of a typedef or of a
6281 // template type argument, in which case the cv-qualifiers are ignored.
6282 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
6283 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
6284 Diag(DS.getConstSpecLoc(),
6285 diag::err_invalid_reference_qualifier_application) << "const";
6286 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
6287 Diag(DS.getVolatileSpecLoc(),
6288 diag::err_invalid_reference_qualifier_application) << "volatile";
6289 // 'restrict' is permitted as an extension.
6290 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
6291 Diag(DS.getAtomicSpecLoc(),
6292 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6295 // Recursively parse the declarator.
6296 Actions.runWithSufficientStackSpace(
6297 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6299 if (D.getNumTypeObjects() > 0) {
6300 // C++ [dcl.ref]p4: There shall be no references to references.
6301 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6302 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6303 if (const IdentifierInfo *II = D.getIdentifier())
6304 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6307 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6310 // Once we've complained about the reference-to-reference, we
6311 // can go ahead and build the (technically ill-formed)
6312 // declarator: reference collapsing will take care of it.
6316 // Remember that we parsed a reference type.
6317 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
6319 std::move(DS.getAttributes()), SourceLocation());
6323 // When correcting from misplaced brackets before the identifier, the location
6324 // is saved inside the declarator so that other diagnostic messages can use
6325 // them. This extracts and returns that location, or returns the provided
6326 // location if a stored location does not exist.
6327 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
6328 SourceLocation Loc) {
6329 if (D.getName().StartLocation.isInvalid() &&
6330 D.getName().EndLocation.isValid())
6331 return D.getName().EndLocation;
6336 /// ParseDirectDeclarator
6337 /// direct-declarator: [C99 6.7.5]
6338 /// [C99] identifier
6339 /// '(' declarator ')'
6340 /// [GNU] '(' attributes declarator ')'
6341 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6342 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6343 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6344 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6345 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6346 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6347 /// attribute-specifier-seq[opt]
6348 /// direct-declarator '(' parameter-type-list ')'
6349 /// direct-declarator '(' identifier-list[opt] ')'
6350 /// [GNU] direct-declarator '(' parameter-forward-declarations
6351 /// parameter-type-list[opt] ')'
6352 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
6353 /// cv-qualifier-seq[opt] exception-specification[opt]
6354 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
6355 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
6356 /// ref-qualifier[opt] exception-specification[opt]
6357 /// [C++] declarator-id
6358 /// [C++11] declarator-id attribute-specifier-seq[opt]
6360 /// declarator-id: [C++ 8]
6361 /// '...'[opt] id-expression
6362 /// '::'[opt] nested-name-specifier[opt] type-name
6364 /// id-expression: [C++ 5.1]
6368 /// unqualified-id: [C++ 5.1]
6370 /// operator-function-id
6371 /// conversion-function-id
6375 /// C++17 adds the following, which we also handle here:
6377 /// simple-declaration:
6378 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6380 /// Note, any additional constructs added here may need corresponding changes
6381 /// in isConstructorDeclarator.
6382 void Parser::ParseDirectDeclarator(Declarator &D) {
6383 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6385 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
6386 // This might be a C++17 structured binding.
6387 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6388 D.getCXXScopeSpec().isEmpty())
6389 return ParseDecompositionDeclarator(D);
6391 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6392 // this context it is a bitfield. Also in range-based for statement colon
6393 // may delimit for-range-declaration.
6394 ColonProtectionRAIIObject X(
6395 *this, D.getContext() == DeclaratorContext::Member ||
6396 (D.getContext() == DeclaratorContext::ForInit &&
6397 getLangOpts().CPlusPlus11));
6399 // ParseDeclaratorInternal might already have parsed the scope.
6400 if (D.getCXXScopeSpec().isEmpty()) {
6401 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6402 D.getContext() == DeclaratorContext::Member;
6403 ParseOptionalCXXScopeSpecifier(
6404 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6405 /*ObjectHasErrors=*/false, EnteringContext);
6408 if (D.getCXXScopeSpec().isValid()) {
6409 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
6410 D.getCXXScopeSpec()))
6411 // Change the declaration context for name lookup, until this function
6412 // is exited (and the declarator has been parsed).
6413 DeclScopeObj.EnterDeclaratorScope();
6414 else if (getObjCDeclContext()) {
6415 // Ensure that we don't interpret the next token as an identifier when
6416 // dealing with declarations in an Objective-C container.
6417 D.SetIdentifier(nullptr, Tok.getLocation());
6418 D.setInvalidType(true);
6420 goto PastIdentifier;
6424 // C++0x [dcl.fct]p14:
6425 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6426 // parameter-declaration-clause without a preceding comma. In this case,
6427 // the ellipsis is parsed as part of the abstract-declarator if the type
6428 // of the parameter either names a template parameter pack that has not
6429 // been expanded or contains auto; otherwise, it is parsed as part of the
6430 // parameter-declaration-clause.
6431 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6432 !((D.getContext() == DeclaratorContext::Prototype ||
6433 D.getContext() == DeclaratorContext::LambdaExprParameter ||
6434 D.getContext() == DeclaratorContext::BlockLiteral) &&
6435 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6436 !Actions.containsUnexpandedParameterPacks(D) &&
6437 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
6438 SourceLocation EllipsisLoc = ConsumeToken();
6439 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6440 // The ellipsis was put in the wrong place. Recover, and explain to
6441 // the user what they should have done.
6443 if (EllipsisLoc.isValid())
6444 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6447 D.setEllipsisLoc(EllipsisLoc);
6449 // The ellipsis can't be followed by a parenthesized declarator. We
6450 // check for that in ParseParenDeclarator, after we have disambiguated
6451 // the l_paren token.
6454 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6456 // We found something that indicates the start of an unqualified-id.
6457 // Parse that unqualified-id.
6458 bool AllowConstructorName;
6459 bool AllowDeductionGuide;
6460 if (D.getDeclSpec().hasTypeSpecifier()) {
6461 AllowConstructorName = false;
6462 AllowDeductionGuide = false;
6463 } else if (D.getCXXScopeSpec().isSet()) {
6464 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6465 D.getContext() == DeclaratorContext::Member);
6466 AllowDeductionGuide = false;
6468 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6469 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6470 D.getContext() == DeclaratorContext::Member);
6473 bool HadScope = D.getCXXScopeSpec().isValid();
6474 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
6475 /*ObjectType=*/nullptr,
6476 /*ObjectHadErrors=*/false,
6477 /*EnteringContext=*/true,
6478 /*AllowDestructorName=*/true, AllowConstructorName,
6479 AllowDeductionGuide, nullptr, D.getName()) ||
6480 // Once we're past the identifier, if the scope was bad, mark the
6481 // whole declarator bad.
6482 D.getCXXScopeSpec().isInvalid()) {
6483 D.SetIdentifier(nullptr, Tok.getLocation());
6484 D.setInvalidType(true);
6486 // ParseUnqualifiedId might have parsed a scope specifier during error
6487 // recovery. If it did so, enter that scope.
6488 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6489 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6490 D.getCXXScopeSpec()))
6491 DeclScopeObj.EnterDeclaratorScope();
6493 // Parsed the unqualified-id; update range information and move along.
6494 if (D.getSourceRange().getBegin().isInvalid())
6495 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
6496 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
6498 goto PastIdentifier;
6501 if (D.getCXXScopeSpec().isNotEmpty()) {
6502 // We have a scope specifier but no following unqualified-id.
6503 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
6504 diag::err_expected_unqualified_id)
6506 D.SetIdentifier(nullptr, Tok.getLocation());
6507 goto PastIdentifier;
6509 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6510 assert(!getLangOpts().CPlusPlus &&
6511 "There's a C++-specific check for tok::identifier above");
6512 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6513 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6514 D.SetRangeEnd(Tok.getLocation());
6516 goto PastIdentifier;
6517 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6518 // We're not allowed an identifier here, but we got one. Try to figure out
6519 // if the user was trying to attach a name to the type, or whether the name
6520 // is some unrelated trailing syntax.
6521 bool DiagnoseIdentifier = false;
6522 if (D.hasGroupingParens())
6523 // An identifier within parens is unlikely to be intended to be anything
6524 // other than a name being "declared".
6525 DiagnoseIdentifier = true;
6526 else if (D.getContext() == DeclaratorContext::TemplateArg)
6527 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6528 DiagnoseIdentifier =
6529 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6530 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6531 D.getContext() == DeclaratorContext::AliasTemplate)
6532 // The most likely error is that the ';' was forgotten.
6533 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6534 else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
6535 D.getContext() == DeclaratorContext::TrailingReturnVar) &&
6536 !isCXX11VirtSpecifier(Tok))
6537 DiagnoseIdentifier = NextToken().isOneOf(
6538 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6539 if (DiagnoseIdentifier) {
6540 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6541 << FixItHint::CreateRemoval(Tok.getLocation());
6542 D.SetIdentifier(nullptr, Tok.getLocation());
6544 goto PastIdentifier;
6548 if (Tok.is(tok::l_paren)) {
6549 // If this might be an abstract-declarator followed by a direct-initializer,
6550 // check whether this is a valid declarator chunk. If it can't be, assume
6551 // that it's an initializer instead.
6552 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
6553 RevertingTentativeParsingAction PA(*this);
6554 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
6555 D.getDeclSpec().getTypeSpecType() == TST_auto) ==
6557 D.SetIdentifier(nullptr, Tok.getLocation());
6558 goto PastIdentifier;
6562 // direct-declarator: '(' declarator ')'
6563 // direct-declarator: '(' attributes declarator ')'
6564 // Example: 'char (*X)' or 'int (*XX)(void)'
6565 ParseParenDeclarator(D);
6567 // If the declarator was parenthesized, we entered the declarator
6568 // scope when parsing the parenthesized declarator, then exited
6569 // the scope already. Re-enter the scope, if we need to.
6570 if (D.getCXXScopeSpec().isSet()) {
6571 // If there was an error parsing parenthesized declarator, declarator
6572 // scope may have been entered before. Don't do it again.
6573 if (!D.isInvalidType() &&
6574 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6575 D.getCXXScopeSpec()))
6576 // Change the declaration context for name lookup, until this function
6577 // is exited (and the declarator has been parsed).
6578 DeclScopeObj.EnterDeclaratorScope();
6580 } else if (D.mayOmitIdentifier()) {
6581 // This could be something simple like "int" (in which case the declarator
6582 // portion is empty), if an abstract-declarator is allowed.
6583 D.SetIdentifier(nullptr, Tok.getLocation());
6585 // The grammar for abstract-pack-declarator does not allow grouping parens.
6586 // FIXME: Revisit this once core issue 1488 is resolved.
6587 if (D.hasEllipsis() && D.hasGroupingParens())
6588 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6589 diag::ext_abstract_pack_declarator_parens);
6591 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6593 if (Tok.is(tok::l_square))
6594 return ParseMisplacedBracketDeclarator(D);
6595 if (D.getContext() == DeclaratorContext::Member) {
6596 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6597 // treating these keyword as valid member names.
6598 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6599 Tok.getIdentifierInfo() &&
6600 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6601 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6602 diag::err_expected_member_name_or_semi_objcxx_keyword)
6603 << Tok.getIdentifierInfo()
6604 << (D.getDeclSpec().isEmpty() ? SourceRange()
6605 : D.getDeclSpec().getSourceRange());
6606 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6607 D.SetRangeEnd(Tok.getLocation());
6609 goto PastIdentifier;
6611 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6612 diag::err_expected_member_name_or_semi)
6613 << (D.getDeclSpec().isEmpty() ? SourceRange()
6614 : D.getDeclSpec().getSourceRange());
6616 if (Tok.getKind() == tok::TokenKind::kw_while) {
6617 Diag(Tok, diag::err_while_loop_outside_of_a_function);
6618 } else if (getLangOpts().CPlusPlus) {
6619 if (Tok.isOneOf(tok::period, tok::arrow))
6620 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6622 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6623 if (Tok.isAtStartOfLine() && Loc.isValid())
6624 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6625 << getLangOpts().CPlusPlus;
6627 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6628 diag::err_expected_unqualified_id)
6629 << getLangOpts().CPlusPlus;
6632 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6633 diag::err_expected_either)
6634 << tok::identifier << tok::l_paren;
6637 D.SetIdentifier(nullptr, Tok.getLocation());
6638 D.setInvalidType(true);
6642 assert(D.isPastIdentifier() &&
6643 "Haven't past the location of the identifier yet?");
6645 // Don't parse attributes unless we have parsed an unparenthesized name.
6646 if (D.hasName() && !D.getNumTypeObjects())
6647 MaybeParseCXX11Attributes(D);
6650 if (Tok.is(tok::l_paren)) {
6651 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6652 // Enter function-declaration scope, limiting any declarators to the
6653 // function prototype scope, including parameter declarators.
6654 ParseScope PrototypeScope(this,
6655 Scope::FunctionPrototypeScope|Scope::DeclScope|
6656 (IsFunctionDeclaration
6657 ? Scope::FunctionDeclarationScope : 0));
6659 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6660 // In such a case, check if we actually have a function declarator; if it
6661 // is not, the declarator has been fully parsed.
6662 bool IsAmbiguous = false;
6663 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6664 // C++2a [temp.res]p5
6665 // A qualified-id is assumed to name a type if
6667 // - it is a decl-specifier of the decl-specifier-seq of a
6669 // - parameter-declaration in a member-declaration [...]
6670 // - parameter-declaration in a declarator of a function or function
6671 // template declaration whose declarator-id is qualified [...]
6672 auto AllowImplicitTypename = ImplicitTypenameContext::No;
6673 if (D.getCXXScopeSpec().isSet())
6674 AllowImplicitTypename =
6675 (ImplicitTypenameContext)Actions.isDeclaratorFunctionLike(D);
6676 else if (D.getContext() == DeclaratorContext::Member) {
6677 AllowImplicitTypename = ImplicitTypenameContext::Yes;
6680 // The name of the declarator, if any, is tentatively declared within
6681 // a possible direct initializer.
6682 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6683 bool IsFunctionDecl =
6684 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
6685 TentativelyDeclaredIdentifiers.pop_back();
6686 if (!IsFunctionDecl)
6689 ParsedAttributes attrs(AttrFactory);
6690 BalancedDelimiterTracker T(*this, tok::l_paren);
6692 if (IsFunctionDeclaration)
6693 Actions.ActOnStartFunctionDeclarationDeclarator(D,
6694 TemplateParameterDepth);
6695 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6696 if (IsFunctionDeclaration)
6697 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6698 PrototypeScope.Exit();
6699 } else if (Tok.is(tok::l_square)) {
6700 ParseBracketDeclarator(D);
6701 } else if (Tok.isRegularKeywordAttribute()) {
6702 // For consistency with attribute parsing.
6703 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
6705 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6706 // This declarator is declaring a function, but the requires clause is
6707 // in the wrong place:
6708 // void (f() requires true);
6710 // void f() requires true;
6712 // void (f()) requires true;
6713 Diag(Tok, diag::err_requires_clause_inside_parens);
6715 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6716 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6717 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6718 !D.hasTrailingRequiresClause())
6719 // We're already ill-formed if we got here but we'll accept it anyway.
6720 D.setTrailingRequiresClause(TrailingRequiresClause.get());
6727 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6728 assert(Tok.is(tok::l_square));
6730 // If this doesn't look like a structured binding, maybe it's a misplaced
6731 // array declarator.
6732 // FIXME: Consume the l_square first so we don't need extra lookahead for
6734 if (!(NextToken().is(tok::identifier) &&
6735 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6736 !(NextToken().is(tok::r_square) &&
6737 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6738 return ParseMisplacedBracketDeclarator(D);
6740 BalancedDelimiterTracker T(*this, tok::l_square);
6743 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6744 while (Tok.isNot(tok::r_square)) {
6745 if (!Bindings.empty()) {
6746 if (Tok.is(tok::comma))
6749 if (Tok.is(tok::identifier)) {
6750 SourceLocation EndLoc = getEndOfPreviousToken();
6751 Diag(EndLoc, diag::err_expected)
6752 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6754 Diag(Tok, diag::err_expected_comma_or_rsquare);
6757 SkipUntil(tok::r_square, tok::comma, tok::identifier,
6758 StopAtSemi | StopBeforeMatch);
6759 if (Tok.is(tok::comma))
6761 else if (Tok.isNot(tok::identifier))
6766 if (Tok.isNot(tok::identifier)) {
6767 Diag(Tok, diag::err_expected) << tok::identifier;
6771 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6775 if (Tok.isNot(tok::r_square))
6776 // We've already diagnosed a problem here.
6779 // C++17 does not allow the identifier-list in a structured binding
6781 if (Bindings.empty())
6782 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6787 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6788 T.getCloseLocation());
6791 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6792 /// only called before the identifier, so these are most likely just grouping
6793 /// parens for precedence. If we find that these are actually function
6794 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6796 /// direct-declarator:
6797 /// '(' declarator ')'
6798 /// [GNU] '(' attributes declarator ')'
6799 /// direct-declarator '(' parameter-type-list ')'
6800 /// direct-declarator '(' identifier-list[opt] ')'
6801 /// [GNU] direct-declarator '(' parameter-forward-declarations
6802 /// parameter-type-list[opt] ')'
6804 void Parser::ParseParenDeclarator(Declarator &D) {
6805 BalancedDelimiterTracker T(*this, tok::l_paren);
6808 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6810 // Eat any attributes before we look at whether this is a grouping or function
6811 // declarator paren. If this is a grouping paren, the attribute applies to
6812 // the type being built up, for example:
6813 // int (__attribute__(()) *x)(long y)
6814 // If this ends up not being a grouping paren, the attribute applies to the
6815 // first argument, for example:
6816 // int (__attribute__(()) int x)
6817 // In either case, we need to eat any attributes to be able to determine what
6818 // sort of paren this is.
6820 ParsedAttributes attrs(AttrFactory);
6821 bool RequiresArg = false;
6822 if (Tok.is(tok::kw___attribute)) {
6823 ParseGNUAttributes(attrs);
6825 // We require that the argument list (if this is a non-grouping paren) be
6826 // present even if the attribute list was empty.
6830 // Eat any Microsoft extensions.
6831 ParseMicrosoftTypeAttributes(attrs);
6833 // Eat any Borland extensions.
6834 if (Tok.is(tok::kw___pascal))
6835 ParseBorlandTypeAttributes(attrs);
6837 // If we haven't past the identifier yet (or where the identifier would be
6838 // stored, if this is an abstract declarator), then this is probably just
6839 // grouping parens. However, if this could be an abstract-declarator, then
6840 // this could also be the start of function arguments (consider 'void()').
6843 if (!D.mayOmitIdentifier()) {
6844 // If this can't be an abstract-declarator, this *must* be a grouping
6845 // paren, because we haven't seen the identifier yet.
6847 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
6848 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6849 NextToken().is(tok::r_paren)) || // C++ int(...)
6850 isDeclarationSpecifier(
6851 ImplicitTypenameContext::No) || // 'int(int)' is a function.
6852 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6853 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6854 // considered to be a type, not a K&R identifier-list.
6857 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6861 // If this is a grouping paren, handle:
6862 // direct-declarator: '(' declarator ')'
6863 // direct-declarator: '(' attributes declarator ')'
6865 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6866 D.setEllipsisLoc(SourceLocation());
6868 bool hadGroupingParens = D.hasGroupingParens();
6869 D.setGroupingParens(true);
6870 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6874 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6875 std::move(attrs), T.getCloseLocation());
6877 D.setGroupingParens(hadGroupingParens);
6879 // An ellipsis cannot be placed outside parentheses.
6880 if (EllipsisLoc.isValid())
6881 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6886 // Okay, if this wasn't a grouping paren, it must be the start of a function
6887 // argument list. Recognize that this declarator will never have an
6888 // identifier (and remember where it would have been), then call into
6889 // ParseFunctionDeclarator to handle of argument list.
6890 D.SetIdentifier(nullptr, Tok.getLocation());
6892 // Enter function-declaration scope, limiting any declarators to the
6893 // function prototype scope, including parameter declarators.
6894 ParseScope PrototypeScope(this,
6895 Scope::FunctionPrototypeScope | Scope::DeclScope |
6896 (D.isFunctionDeclaratorAFunctionDeclaration()
6897 ? Scope::FunctionDeclarationScope : 0));
6898 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6899 PrototypeScope.Exit();
6902 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6903 const Declarator &D, const DeclSpec &DS,
6904 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
6905 // C++11 [expr.prim.general]p3:
6906 // If a declaration declares a member function or member function
6907 // template of a class X, the expression this is a prvalue of type
6908 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6909 // and the end of the function-definition, member-declarator, or
6911 // FIXME: currently, "static" case isn't handled correctly.
6912 bool IsCXX11MemberFunction =
6913 getLangOpts().CPlusPlus11 &&
6914 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6915 (D.getContext() == DeclaratorContext::Member
6916 ? !D.getDeclSpec().isFriendSpecified()
6917 : D.getContext() == DeclaratorContext::File &&
6918 D.getCXXScopeSpec().isValid() &&
6919 Actions.CurContext->isRecord());
6920 if (!IsCXX11MemberFunction)
6923 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6924 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6926 // FIXME: Collect C++ address spaces.
6927 // If there are multiple different address spaces, the source is invalid.
6928 // Carry on using the first addr space for the qualifiers of 'this'.
6929 // The diagnostic will be given later while creating the function
6930 // prototype for the method.
6931 if (getLangOpts().OpenCLCPlusPlus) {
6932 for (ParsedAttr &attr : DS.getAttributes()) {
6933 LangAS ASIdx = attr.asOpenCLLangAS();
6934 if (ASIdx != LangAS::Default) {
6935 Q.addAddressSpace(ASIdx);
6940 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6941 IsCXX11MemberFunction);
6944 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6945 /// declarator D up to a paren, which indicates that we are parsing function
6948 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
6949 /// immediately after the open paren - they will be applied to the DeclSpec
6950 /// of the first parameter.
6952 /// If RequiresArg is true, then the first argument of the function is required
6953 /// to be present and required to not be an identifier list.
6955 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6956 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6957 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6958 /// (C++2a) the trailing requires-clause.
6960 /// [C++11] exception-specification:
6961 /// dynamic-exception-specification
6962 /// noexcept-specification
6964 void Parser::ParseFunctionDeclarator(Declarator &D,
6965 ParsedAttributes &FirstArgAttrs,
6966 BalancedDelimiterTracker &Tracker,
6969 assert(getCurScope()->isFunctionPrototypeScope() &&
6970 "Should call from a Function scope");
6971 // lparen is already consumed!
6972 assert(D.isPastIdentifier() && "Should not call before identifier!");
6974 // This should be true when the function has typed arguments.
6975 // Otherwise, it is treated as a K&R-style function.
6976 bool HasProto = false;
6977 // Build up an array of information about the parsed arguments.
6978 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6979 // Remember where we see an ellipsis, if any.
6980 SourceLocation EllipsisLoc;
6982 DeclSpec DS(AttrFactory);
6983 bool RefQualifierIsLValueRef = true;
6984 SourceLocation RefQualifierLoc;
6985 ExceptionSpecificationType ESpecType = EST_None;
6986 SourceRange ESpecRange;
6987 SmallVector<ParsedType, 2> DynamicExceptions;
6988 SmallVector<SourceRange, 2> DynamicExceptionRanges;
6989 ExprResult NoexceptExpr;
6990 CachedTokens *ExceptionSpecTokens = nullptr;
6991 ParsedAttributes FnAttrs(AttrFactory);
6992 TypeResult TrailingReturnType;
6993 SourceLocation TrailingReturnTypeLoc;
6995 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6996 EndLoc is the end location for the function declarator.
6997 They differ for trailing return types. */
6998 SourceLocation StartLoc, LocalEndLoc, EndLoc;
6999 SourceLocation LParenLoc, RParenLoc;
7000 LParenLoc = Tracker.getOpenLocation();
7001 StartLoc = LParenLoc;
7003 if (isFunctionDeclaratorIdentifierList()) {
7005 Diag(Tok, diag::err_argument_required_after_attribute);
7007 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7009 Tracker.consumeClose();
7010 RParenLoc = Tracker.getCloseLocation();
7011 LocalEndLoc = RParenLoc;
7014 // If there are attributes following the identifier list, parse them and
7016 MaybeParseCXX11Attributes(FnAttrs);
7017 ProhibitAttributes(FnAttrs);
7019 if (Tok.isNot(tok::r_paren))
7020 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7021 else if (RequiresArg)
7022 Diag(Tok, diag::err_argument_required_after_attribute);
7024 // OpenCL disallows functions without a prototype, but it doesn't enforce
7025 // strict prototypes as in C2x because it allows a function definition to
7026 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7027 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7028 getLangOpts().OpenCL;
7030 // If we have the closing ')', eat it.
7031 Tracker.consumeClose();
7032 RParenLoc = Tracker.getCloseLocation();
7033 LocalEndLoc = RParenLoc;
7036 if (getLangOpts().CPlusPlus) {
7037 // FIXME: Accept these components in any order, and produce fixits to
7038 // correct the order if the user gets it wrong. Ideally we should deal
7039 // with the pure-specifier in the same way.
7041 // Parse cv-qualifier-seq[opt].
7042 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
7043 /*AtomicAllowed*/ false,
7044 /*IdentifierRequired=*/false,
7045 llvm::function_ref<void()>([&]() {
7046 Actions.CodeCompleteFunctionQualifiers(DS, D);
7048 if (!DS.getSourceRange().getEnd().isInvalid()) {
7049 EndLoc = DS.getSourceRange().getEnd();
7052 // Parse ref-qualifier[opt].
7053 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7054 EndLoc = RefQualifierLoc;
7056 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7057 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7059 // Parse exception-specification[opt].
7060 // FIXME: Per [class.mem]p6, all exception-specifications at class scope
7061 // should be delayed, including those for non-members (eg, friend
7062 // declarations). But only applying this to member declarations is
7063 // consistent with what other implementations do.
7064 bool Delayed = D.isFirstDeclarationOfMember() &&
7065 D.isFunctionDeclaratorAFunctionDeclaration();
7066 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7067 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7068 GetLookAheadToken(1).is(tok::l_paren) &&
7069 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7070 GetLookAheadToken(3).is(tok::l_paren) &&
7071 GetLookAheadToken(4).is(tok::identifier) &&
7072 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7073 // HACK: We've got an exception-specification
7074 // noexcept(noexcept(swap(...)))
7076 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7077 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7078 // for 'swap' will only find the function we're currently declaring,
7079 // whereas it expects to find a non-member swap through ADL. Turn off
7080 // delayed parsing to give it a chance to find what it expects.
7083 ESpecType = tryParseExceptionSpecification(Delayed,
7086 DynamicExceptionRanges,
7088 ExceptionSpecTokens);
7089 if (ESpecType != EST_None)
7090 EndLoc = ESpecRange.getEnd();
7092 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7093 // after the exception-specification.
7094 MaybeParseCXX11Attributes(FnAttrs);
7096 // Parse trailing-return-type[opt].
7097 LocalEndLoc = EndLoc;
7098 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7099 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7100 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
7101 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7102 LocalEndLoc = Tok.getLocation();
7104 TrailingReturnType =
7105 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7106 TrailingReturnTypeLoc = Range.getBegin();
7107 EndLoc = Range.getEnd();
7110 MaybeParseCXX11Attributes(FnAttrs);
7114 // Collect non-parameter declarations from the prototype if this is a function
7115 // declaration. They will be moved into the scope of the function. Only do
7116 // this in C and not C++, where the decls will continue to live in the
7117 // surrounding context.
7118 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7119 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7120 for (Decl *D : getCurScope()->decls()) {
7121 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7122 if (!ND || isa<ParmVarDecl>(ND))
7124 DeclsInPrototype.push_back(ND);
7126 // Sort DeclsInPrototype based on raw encoding of the source location.
7127 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7128 // moving to DeclContext. This provides a stable ordering for traversing
7129 // Decls in DeclContext, which is important for tasks like ASTWriter for
7130 // deterministic output.
7131 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7132 return D1->getLocation().getRawEncoding() <
7133 D2->getLocation().getRawEncoding();
7137 // Remember that we parsed a function type, and remember the attributes.
7138 D.AddTypeInfo(DeclaratorChunk::getFunction(
7139 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7140 ParamInfo.size(), EllipsisLoc, RParenLoc,
7141 RefQualifierIsLValueRef, RefQualifierLoc,
7142 /*MutableLoc=*/SourceLocation(),
7143 ESpecType, ESpecRange, DynamicExceptions.data(),
7144 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7145 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7146 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7147 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7149 std::move(FnAttrs), EndLoc);
7152 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
7153 /// true if a ref-qualifier is found.
7154 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7155 SourceLocation &RefQualifierLoc) {
7156 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7157 Diag(Tok, getLangOpts().CPlusPlus11 ?
7158 diag::warn_cxx98_compat_ref_qualifier :
7159 diag::ext_ref_qualifier);
7161 RefQualifierIsLValueRef = Tok.is(tok::amp);
7162 RefQualifierLoc = ConsumeToken();
7168 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
7169 /// identifier list form for a K&R-style function: void foo(a,b,c)
7171 /// Note that identifier-lists are only allowed for normal declarators, not for
7172 /// abstract-declarators.
7173 bool Parser::isFunctionDeclaratorIdentifierList() {
7174 return !getLangOpts().requiresStrictPrototypes()
7175 && Tok.is(tok::identifier)
7176 && !TryAltiVecVectorToken()
7177 // K&R identifier lists can't have typedefs as identifiers, per C99
7179 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7180 // Identifier lists follow a really simple grammar: the identifiers can
7181 // be followed *only* by a ", identifier" or ")". However, K&R
7182 // identifier lists are really rare in the brave new modern world, and
7183 // it is very common for someone to typo a type in a non-K&R style
7184 // list. If we are presented with something like: "void foo(intptr x,
7185 // float y)", we don't want to start parsing the function declarator as
7186 // though it is a K&R style declarator just because intptr is an
7189 // To handle this, we check to see if the token after the first
7190 // identifier is a "," or ")". Only then do we parse it as an
7192 && (!Tok.is(tok::eof) &&
7193 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7196 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
7197 /// we found a K&R-style identifier list instead of a typed parameter list.
7199 /// After returning, ParamInfo will hold the parsed parameters.
7201 /// identifier-list: [C99 6.7.5]
7203 /// identifier-list ',' identifier
7205 void Parser::ParseFunctionDeclaratorIdentifierList(
7207 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
7208 // We should never reach this point in C2x or C++.
7209 assert(!getLangOpts().requiresStrictPrototypes() &&
7210 "Cannot parse an identifier list in C2x or C++");
7212 // If there was no identifier specified for the declarator, either we are in
7213 // an abstract-declarator, or we are in a parameter declarator which was found
7214 // to be abstract. In abstract-declarators, identifier lists are not valid:
7216 if (!D.getIdentifier())
7217 Diag(Tok, diag::ext_ident_list_in_param);
7219 // Maintain an efficient lookup of params we have seen so far.
7220 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
7223 // If this isn't an identifier, report the error and skip until ')'.
7224 if (Tok.isNot(tok::identifier)) {
7225 Diag(Tok, diag::err_expected) << tok::identifier;
7226 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7227 // Forget we parsed anything.
7232 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7234 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7235 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7236 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7238 // Verify that the argument identifier has not already been mentioned.
7239 if (!ParamsSoFar.insert(ParmII).second) {
7240 Diag(Tok, diag::err_param_redefinition) << ParmII;
7242 // Remember this identifier in ParamInfo.
7243 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7248 // Eat the identifier.
7250 // The list continues if we see a comma.
7251 } while (TryConsumeToken(tok::comma));
7254 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
7255 /// after the opening parenthesis. This function will not parse a K&R-style
7256 /// identifier list.
7258 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
7259 /// is non-null, then the caller parsed those attributes immediately after the
7260 /// open paren - they will be applied to the DeclSpec of the first parameter.
7262 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
7263 /// be the location of the ellipsis, if any was parsed.
7265 /// parameter-type-list: [C99 6.7.5]
7267 /// parameter-list ',' '...'
7268 /// [C++] parameter-list '...'
7270 /// parameter-list: [C99 6.7.5]
7271 /// parameter-declaration
7272 /// parameter-list ',' parameter-declaration
7274 /// parameter-declaration: [C99 6.7.5]
7275 /// declaration-specifiers declarator
7276 /// [C++] declaration-specifiers declarator '=' assignment-expression
7277 /// [C++11] initializer-clause
7278 /// [GNU] declaration-specifiers declarator attributes
7279 /// declaration-specifiers abstract-declarator[opt]
7280 /// [C++] declaration-specifiers abstract-declarator[opt]
7281 /// '=' assignment-expression
7282 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
7283 /// [C++11] attribute-specifier-seq parameter-declaration
7285 void Parser::ParseParameterDeclarationClause(
7286 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7287 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
7288 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7290 // Avoid exceeding the maximum function scope depth.
7291 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7292 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7293 // getFunctionPrototypeDepth() - 1.
7294 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7295 ParmVarDecl::getMaxFunctionScopeDepth()) {
7296 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7297 << ParmVarDecl::getMaxFunctionScopeDepth();
7302 // C++2a [temp.res]p5
7303 // A qualified-id is assumed to name a type if
7305 // - it is a decl-specifier of the decl-specifier-seq of a
7307 // - parameter-declaration in a member-declaration [...]
7308 // - parameter-declaration in a declarator of a function or function
7309 // template declaration whose declarator-id is qualified [...]
7310 // - parameter-declaration in a lambda-declarator [...]
7311 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7312 if (DeclaratorCtx == DeclaratorContext::Member ||
7313 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7314 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7315 IsACXXFunctionDeclaration) {
7316 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7320 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7321 // before deciding this was a parameter-declaration-clause.
7322 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7325 // Parse the declaration-specifiers.
7326 // Just use the ParsingDeclaration "scope" of the declarator.
7327 DeclSpec DS(AttrFactory);
7329 ParsedAttributes ArgDeclAttrs(AttrFactory);
7330 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7332 if (FirstArgAttrs.Range.isValid()) {
7333 // If the caller parsed attributes for the first argument, add them now.
7334 // Take them so that we only apply the attributes to the first parameter.
7335 // We have already started parsing the decl-specifier sequence, so don't
7336 // parse any parameter-declaration pieces that precede it.
7337 ArgDeclSpecAttrs.takeAllFrom(FirstArgAttrs);
7339 // Parse any C++11 attributes.
7340 MaybeParseCXX11Attributes(ArgDeclAttrs);
7342 // Skip any Microsoft attributes before a param.
7343 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7346 SourceLocation DSStart = Tok.getLocation();
7348 ParseDeclarationSpecifiers(DS, /*TemplateInfo=*/ParsedTemplateInfo(),
7349 AS_none, DeclSpecContext::DSC_normal,
7350 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7351 DS.takeAttributesFrom(ArgDeclSpecAttrs);
7353 // Parse the declarator. This is "PrototypeContext" or
7354 // "LambdaExprParameterContext", because we must accept either
7355 // 'declarator' or 'abstract-declarator' here.
7356 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7357 DeclaratorCtx == DeclaratorContext::RequiresExpr
7358 ? DeclaratorContext::RequiresExpr
7359 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7360 ? DeclaratorContext::LambdaExprParameter
7361 : DeclaratorContext::Prototype);
7362 ParseDeclarator(ParmDeclarator);
7364 // Parse GNU attributes, if present.
7365 MaybeParseGNUAttributes(ParmDeclarator);
7366 if (getLangOpts().HLSL)
7367 MaybeParseHLSLSemantics(DS.getAttributes());
7369 if (Tok.is(tok::kw_requires)) {
7370 // User tried to define a requires clause in a parameter declaration,
7371 // which is surely not a function declaration.
7372 // void f(int (*g)(int, int) requires true);
7374 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7376 Actions.CorrectDelayedTyposInExpr(
7377 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7380 // Remember this parsed parameter in ParamInfo.
7381 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7383 // DefArgToks is used when the parsing of default arguments needs
7385 std::unique_ptr<CachedTokens> DefArgToks;
7387 // If no parameter was specified, verify that *something* was specified,
7388 // otherwise we have a missing type and identifier.
7389 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7390 ParmDeclarator.getNumTypeObjects() == 0) {
7391 // Completely missing, emit error.
7392 Diag(DSStart, diag::err_missing_param);
7394 // Otherwise, we have something. Add it and let semantic analysis try
7395 // to grok it and add the result to the ParamInfo we are building.
7397 // Last chance to recover from a misplaced ellipsis in an attempted
7398 // parameter pack declaration.
7399 if (Tok.is(tok::ellipsis) &&
7400 (NextToken().isNot(tok::r_paren) ||
7401 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7402 !Actions.isUnexpandedParameterPackPermitted())) &&
7403 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
7404 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
7406 // Now we are at the point where declarator parsing is finished.
7408 // Try to catch keywords in place of the identifier in a declarator, and
7409 // in particular the common case where:
7410 // 1 identifier comes at the end of the declarator
7411 // 2 if the identifier is dropped, the declarator is valid but anonymous
7413 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7414 // which is never valid in a param list (e.g. missing a ',')
7415 // And we can't handle this in ParseDeclarator because in general keywords
7416 // may be allowed to follow the declarator. (And in some cases there'd be
7417 // better recovery like inserting punctuation). ParseDeclarator is just
7418 // treating this as an anonymous parameter, and fortunately at this point
7419 // we've already almost done that.
7421 // We care about case 1) where the declarator type should be known, and
7422 // the identifier should be null.
7423 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7424 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
7425 Tok.getIdentifierInfo() &&
7426 Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
7427 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7428 // Consume the keyword.
7431 // Inform the actions module about the parameter declarator, so it gets
7432 // added to the current scope.
7433 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
7434 // Parse the default argument, if any. We parse the default
7435 // arguments in all dialects; the semantic analysis in
7436 // ActOnParamDefaultArgument will reject the default argument in
7438 if (Tok.is(tok::equal)) {
7439 SourceLocation EqualLoc = Tok.getLocation();
7441 // Parse the default argument
7442 if (DeclaratorCtx == DeclaratorContext::Member) {
7443 // If we're inside a class definition, cache the tokens
7444 // corresponding to the default argument. We'll actually parse
7445 // them when we see the end of the class definition.
7446 DefArgToks.reset(new CachedTokens);
7448 SourceLocation ArgStartLoc = NextToken().getLocation();
7449 ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument);
7450 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7456 // The argument isn't actually potentially evaluated unless it is
7458 EnterExpressionEvaluationContext Eval(
7460 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
7463 ExprResult DefArgResult;
7464 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7465 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
7466 DefArgResult = ParseBraceInitializer();
7468 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
7469 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
7470 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
7471 // Skip the statement expression and continue parsing
7472 SkipUntil(tok::comma, StopBeforeMatch);
7475 DefArgResult = ParseAssignmentExpression();
7477 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
7478 if (DefArgResult.isInvalid()) {
7479 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
7480 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7482 // Inform the actions module about the default argument
7483 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7484 DefArgResult.get());
7489 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7490 ParmDeclarator.getIdentifierLoc(),
7491 Param, std::move(DefArgToks)));
7494 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7495 if (!getLangOpts().CPlusPlus) {
7496 // We have ellipsis without a preceding ',', which is ill-formed
7497 // in C. Complain and provide the fix.
7498 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7499 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7500 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7501 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7502 // It looks like this was supposed to be a parameter pack. Warn and
7503 // point out where the ellipsis should have gone.
7504 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7505 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7506 << ParmEllipsis.isValid() << ParmEllipsis;
7507 if (ParmEllipsis.isValid()) {
7509 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7511 Diag(ParmDeclarator.getIdentifierLoc(),
7512 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7513 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7515 << !ParmDeclarator.hasName();
7517 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7518 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7521 // We can't have any more parameters after an ellipsis.
7525 // If the next token is a comma, consume it and keep reading arguments.
7526 } while (TryConsumeToken(tok::comma));
7529 /// [C90] direct-declarator '[' constant-expression[opt] ']'
7530 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
7531 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
7532 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
7533 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
7534 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
7535 /// attribute-specifier-seq[opt]
7536 void Parser::ParseBracketDeclarator(Declarator &D) {
7537 if (CheckProhibitedCXX11Attribute())
7540 BalancedDelimiterTracker T(*this, tok::l_square);
7543 // C array syntax has many features, but by-far the most common is [] and [4].
7544 // This code does a fast path to handle some of the most obvious cases.
7545 if (Tok.getKind() == tok::r_square) {
7547 ParsedAttributes attrs(AttrFactory);
7548 MaybeParseCXX11Attributes(attrs);
7550 // Remember that we parsed the empty array type.
7551 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7552 T.getOpenLocation(),
7553 T.getCloseLocation()),
7554 std::move(attrs), T.getCloseLocation());
7556 } else if (Tok.getKind() == tok::numeric_constant &&
7557 GetLookAheadToken(1).is(tok::r_square)) {
7558 // [4] is very common. Parse the numeric constant expression.
7559 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
7563 ParsedAttributes attrs(AttrFactory);
7564 MaybeParseCXX11Attributes(attrs);
7566 // Remember that we parsed a array type, and remember its features.
7567 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
7568 T.getOpenLocation(),
7569 T.getCloseLocation()),
7570 std::move(attrs), T.getCloseLocation());
7572 } else if (Tok.getKind() == tok::code_completion) {
7574 Actions.CodeCompleteBracketDeclarator(getCurScope());
7578 // If valid, this location is the position where we read the 'static' keyword.
7579 SourceLocation StaticLoc;
7580 TryConsumeToken(tok::kw_static, StaticLoc);
7582 // If there is a type-qualifier-list, read it now.
7583 // Type qualifiers in an array subscript are a C99 feature.
7584 DeclSpec DS(AttrFactory);
7585 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
7587 // If we haven't already read 'static', check to see if there is one after the
7588 // type-qualifier-list.
7589 if (!StaticLoc.isValid())
7590 TryConsumeToken(tok::kw_static, StaticLoc);
7592 // Handle "direct-declarator [ type-qual-list[opt] * ]".
7593 bool isStar = false;
7594 ExprResult NumElements;
7596 // Handle the case where we have '[*]' as the array size. However, a leading
7597 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
7598 // the token after the star is a ']'. Since stars in arrays are
7599 // infrequent, use of lookahead is not costly here.
7600 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
7601 ConsumeToken(); // Eat the '*'.
7603 if (StaticLoc.isValid()) {
7604 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
7605 StaticLoc = SourceLocation(); // Drop the static.
7608 } else if (Tok.isNot(tok::r_square)) {
7609 // Note, in C89, this production uses the constant-expr production instead
7610 // of assignment-expr. The only difference is that assignment-expr allows
7611 // things like '=' and '*='. Sema rejects these in C89 mode because they
7612 // are not i-c-e's, so we don't need to distinguish between the two here.
7614 // Parse the constant-expression or assignment-expression now (depending
7616 if (getLangOpts().CPlusPlus) {
7617 NumElements = ParseConstantExpression();
7619 EnterExpressionEvaluationContext Unevaluated(
7620 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7622 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
7625 if (StaticLoc.isValid()) {
7626 Diag(StaticLoc, diag::err_unspecified_size_with_static);
7627 StaticLoc = SourceLocation(); // Drop the static.
7631 // If there was an error parsing the assignment-expression, recover.
7632 if (NumElements.isInvalid()) {
7633 D.setInvalidType(true);
7634 // If the expression was invalid, skip it.
7635 SkipUntil(tok::r_square, StopAtSemi);
7641 MaybeParseCXX11Attributes(DS.getAttributes());
7643 // Remember that we parsed a array type, and remember its features.
7645 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
7646 isStar, NumElements.get(), T.getOpenLocation(),
7647 T.getCloseLocation()),
7648 std::move(DS.getAttributes()), T.getCloseLocation());
7651 /// Diagnose brackets before an identifier.
7652 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7653 assert(Tok.is(tok::l_square) && "Missing opening bracket");
7654 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7656 SourceLocation StartBracketLoc = Tok.getLocation();
7657 Declarator TempDeclarator(D.getDeclSpec(), ParsedAttributesView::none(),
7660 while (Tok.is(tok::l_square)) {
7661 ParseBracketDeclarator(TempDeclarator);
7664 // Stuff the location of the start of the brackets into the Declarator.
7665 // The diagnostics from ParseDirectDeclarator will make more sense if
7666 // they use this location instead.
7667 if (Tok.is(tok::semi))
7668 D.getName().EndLocation = StartBracketLoc;
7670 SourceLocation SuggestParenLoc = Tok.getLocation();
7672 // Now that the brackets are removed, try parsing the declarator again.
7673 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7675 // Something went wrong parsing the brackets, in which case,
7676 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7678 if (TempDeclarator.getNumTypeObjects() == 0)
7681 // Determine if parens will need to be suggested in the diagnostic.
7682 bool NeedParens = false;
7683 if (D.getNumTypeObjects() != 0) {
7684 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7685 case DeclaratorChunk::Pointer:
7686 case DeclaratorChunk::Reference:
7687 case DeclaratorChunk::BlockPointer:
7688 case DeclaratorChunk::MemberPointer:
7689 case DeclaratorChunk::Pipe:
7692 case DeclaratorChunk::Array:
7693 case DeclaratorChunk::Function:
7694 case DeclaratorChunk::Paren:
7700 // Create a DeclaratorChunk for the inserted parens.
7701 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7702 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7706 // Adding back the bracket info to the end of the Declarator.
7707 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7708 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7709 D.AddTypeInfo(Chunk, SourceLocation());
7712 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7713 // If parentheses are required, always suggest them.
7714 if (!D.getIdentifier() && !NeedParens)
7717 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7719 // Generate the move bracket error message.
7720 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7721 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7724 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7725 << getLangOpts().CPlusPlus
7726 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7727 << FixItHint::CreateInsertion(EndLoc, ")")
7728 << FixItHint::CreateInsertionFromRange(
7729 EndLoc, CharSourceRange(BracketRange, true))
7730 << FixItHint::CreateRemoval(BracketRange);
7732 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7733 << getLangOpts().CPlusPlus
7734 << FixItHint::CreateInsertionFromRange(
7735 EndLoc, CharSourceRange(BracketRange, true))
7736 << FixItHint::CreateRemoval(BracketRange);
7740 /// [GNU] typeof-specifier:
7741 /// typeof ( expressions )
7742 /// typeof ( type-name )
7743 /// [GNU/C++] typeof unary-expression
7744 /// [C2x] typeof-specifier:
7745 /// typeof '(' typeof-specifier-argument ')'
7746 /// typeof_unqual '(' typeof-specifier-argument ')'
7748 /// typeof-specifier-argument:
7752 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7753 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
7754 "Not a typeof specifier");
7756 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
7757 const IdentifierInfo *II = Tok.getIdentifierInfo();
7758 if (getLangOpts().C2x && !II->getName().startswith("__"))
7759 Diag(Tok.getLocation(), diag::warn_c2x_compat_keyword) << Tok.getName();
7762 SourceLocation StartLoc = ConsumeToken();
7763 bool HasParens = Tok.is(tok::l_paren);
7765 EnterExpressionEvaluationContext Unevaluated(
7766 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7767 Sema::ReuseLambdaContextDecl);
7771 SourceRange CastRange;
7772 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7773 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7775 DS.setTypeArgumentRange(CastRange);
7777 if (CastRange.getEnd().isInvalid())
7778 // FIXME: Not accurate, the range gets one token more than it should.
7779 DS.SetRangeEnd(Tok.getLocation());
7781 DS.SetRangeEnd(CastRange.getEnd());
7785 DS.SetTypeSpecError();
7789 const char *PrevSpec = nullptr;
7791 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7792 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualType
7793 : DeclSpec::TST_typeofType,
7796 Actions.getASTContext().getPrintingPolicy()))
7797 Diag(StartLoc, DiagID) << PrevSpec;
7801 // If we get here, the operand to the typeof was an expression.
7802 if (Operand.isInvalid()) {
7803 DS.SetTypeSpecError();
7807 // We might need to transform the operand if it is potentially evaluated.
7808 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7809 if (Operand.isInvalid()) {
7810 DS.SetTypeSpecError();
7814 const char *PrevSpec = nullptr;
7816 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7817 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualExpr
7818 : DeclSpec::TST_typeofExpr,
7820 DiagID, Operand.get(),
7821 Actions.getASTContext().getPrintingPolicy()))
7822 Diag(StartLoc, DiagID) << PrevSpec;
7825 /// [C11] atomic-specifier:
7826 /// _Atomic ( type-name )
7828 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7829 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7830 "Not an atomic specifier");
7832 SourceLocation StartLoc = ConsumeToken();
7833 BalancedDelimiterTracker T(*this, tok::l_paren);
7834 if (T.consumeOpen())
7837 TypeResult Result = ParseTypeName();
7838 if (Result.isInvalid()) {
7839 SkipUntil(tok::r_paren, StopAtSemi);
7846 if (T.getCloseLocation().isInvalid())
7849 DS.setTypeArgumentRange(T.getRange());
7850 DS.SetRangeEnd(T.getCloseLocation());
7852 const char *PrevSpec = nullptr;
7854 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7855 DiagID, Result.get(),
7856 Actions.getASTContext().getPrintingPolicy()))
7857 Diag(StartLoc, DiagID) << PrevSpec;
7860 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7861 /// from TryAltiVecVectorToken.
7862 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7863 Token Next = NextToken();
7864 switch (Next.getKind()) {
7865 default: return false;
7868 case tok::kw_signed:
7869 case tok::kw_unsigned:
7874 case tok::kw_double:
7877 case tok::kw___bool:
7878 case tok::kw___pixel:
7879 Tok.setKind(tok::kw___vector);
7881 case tok::identifier:
7882 if (Next.getIdentifierInfo() == Ident_pixel) {
7883 Tok.setKind(tok::kw___vector);
7886 if (Next.getIdentifierInfo() == Ident_bool ||
7887 Next.getIdentifierInfo() == Ident_Bool) {
7888 Tok.setKind(tok::kw___vector);
7895 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7896 const char *&PrevSpec, unsigned &DiagID,
7898 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7899 if (Tok.getIdentifierInfo() == Ident_vector) {
7900 Token Next = NextToken();
7901 switch (Next.getKind()) {
7904 case tok::kw_signed:
7905 case tok::kw_unsigned:
7910 case tok::kw_double:
7913 case tok::kw___bool:
7914 case tok::kw___pixel:
7915 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7917 case tok::identifier:
7918 if (Next.getIdentifierInfo() == Ident_pixel) {
7919 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7922 if (Next.getIdentifierInfo() == Ident_bool ||
7923 Next.getIdentifierInfo() == Ident_Bool) {
7925 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7932 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7933 DS.isTypeAltiVecVector()) {
7934 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7936 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7937 DS.isTypeAltiVecVector()) {
7938 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7944 void Parser::DiagnoseBitIntUse(const Token &Tok) {
7945 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
7946 // the token is about _BitInt and gets (potentially) diagnosed as use of an
7948 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
7949 "expected either an _ExtInt or _BitInt token!");
7951 SourceLocation Loc = Tok.getLocation();
7952 if (Tok.is(tok::kw__ExtInt)) {
7953 Diag(Loc, diag::warn_ext_int_deprecated)
7954 << FixItHint::CreateReplacement(Loc, "_BitInt");
7956 // In C2x mode, diagnose that the use is not compatible with pre-C2x modes.
7957 // Otherwise, diagnose that the use is a Clang extension.
7958 if (getLangOpts().C2x)
7959 Diag(Loc, diag::warn_c2x_compat_keyword) << Tok.getName();
7961 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;