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
));
1698 // Consume the attributes.
1699 SourceLocation Loc
= Tok
.getLocation();
1700 ParseCXX11Attributes(Attrs
);
1701 CharSourceRange
AttrRange(SourceRange(Loc
, Attrs
.Range
.getEnd()), true);
1702 // FIXME: use err_attributes_misplaced
1703 Diag(Loc
, diag::err_attributes_not_allowed
)
1704 << FixItHint::CreateInsertionFromRange(CorrectLocation
, AttrRange
)
1705 << FixItHint::CreateRemoval(AttrRange
);
1708 void Parser::DiagnoseProhibitedAttributes(
1709 const SourceRange
&Range
, const SourceLocation CorrectLocation
) {
1710 if (CorrectLocation
.isValid()) {
1711 CharSourceRange
AttrRange(Range
, true);
1712 Diag(CorrectLocation
, diag::err_attributes_misplaced
)
1713 << FixItHint::CreateInsertionFromRange(CorrectLocation
, AttrRange
)
1714 << FixItHint::CreateRemoval(AttrRange
);
1716 Diag(Range
.getBegin(), diag::err_attributes_not_allowed
) << Range
;
1719 void Parser::ProhibitCXX11Attributes(ParsedAttributes
&Attrs
, unsigned DiagID
,
1720 bool DiagnoseEmptyAttrs
,
1721 bool WarnOnUnknownAttrs
) {
1723 if (DiagnoseEmptyAttrs
&& Attrs
.empty() && Attrs
.Range
.isValid()) {
1724 // An attribute list has been parsed, but it was empty.
1725 // This is the case for [[]].
1726 const auto &LangOpts
= getLangOpts();
1727 auto &SM
= PP
.getSourceManager();
1729 Lexer::getRawToken(Attrs
.Range
.getBegin(), FirstLSquare
, SM
, LangOpts
);
1731 if (FirstLSquare
.is(tok::l_square
)) {
1732 std::optional
<Token
> SecondLSquare
=
1733 Lexer::findNextToken(FirstLSquare
.getLocation(), SM
, LangOpts
);
1735 if (SecondLSquare
&& SecondLSquare
->is(tok::l_square
)) {
1736 // The attribute range starts with [[, but is empty. So this must
1737 // be [[]], which we are supposed to diagnose because
1738 // DiagnoseEmptyAttrs is true.
1739 Diag(Attrs
.Range
.getBegin(), DiagID
) << Attrs
.Range
;
1745 for (const ParsedAttr
&AL
: Attrs
) {
1746 if (!AL
.isCXX11Attribute() && !AL
.isC2xAttribute())
1748 if (AL
.getKind() == ParsedAttr::UnknownAttribute
) {
1749 if (WarnOnUnknownAttrs
)
1750 Diag(AL
.getLoc(), diag::warn_unknown_attribute_ignored
)
1751 << AL
<< AL
.getRange();
1753 Diag(AL
.getLoc(), DiagID
) << AL
;
1759 void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes
&Attrs
) {
1760 for (const ParsedAttr
&PA
: Attrs
) {
1761 if (PA
.isCXX11Attribute() || PA
.isC2xAttribute())
1762 Diag(PA
.getLoc(), diag::ext_cxx11_attr_placement
) << PA
<< PA
.getRange();
1766 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1767 // applies to var, not the type Foo.
1768 // As an exception to the rule, __declspec(align(...)) before the
1769 // class-key affects the type instead of the variable.
1770 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1772 // This function moves attributes that should apply to the type off DS to Attrs.
1773 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes
&Attrs
,
1775 Sema::TagUseKind TUK
) {
1776 if (TUK
== Sema::TUK_Reference
)
1779 llvm::SmallVector
<ParsedAttr
*, 1> ToBeMoved
;
1781 for (ParsedAttr
&AL
: DS
.getAttributes()) {
1782 if ((AL
.getKind() == ParsedAttr::AT_Aligned
&&
1783 AL
.isDeclspecAttribute()) ||
1784 AL
.isMicrosoftAttribute())
1785 ToBeMoved
.push_back(&AL
);
1788 for (ParsedAttr
*AL
: ToBeMoved
) {
1789 DS
.getAttributes().remove(AL
);
1794 /// ParseDeclaration - Parse a full 'declaration', which consists of
1795 /// declaration-specifiers, some number of declarators, and a semicolon.
1796 /// 'Context' should be a DeclaratorContext value. This returns the
1797 /// location of the semicolon in DeclEnd.
1799 /// declaration: [C99 6.7]
1800 /// block-declaration ->
1801 /// simple-declaration
1803 /// [C++] template-declaration
1804 /// [C++] namespace-definition
1805 /// [C++] using-directive
1806 /// [C++] using-declaration
1807 /// [C++11/C11] static_assert-declaration
1808 /// others... [FIXME]
1810 Parser::DeclGroupPtrTy
Parser::ParseDeclaration(DeclaratorContext Context
,
1811 SourceLocation
&DeclEnd
,
1812 ParsedAttributes
&DeclAttrs
,
1813 ParsedAttributes
&DeclSpecAttrs
,
1814 SourceLocation
*DeclSpecStart
) {
1815 ParenBraceBracketBalancer
BalancerRAIIObj(*this);
1816 // Must temporarily exit the objective-c container scope for
1817 // parsing c none objective-c decls.
1818 ObjCDeclContextSwitch
ObjCDC(*this);
1820 Decl
*SingleDecl
= nullptr;
1821 switch (Tok
.getKind()) {
1822 case tok::kw_template
:
1823 case tok::kw_export
:
1824 ProhibitAttributes(DeclAttrs
);
1825 ProhibitAttributes(DeclSpecAttrs
);
1827 ParseDeclarationStartingWithTemplate(Context
, DeclEnd
, DeclAttrs
);
1829 case tok::kw_inline
:
1830 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1831 if (getLangOpts().CPlusPlus
&& NextToken().is(tok::kw_namespace
)) {
1832 ProhibitAttributes(DeclAttrs
);
1833 ProhibitAttributes(DeclSpecAttrs
);
1834 SourceLocation InlineLoc
= ConsumeToken();
1835 return ParseNamespace(Context
, DeclEnd
, InlineLoc
);
1837 return ParseSimpleDeclaration(Context
, DeclEnd
, DeclAttrs
, DeclSpecAttrs
,
1838 true, nullptr, DeclSpecStart
);
1840 case tok::kw_cbuffer
:
1841 case tok::kw_tbuffer
:
1842 SingleDecl
= ParseHLSLBuffer(DeclEnd
);
1844 case tok::kw_namespace
:
1845 ProhibitAttributes(DeclAttrs
);
1846 ProhibitAttributes(DeclSpecAttrs
);
1847 return ParseNamespace(Context
, DeclEnd
);
1848 case tok::kw_using
: {
1849 ParsedAttributes
Attrs(AttrFactory
);
1850 takeAndConcatenateAttrs(DeclAttrs
, DeclSpecAttrs
, Attrs
);
1851 return ParseUsingDirectiveOrDeclaration(Context
, ParsedTemplateInfo(),
1854 case tok::kw_static_assert
:
1855 case tok::kw__Static_assert
:
1856 ProhibitAttributes(DeclAttrs
);
1857 ProhibitAttributes(DeclSpecAttrs
);
1858 SingleDecl
= ParseStaticAssertDeclaration(DeclEnd
);
1861 return ParseSimpleDeclaration(Context
, DeclEnd
, DeclAttrs
, DeclSpecAttrs
,
1862 true, nullptr, DeclSpecStart
);
1865 // This routine returns a DeclGroup, if the thing we parsed only contains a
1866 // single decl, convert it now.
1867 return Actions
.ConvertDeclToDeclGroup(SingleDecl
);
1870 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1871 /// declaration-specifiers init-declarator-list[opt] ';'
1872 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1873 /// init-declarator-list ';'
1874 ///[C90/C++]init-declarator-list ';' [TODO]
1875 /// [OMP] threadprivate-directive
1876 /// [OMP] allocate-directive [TODO]
1878 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1879 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1881 /// If RequireSemi is false, this does not check for a ';' at the end of the
1882 /// declaration. If it is true, it checks for and eats it.
1884 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1885 /// of a simple-declaration. If we find that we are, we also parse the
1886 /// for-range-initializer, and place it here.
1888 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1889 /// the Declaration. The SourceLocation for this Decl is set to
1890 /// DeclSpecStart if DeclSpecStart is non-null.
1891 Parser::DeclGroupPtrTy
Parser::ParseSimpleDeclaration(
1892 DeclaratorContext Context
, SourceLocation
&DeclEnd
,
1893 ParsedAttributes
&DeclAttrs
, ParsedAttributes
&DeclSpecAttrs
,
1894 bool RequireSemi
, ForRangeInit
*FRI
, SourceLocation
*DeclSpecStart
) {
1895 // Need to retain these for diagnostics before we add them to the DeclSepc.
1896 ParsedAttributesView OriginalDeclSpecAttrs
;
1897 OriginalDeclSpecAttrs
.addAll(DeclSpecAttrs
.begin(), DeclSpecAttrs
.end());
1898 OriginalDeclSpecAttrs
.Range
= DeclSpecAttrs
.Range
;
1900 // Parse the common declaration-specifiers piece.
1901 ParsingDeclSpec
DS(*this);
1902 DS
.takeAttributesFrom(DeclSpecAttrs
);
1904 DeclSpecContext DSContext
= getDeclSpecContextFromDeclaratorContext(Context
);
1905 ParseDeclarationSpecifiers(DS
, ParsedTemplateInfo(), AS_none
, DSContext
);
1907 // If we had a free-standing type definition with a missing semicolon, we
1908 // may get this far before the problem becomes obvious.
1909 if (DS
.hasTagDefinition() &&
1910 DiagnoseMissingSemiAfterTagDefinition(DS
, AS_none
, DSContext
))
1913 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1914 // declaration-specifiers init-declarator-list[opt] ';'
1915 if (Tok
.is(tok::semi
)) {
1916 ProhibitAttributes(DeclAttrs
);
1917 DeclEnd
= Tok
.getLocation();
1918 if (RequireSemi
) ConsumeToken();
1919 RecordDecl
*AnonRecord
= nullptr;
1920 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(
1921 getCurScope(), AS_none
, DS
, ParsedAttributesView::none(), AnonRecord
);
1922 DS
.complete(TheDecl
);
1924 Decl
* decls
[] = {AnonRecord
, TheDecl
};
1925 return Actions
.BuildDeclaratorGroup(decls
);
1927 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
1931 DS
.SetRangeStart(*DeclSpecStart
);
1933 return ParseDeclGroup(DS
, Context
, DeclAttrs
, &DeclEnd
, FRI
);
1936 /// Returns true if this might be the start of a declarator, or a common typo
1937 /// for a declarator.
1938 bool Parser::MightBeDeclarator(DeclaratorContext Context
) {
1939 switch (Tok
.getKind()) {
1940 case tok::annot_cxxscope
:
1941 case tok::annot_template_id
:
1943 case tok::code_completion
:
1944 case tok::coloncolon
:
1946 case tok::kw___attribute
:
1947 case tok::kw_operator
:
1954 return getLangOpts().CPlusPlus
;
1956 case tok::l_square
: // Might be an attribute on an unnamed bit-field.
1957 return Context
== DeclaratorContext::Member
&& getLangOpts().CPlusPlus11
&&
1958 NextToken().is(tok::l_square
);
1960 case tok::colon
: // Might be a typo for '::' or an unnamed bit-field.
1961 return Context
== DeclaratorContext::Member
|| getLangOpts().CPlusPlus
;
1963 case tok::identifier
:
1964 switch (NextToken().getKind()) {
1965 case tok::code_completion
:
1966 case tok::coloncolon
:
1969 case tok::equalequal
: // Might be a typo for '='.
1970 case tok::kw_alignas
:
1972 case tok::kw___attribute
:
1984 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1985 // and in block scope it's probably a label. Inside a class definition,
1986 // this is a bit-field.
1987 return Context
== DeclaratorContext::Member
||
1988 (getLangOpts().CPlusPlus
&& Context
== DeclaratorContext::File
);
1990 case tok::identifier
: // Possible virt-specifier.
1991 return getLangOpts().CPlusPlus11
&& isCXX11VirtSpecifier(NextToken());
2002 /// Skip until we reach something which seems like a sensible place to pick
2003 /// up parsing after a malformed declaration. This will sometimes stop sooner
2004 /// than SkipUntil(tok::r_brace) would, but will never stop later.
2005 void Parser::SkipMalformedDecl() {
2007 switch (Tok
.getKind()) {
2009 // Skip until matching }, then stop. We've probably skipped over
2010 // a malformed class or function definition or similar.
2012 SkipUntil(tok::r_brace
);
2013 if (Tok
.isOneOf(tok::comma
, tok::l_brace
, tok::kw_try
)) {
2014 // This declaration isn't over yet. Keep skipping.
2017 TryConsumeToken(tok::semi
);
2022 SkipUntil(tok::r_square
);
2027 SkipUntil(tok::r_paren
);
2037 case tok::kw_inline
:
2038 // 'inline namespace' at the start of a line is almost certainly
2039 // a good place to pick back up parsing, except in an Objective-C
2040 // @interface context.
2041 if (Tok
.isAtStartOfLine() && NextToken().is(tok::kw_namespace
) &&
2042 (!ParsingInObjCContainer
|| CurParsedObjCImpl
))
2046 case tok::kw_namespace
:
2047 // 'namespace' at the start of a line is almost certainly a good
2048 // place to pick back up parsing, except in an Objective-C
2049 // @interface context.
2050 if (Tok
.isAtStartOfLine() &&
2051 (!ParsingInObjCContainer
|| CurParsedObjCImpl
))
2056 // @end is very much like } in Objective-C contexts.
2057 if (NextToken().isObjCAtKeyword(tok::objc_end
) &&
2058 ParsingInObjCContainer
)
2064 // - and + probably start new method declarations in Objective-C contexts.
2065 if (Tok
.isAtStartOfLine() && ParsingInObjCContainer
)
2070 case tok::annot_module_begin
:
2071 case tok::annot_module_end
:
2072 case tok::annot_module_include
:
2083 /// ParseDeclGroup - Having concluded that this is either a function
2084 /// definition or a group of object declarations, actually parse the
2086 Parser::DeclGroupPtrTy
Parser::ParseDeclGroup(ParsingDeclSpec
&DS
,
2087 DeclaratorContext Context
,
2088 ParsedAttributes
&Attrs
,
2089 SourceLocation
*DeclEnd
,
2090 ForRangeInit
*FRI
) {
2091 // Parse the first declarator.
2092 // Consume all of the attributes from `Attrs` by moving them to our own local
2093 // list. This ensures that we will not attempt to interpret them as statement
2094 // attributes higher up the callchain.
2095 ParsedAttributes
LocalAttrs(AttrFactory
);
2096 LocalAttrs
.takeAllFrom(Attrs
);
2097 ParsingDeclarator
D(*this, DS
, LocalAttrs
, Context
);
2100 // Bail out if the first declarator didn't seem well-formed.
2101 if (!D
.hasName() && !D
.mayOmitIdentifier()) {
2102 SkipMalformedDecl();
2106 if (getLangOpts().HLSL
)
2107 MaybeParseHLSLSemantics(D
);
2109 if (Tok
.is(tok::kw_requires
))
2110 ParseTrailingRequiresClause(D
);
2112 // Save late-parsed attributes for now; they need to be parsed in the
2113 // appropriate function scope after the function Decl has been constructed.
2114 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2115 LateParsedAttrList
LateParsedAttrs(true);
2116 if (D
.isFunctionDeclarator()) {
2117 MaybeParseGNUAttributes(D
, &LateParsedAttrs
);
2119 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2120 // attribute. If we find the keyword here, tell the user to put it
2121 // at the start instead.
2122 if (Tok
.is(tok::kw__Noreturn
)) {
2123 SourceLocation Loc
= ConsumeToken();
2124 const char *PrevSpec
;
2127 // We can offer a fixit if it's valid to mark this function as _Noreturn
2128 // and we don't have any other declarators in this declaration.
2129 bool Fixit
= !DS
.setFunctionSpecNoreturn(Loc
, PrevSpec
, DiagID
);
2130 MaybeParseGNUAttributes(D
, &LateParsedAttrs
);
2131 Fixit
&= Tok
.isOneOf(tok::semi
, tok::l_brace
, tok::kw_try
);
2133 Diag(Loc
, diag::err_c11_noreturn_misplaced
)
2134 << (Fixit
? FixItHint::CreateRemoval(Loc
) : FixItHint())
2135 << (Fixit
? FixItHint::CreateInsertion(D
.getBeginLoc(), "_Noreturn ")
2139 // Check to see if we have a function *definition* which must have a body.
2140 if (Tok
.is(tok::equal
) && NextToken().is(tok::code_completion
)) {
2142 Actions
.CodeCompleteAfterFunctionEquals(D
);
2145 // We're at the point where the parsing of function declarator is finished.
2147 // A common error is that users accidently add a virtual specifier
2148 // (e.g. override) in an out-line method definition.
2149 // We attempt to recover by stripping all these specifiers coming after
2151 while (auto Specifier
= isCXX11VirtSpecifier()) {
2152 Diag(Tok
, diag::err_virt_specifier_outside_class
)
2153 << VirtSpecifiers::getSpecifierName(Specifier
)
2154 << FixItHint::CreateRemoval(Tok
.getLocation());
2157 // Look at the next token to make sure that this isn't a function
2158 // declaration. We have to check this because __attribute__ might be the
2159 // start of a function definition in GCC-extended K&R C.
2160 if (!isDeclarationAfterDeclarator()) {
2162 // Function definitions are only allowed at file scope and in C++ classes.
2163 // The C++ inline method definition case is handled elsewhere, so we only
2164 // need to handle the file scope definition case.
2165 if (Context
== DeclaratorContext::File
) {
2166 if (isStartOfFunctionDefinition(D
)) {
2167 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
2168 Diag(Tok
, diag::err_function_declared_typedef
);
2170 // Recover by treating the 'typedef' as spurious.
2171 DS
.ClearStorageClassSpecs();
2174 Decl
*TheDecl
= ParseFunctionDefinition(D
, ParsedTemplateInfo(),
2176 return Actions
.ConvertDeclToDeclGroup(TheDecl
);
2179 if (isDeclarationSpecifier(ImplicitTypenameContext::No
)) {
2180 // If there is an invalid declaration specifier right after the
2181 // function prototype, then we must be in a missing semicolon case
2182 // where this isn't actually a body. Just fall through into the code
2183 // that handles it as a prototype, and let the top-level code handle
2184 // the erroneous declspec where it would otherwise expect a comma or
2187 Diag(Tok
, diag::err_expected_fn_body
);
2188 SkipUntil(tok::semi
);
2192 if (Tok
.is(tok::l_brace
)) {
2193 Diag(Tok
, diag::err_function_definition_not_allowed
);
2194 SkipMalformedDecl();
2201 if (ParseAsmAttributesAfterDeclarator(D
))
2204 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2205 // must parse and analyze the for-range-initializer before the declaration is
2208 // Handle the Objective-C for-in loop variable similarly, although we
2209 // don't need to parse the container in advance.
2210 if (FRI
&& (Tok
.is(tok::colon
) || isTokIdentifier_in())) {
2211 bool IsForRangeLoop
= false;
2212 if (TryConsumeToken(tok::colon
, FRI
->ColonLoc
)) {
2213 IsForRangeLoop
= true;
2214 if (getLangOpts().OpenMP
)
2215 Actions
.startOpenMPCXXRangeFor();
2216 if (Tok
.is(tok::l_brace
))
2217 FRI
->RangeExpr
= ParseBraceInitializer();
2219 FRI
->RangeExpr
= ParseExpression();
2222 Decl
*ThisDecl
= Actions
.ActOnDeclarator(getCurScope(), D
);
2223 if (IsForRangeLoop
) {
2224 Actions
.ActOnCXXForRangeDecl(ThisDecl
);
2227 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(ThisDecl
))
2228 VD
->setObjCForDecl(true);
2230 Actions
.FinalizeDeclaration(ThisDecl
);
2231 D
.complete(ThisDecl
);
2232 return Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, ThisDecl
);
2235 SmallVector
<Decl
*, 8> DeclsInGroup
;
2236 Decl
*FirstDecl
= ParseDeclarationAfterDeclaratorAndAttributes(
2237 D
, ParsedTemplateInfo(), FRI
);
2238 if (LateParsedAttrs
.size() > 0)
2239 ParseLexedAttributeList(LateParsedAttrs
, FirstDecl
, true, false);
2240 D
.complete(FirstDecl
);
2242 DeclsInGroup
.push_back(FirstDecl
);
2244 bool ExpectSemi
= Context
!= DeclaratorContext::ForInit
;
2246 // If we don't have a comma, it is either the end of the list (a ';') or an
2248 SourceLocation CommaLoc
;
2249 while (TryConsumeToken(tok::comma
, CommaLoc
)) {
2250 if (Tok
.isAtStartOfLine() && ExpectSemi
&& !MightBeDeclarator(Context
)) {
2251 // This comma was followed by a line-break and something which can't be
2252 // the start of a declarator. The comma was probably a typo for a
2254 Diag(CommaLoc
, diag::err_expected_semi_declaration
)
2255 << FixItHint::CreateReplacement(CommaLoc
, ";");
2260 // Parse the next declarator.
2262 D
.setCommaLoc(CommaLoc
);
2264 // Accept attributes in an init-declarator. In the first declarator in a
2265 // declaration, these would be part of the declspec. In subsequent
2266 // declarators, they become part of the declarator itself, so that they
2267 // don't apply to declarators after *this* one. Examples:
2268 // short __attribute__((common)) var; -> declspec
2269 // short var __attribute__((common)); -> declarator
2270 // short x, __attribute__((common)) var; -> declarator
2271 MaybeParseGNUAttributes(D
);
2273 // MSVC parses but ignores qualifiers after the comma as an extension.
2274 if (getLangOpts().MicrosoftExt
)
2275 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2279 if (getLangOpts().HLSL
)
2280 MaybeParseHLSLSemantics(D
);
2282 if (!D
.isInvalidType()) {
2283 // C++2a [dcl.decl]p1
2285 // declarator initializer[opt]
2286 // declarator requires-clause
2287 if (Tok
.is(tok::kw_requires
))
2288 ParseTrailingRequiresClause(D
);
2289 Decl
*ThisDecl
= ParseDeclarationAfterDeclarator(D
);
2290 D
.complete(ThisDecl
);
2292 DeclsInGroup
.push_back(ThisDecl
);
2297 *DeclEnd
= Tok
.getLocation();
2299 if (ExpectSemi
&& ExpectAndConsumeSemi(
2300 Context
== DeclaratorContext::File
2301 ? diag::err_invalid_token_after_toplevel_declarator
2302 : diag::err_expected_semi_declaration
)) {
2303 // Okay, there was no semicolon and one was expected. If we see a
2304 // declaration specifier, just assume it was missing and continue parsing.
2305 // Otherwise things are very confused and we skip to recover.
2306 if (!isDeclarationSpecifier(ImplicitTypenameContext::No
)) {
2307 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
2308 TryConsumeToken(tok::semi
);
2312 return Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
);
2315 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2316 /// declarator. Returns true on an error.
2317 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator
&D
) {
2318 // If a simple-asm-expr is present, parse it.
2319 if (Tok
.is(tok::kw_asm
)) {
2321 ExprResult
AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc
));
2322 if (AsmLabel
.isInvalid()) {
2323 SkipUntil(tok::semi
, StopBeforeMatch
);
2327 D
.setAsmLabel(AsmLabel
.get());
2331 MaybeParseGNUAttributes(D
);
2335 /// Parse 'declaration' after parsing 'declaration-specifiers
2336 /// declarator'. This method parses the remainder of the declaration
2337 /// (including any attributes or initializer, among other things) and
2338 /// finalizes the declaration.
2340 /// init-declarator: [C99 6.7]
2342 /// declarator '=' initializer
2343 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2344 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2345 /// [C++] declarator initializer[opt]
2347 /// [C++] initializer:
2348 /// [C++] '=' initializer-clause
2349 /// [C++] '(' expression-list ')'
2350 /// [C++0x] '=' 'default' [TODO]
2351 /// [C++0x] '=' 'delete'
2352 /// [C++0x] braced-init-list
2354 /// According to the standard grammar, =default and =delete are function
2355 /// definitions, but that definitely doesn't fit with the parser here.
2357 Decl
*Parser::ParseDeclarationAfterDeclarator(
2358 Declarator
&D
, const ParsedTemplateInfo
&TemplateInfo
) {
2359 if (ParseAsmAttributesAfterDeclarator(D
))
2362 return ParseDeclarationAfterDeclaratorAndAttributes(D
, TemplateInfo
);
2365 Decl
*Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2366 Declarator
&D
, const ParsedTemplateInfo
&TemplateInfo
, ForRangeInit
*FRI
) {
2367 // RAII type used to track whether we're inside an initializer.
2368 struct InitializerScopeRAII
{
2373 InitializerScopeRAII(Parser
&P
, Declarator
&D
, Decl
*ThisDecl
)
2374 : P(P
), D(D
), ThisDecl(ThisDecl
) {
2375 if (ThisDecl
&& P
.getLangOpts().CPlusPlus
) {
2377 if (D
.getCXXScopeSpec().isSet()) {
2379 S
= P
.getCurScope();
2381 P
.Actions
.ActOnCXXEnterDeclInitializer(S
, ThisDecl
);
2384 ~InitializerScopeRAII() { pop(); }
2386 if (ThisDecl
&& P
.getLangOpts().CPlusPlus
) {
2388 if (D
.getCXXScopeSpec().isSet())
2389 S
= P
.getCurScope();
2390 P
.Actions
.ActOnCXXExitDeclInitializer(S
, ThisDecl
);
2398 enum class InitKind
{ Uninitialized
, Equal
, CXXDirect
, CXXBraced
};
2399 InitKind TheInitKind
;
2400 // If a '==' or '+=' is found, suggest a fixit to '='.
2401 if (isTokenEqualOrEqualTypo())
2402 TheInitKind
= InitKind::Equal
;
2403 else if (Tok
.is(tok::l_paren
))
2404 TheInitKind
= InitKind::CXXDirect
;
2405 else if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
) &&
2406 (!CurParsedObjCImpl
|| !D
.isFunctionDeclarator()))
2407 TheInitKind
= InitKind::CXXBraced
;
2409 TheInitKind
= InitKind::Uninitialized
;
2410 if (TheInitKind
!= InitKind::Uninitialized
)
2411 D
.setHasInitializer();
2413 // Inform Sema that we just parsed this declarator.
2414 Decl
*ThisDecl
= nullptr;
2415 Decl
*OuterDecl
= nullptr;
2416 switch (TemplateInfo
.Kind
) {
2417 case ParsedTemplateInfo::NonTemplate
:
2418 ThisDecl
= Actions
.ActOnDeclarator(getCurScope(), D
);
2421 case ParsedTemplateInfo::Template
:
2422 case ParsedTemplateInfo::ExplicitSpecialization
: {
2423 ThisDecl
= Actions
.ActOnTemplateDeclarator(getCurScope(),
2424 *TemplateInfo
.TemplateParams
,
2426 if (VarTemplateDecl
*VT
= dyn_cast_or_null
<VarTemplateDecl
>(ThisDecl
)) {
2427 // Re-direct this decl to refer to the templated decl so that we can
2429 ThisDecl
= VT
->getTemplatedDecl();
2434 case ParsedTemplateInfo::ExplicitInstantiation
: {
2435 if (Tok
.is(tok::semi
)) {
2436 DeclResult ThisRes
= Actions
.ActOnExplicitInstantiation(
2437 getCurScope(), TemplateInfo
.ExternLoc
, TemplateInfo
.TemplateLoc
, D
);
2438 if (ThisRes
.isInvalid()) {
2439 SkipUntil(tok::semi
, StopBeforeMatch
);
2442 ThisDecl
= ThisRes
.get();
2444 // FIXME: This check should be for a variable template instantiation only.
2446 // Check that this is a valid instantiation
2447 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
2448 // If the declarator-id is not a template-id, issue a diagnostic and
2449 // recover by ignoring the 'template' keyword.
2450 Diag(Tok
, diag::err_template_defn_explicit_instantiation
)
2451 << 2 << FixItHint::CreateRemoval(TemplateInfo
.TemplateLoc
);
2452 ThisDecl
= Actions
.ActOnDeclarator(getCurScope(), D
);
2454 SourceLocation LAngleLoc
=
2455 PP
.getLocForEndOfToken(TemplateInfo
.TemplateLoc
);
2456 Diag(D
.getIdentifierLoc(),
2457 diag::err_explicit_instantiation_with_definition
)
2458 << SourceRange(TemplateInfo
.TemplateLoc
)
2459 << FixItHint::CreateInsertion(LAngleLoc
, "<>");
2461 // Recover as if it were an explicit specialization.
2462 TemplateParameterLists FakedParamLists
;
2463 FakedParamLists
.push_back(Actions
.ActOnTemplateParameterList(
2464 0, SourceLocation(), TemplateInfo
.TemplateLoc
, LAngleLoc
,
2465 std::nullopt
, LAngleLoc
, nullptr));
2468 Actions
.ActOnTemplateDeclarator(getCurScope(), FakedParamLists
, D
);
2475 switch (TheInitKind
) {
2476 // Parse declarator '=' initializer.
2477 case InitKind::Equal
: {
2478 SourceLocation EqualLoc
= ConsumeToken();
2480 if (Tok
.is(tok::kw_delete
)) {
2481 if (D
.isFunctionDeclarator())
2482 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration
)
2485 Diag(ConsumeToken(), diag::err_deleted_non_function
);
2486 } else if (Tok
.is(tok::kw_default
)) {
2487 if (D
.isFunctionDeclarator())
2488 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration
)
2491 Diag(ConsumeToken(), diag::err_default_special_members
)
2492 << getLangOpts().CPlusPlus20
;
2494 InitializerScopeRAII
InitScope(*this, D
, ThisDecl
);
2496 if (Tok
.is(tok::code_completion
)) {
2498 Actions
.CodeCompleteInitializer(getCurScope(), ThisDecl
);
2499 Actions
.FinalizeDeclaration(ThisDecl
);
2503 PreferredType
.enterVariableInit(Tok
.getLocation(), ThisDecl
);
2504 ExprResult Init
= ParseInitializer();
2506 // If this is the only decl in (possibly) range based for statement,
2507 // our best guess is that the user meant ':' instead of '='.
2508 if (Tok
.is(tok::r_paren
) && FRI
&& D
.isFirstDeclarator()) {
2509 Diag(EqualLoc
, diag::err_single_decl_assign_in_for_range
)
2510 << FixItHint::CreateReplacement(EqualLoc
, ":");
2511 // We are trying to stop parser from looking for ';' in this for
2512 // statement, therefore preventing spurious errors to be issued.
2513 FRI
->ColonLoc
= EqualLoc
;
2515 FRI
->RangeExpr
= Init
;
2520 if (Init
.isInvalid()) {
2521 SmallVector
<tok::TokenKind
, 2> StopTokens
;
2522 StopTokens
.push_back(tok::comma
);
2523 if (D
.getContext() == DeclaratorContext::ForInit
||
2524 D
.getContext() == DeclaratorContext::SelectionInit
)
2525 StopTokens
.push_back(tok::r_paren
);
2526 SkipUntil(StopTokens
, StopAtSemi
| StopBeforeMatch
);
2527 Actions
.ActOnInitializerError(ThisDecl
);
2529 Actions
.AddInitializerToDecl(ThisDecl
, Init
.get(),
2530 /*DirectInit=*/false);
2534 case InitKind::CXXDirect
: {
2535 // Parse C++ direct initializer: '(' expression-list ')'
2536 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2541 InitializerScopeRAII
InitScope(*this, D
, ThisDecl
);
2543 auto ThisVarDecl
= dyn_cast_or_null
<VarDecl
>(ThisDecl
);
2544 auto RunSignatureHelp
= [&]() {
2545 QualType PreferredType
= Actions
.ProduceConstructorSignatureHelp(
2546 ThisVarDecl
->getType()->getCanonicalTypeInternal(),
2547 ThisDecl
->getLocation(), Exprs
, T
.getOpenLocation(),
2549 CalledSignatureHelp
= true;
2550 return PreferredType
;
2552 auto SetPreferredType
= [&] {
2553 PreferredType
.enterFunctionArgument(Tok
.getLocation(), RunSignatureHelp
);
2556 llvm::function_ref
<void()> ExpressionStarts
;
2558 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2559 // VarDecl. This is an error and it is reported in a call to
2560 // Actions.ActOnInitializerError(). However, we call
2561 // ProduceConstructorSignatureHelp only on VarDecls.
2562 ExpressionStarts
= SetPreferredType
;
2564 if (ParseExpressionList(Exprs
, ExpressionStarts
)) {
2565 if (ThisVarDecl
&& PP
.isCodeCompletionReached() && !CalledSignatureHelp
) {
2566 Actions
.ProduceConstructorSignatureHelp(
2567 ThisVarDecl
->getType()->getCanonicalTypeInternal(),
2568 ThisDecl
->getLocation(), Exprs
, T
.getOpenLocation(),
2570 CalledSignatureHelp
= true;
2572 Actions
.ActOnInitializerError(ThisDecl
);
2573 SkipUntil(tok::r_paren
, StopAtSemi
);
2579 ExprResult Initializer
= Actions
.ActOnParenListExpr(T
.getOpenLocation(),
2580 T
.getCloseLocation(),
2582 Actions
.AddInitializerToDecl(ThisDecl
, Initializer
.get(),
2583 /*DirectInit=*/true);
2587 case InitKind::CXXBraced
: {
2588 // Parse C++0x braced-init-list.
2589 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
2591 InitializerScopeRAII
InitScope(*this, D
, ThisDecl
);
2593 PreferredType
.enterVariableInit(Tok
.getLocation(), ThisDecl
);
2594 ExprResult
Init(ParseBraceInitializer());
2598 if (Init
.isInvalid()) {
2599 Actions
.ActOnInitializerError(ThisDecl
);
2601 Actions
.AddInitializerToDecl(ThisDecl
, Init
.get(), /*DirectInit=*/true);
2604 case InitKind::Uninitialized
: {
2605 Actions
.ActOnUninitializedDecl(ThisDecl
);
2610 Actions
.FinalizeDeclaration(ThisDecl
);
2611 return OuterDecl
? OuterDecl
: ThisDecl
;
2614 /// ParseSpecifierQualifierList
2615 /// specifier-qualifier-list:
2616 /// type-specifier specifier-qualifier-list[opt]
2617 /// type-qualifier specifier-qualifier-list[opt]
2618 /// [GNU] attributes specifier-qualifier-list[opt]
2620 void Parser::ParseSpecifierQualifierList(
2621 DeclSpec
&DS
, ImplicitTypenameContext AllowImplicitTypename
,
2622 AccessSpecifier AS
, DeclSpecContext DSC
) {
2623 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2624 /// parse declaration-specifiers and complain about extra stuff.
2625 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2626 ParseDeclarationSpecifiers(DS
, ParsedTemplateInfo(), AS
, DSC
, nullptr,
2627 AllowImplicitTypename
);
2629 // Validate declspec for type-name.
2630 unsigned Specs
= DS
.getParsedSpecifiers();
2631 if (isTypeSpecifier(DSC
) && !DS
.hasTypeSpecifier()) {
2632 Diag(Tok
, diag::err_expected_type
);
2633 DS
.SetTypeSpecError();
2634 } else if (Specs
== DeclSpec::PQ_None
&& !DS
.hasAttributes()) {
2635 Diag(Tok
, diag::err_typename_requires_specqual
);
2636 if (!DS
.hasTypeSpecifier())
2637 DS
.SetTypeSpecError();
2640 // Issue diagnostic and remove storage class if present.
2641 if (Specs
& DeclSpec::PQ_StorageClassSpecifier
) {
2642 if (DS
.getStorageClassSpecLoc().isValid())
2643 Diag(DS
.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass
);
2645 Diag(DS
.getThreadStorageClassSpecLoc(),
2646 diag::err_typename_invalid_storageclass
);
2647 DS
.ClearStorageClassSpecs();
2650 // Issue diagnostic and remove function specifier if present.
2651 if (Specs
& DeclSpec::PQ_FunctionSpecifier
) {
2652 if (DS
.isInlineSpecified())
2653 Diag(DS
.getInlineSpecLoc(), diag::err_typename_invalid_functionspec
);
2654 if (DS
.isVirtualSpecified())
2655 Diag(DS
.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec
);
2656 if (DS
.hasExplicitSpecifier())
2657 Diag(DS
.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec
);
2658 if (DS
.isNoreturnSpecified())
2659 Diag(DS
.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec
);
2660 DS
.ClearFunctionSpecs();
2663 // Issue diagnostic and remove constexpr specifier if present.
2664 if (DS
.hasConstexprSpecifier() && DSC
!= DeclSpecContext::DSC_condition
) {
2665 Diag(DS
.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr
)
2666 << static_cast<int>(DS
.getConstexprSpecifier());
2667 DS
.ClearConstexprSpec();
2671 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2672 /// specified token is valid after the identifier in a declarator which
2673 /// immediately follows the declspec. For example, these things are valid:
2675 /// int x [ 4]; // direct-declarator
2676 /// int x ( int y); // direct-declarator
2677 /// int(int x ) // direct-declarator
2678 /// int x ; // simple-declaration
2679 /// int x = 17; // init-declarator-list
2680 /// int x , y; // init-declarator-list
2681 /// int x __asm__ ("foo"); // init-declarator-list
2682 /// int x : 4; // struct-declarator
2683 /// int x { 5}; // C++'0x unified initializers
2685 /// This is not, because 'x' does not immediately follow the declspec (though
2686 /// ')' happens to be valid anyway).
2689 static bool isValidAfterIdentifierInDeclarator(const Token
&T
) {
2690 return T
.isOneOf(tok::l_square
, tok::l_paren
, tok::r_paren
, tok::semi
,
2691 tok::comma
, tok::equal
, tok::kw_asm
, tok::l_brace
,
2695 /// ParseImplicitInt - This method is called when we have an non-typename
2696 /// identifier in a declspec (which normally terminates the decl spec) when
2697 /// the declspec has no type specifier. In this case, the declspec is either
2698 /// malformed or is "implicit int" (in K&R and C89).
2700 /// This method handles diagnosing this prettily and returns false if the
2701 /// declspec is done being processed. If it recovers and thinks there may be
2702 /// other pieces of declspec after it, it returns true.
2704 bool Parser::ParseImplicitInt(DeclSpec
&DS
, CXXScopeSpec
*SS
,
2705 const ParsedTemplateInfo
&TemplateInfo
,
2706 AccessSpecifier AS
, DeclSpecContext DSC
,
2707 ParsedAttributes
&Attrs
) {
2708 assert(Tok
.is(tok::identifier
) && "should have identifier");
2710 SourceLocation Loc
= Tok
.getLocation();
2711 // If we see an identifier that is not a type name, we normally would
2712 // parse it as the identifier being declared. However, when a typename
2713 // is typo'd or the definition is not included, this will incorrectly
2714 // parse the typename as the identifier name and fall over misparsing
2715 // later parts of the diagnostic.
2717 // As such, we try to do some look-ahead in cases where this would
2718 // otherwise be an "implicit-int" case to see if this is invalid. For
2719 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2720 // an identifier with implicit int, we'd get a parse error because the
2721 // next token is obviously invalid for a type. Parse these as a case
2722 // with an invalid type specifier.
2723 assert(!DS
.hasTypeSpecifier() && "Type specifier checked above");
2725 // Since we know that this either implicit int (which is rare) or an
2726 // error, do lookahead to try to do better recovery. This never applies
2727 // within a type specifier. Outside of C++, we allow this even if the
2728 // language doesn't "officially" support implicit int -- we support
2729 // implicit int as an extension in some language modes.
2730 if (!isTypeSpecifier(DSC
) && getLangOpts().isImplicitIntAllowed() &&
2731 isValidAfterIdentifierInDeclarator(NextToken())) {
2732 // If this token is valid for implicit int, e.g. "static x = 4", then
2733 // we just avoid eating the identifier, so it will be parsed as the
2734 // identifier in the declarator.
2738 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2739 // for incomplete declarations such as `pipe p`.
2740 if (getLangOpts().OpenCLCPlusPlus
&& DS
.isTypeSpecPipe())
2743 if (getLangOpts().CPlusPlus
&&
2744 DS
.getStorageClassSpec() == DeclSpec::SCS_auto
) {
2745 // Don't require a type specifier if we have the 'auto' storage class
2746 // specifier in C++98 -- we'll promote it to a type specifier.
2748 AnnotateScopeToken(*SS
, /*IsNewAnnotation*/false);
2752 if (getLangOpts().CPlusPlus
&& (!SS
|| SS
->isEmpty()) &&
2753 getLangOpts().MSVCCompat
) {
2754 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2755 // Give Sema a chance to recover if we are in a template with dependent base
2757 if (ParsedType T
= Actions
.ActOnMSVCUnknownTypeName(
2758 *Tok
.getIdentifierInfo(), Tok
.getLocation(),
2759 DSC
== DeclSpecContext::DSC_template_type_arg
)) {
2760 const char *PrevSpec
;
2762 DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
, DiagID
, T
,
2763 Actions
.getASTContext().getPrintingPolicy());
2764 DS
.SetRangeEnd(Tok
.getLocation());
2770 // Otherwise, if we don't consume this token, we are going to emit an
2771 // error anyway. Try to recover from various common problems. Check
2772 // to see if this was a reference to a tag name without a tag specified.
2773 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2775 // C++ doesn't need this, and isTagName doesn't take SS.
2776 if (SS
== nullptr) {
2777 const char *TagName
= nullptr, *FixitTagName
= nullptr;
2778 tok::TokenKind TagKind
= tok::unknown
;
2780 switch (Actions
.isTagName(*Tok
.getIdentifierInfo(), getCurScope())) {
2782 case DeclSpec::TST_enum
:
2783 TagName
="enum" ; FixitTagName
= "enum " ; TagKind
=tok::kw_enum
;break;
2784 case DeclSpec::TST_union
:
2785 TagName
="union" ; FixitTagName
= "union " ;TagKind
=tok::kw_union
;break;
2786 case DeclSpec::TST_struct
:
2787 TagName
="struct"; FixitTagName
= "struct ";TagKind
=tok::kw_struct
;break;
2788 case DeclSpec::TST_interface
:
2789 TagName
="__interface"; FixitTagName
= "__interface ";
2790 TagKind
=tok::kw___interface
;break;
2791 case DeclSpec::TST_class
:
2792 TagName
="class" ; FixitTagName
= "class " ;TagKind
=tok::kw_class
;break;
2796 IdentifierInfo
*TokenName
= Tok
.getIdentifierInfo();
2797 LookupResult
R(Actions
, TokenName
, SourceLocation(),
2798 Sema::LookupOrdinaryName
);
2800 Diag(Loc
, diag::err_use_of_tag_name_without_tag
)
2801 << TokenName
<< TagName
<< getLangOpts().CPlusPlus
2802 << FixItHint::CreateInsertion(Tok
.getLocation(), FixitTagName
);
2804 if (Actions
.LookupParsedName(R
, getCurScope(), SS
)) {
2805 for (LookupResult::iterator I
= R
.begin(), IEnd
= R
.end();
2807 Diag((*I
)->getLocation(), diag::note_decl_hiding_tag_type
)
2808 << TokenName
<< TagName
;
2811 // Parse this as a tag as if the missing tag were present.
2812 if (TagKind
== tok::kw_enum
)
2813 ParseEnumSpecifier(Loc
, DS
, TemplateInfo
, AS
,
2814 DeclSpecContext::DSC_normal
);
2816 ParseClassSpecifier(TagKind
, Loc
, DS
, TemplateInfo
, AS
,
2817 /*EnteringContext*/ false,
2818 DeclSpecContext::DSC_normal
, Attrs
);
2823 // Determine whether this identifier could plausibly be the name of something
2824 // being declared (with a missing type).
2825 if (!isTypeSpecifier(DSC
) && (!SS
|| DSC
== DeclSpecContext::DSC_top_level
||
2826 DSC
== DeclSpecContext::DSC_class
)) {
2827 // Look ahead to the next token to try to figure out what this declaration
2828 // was supposed to be.
2829 switch (NextToken().getKind()) {
2830 case tok::l_paren
: {
2831 // static x(4); // 'x' is not a type
2832 // x(int n); // 'x' is not a type
2833 // x (*p)[]; // 'x' is a type
2835 // Since we're in an error case, we can afford to perform a tentative
2836 // parse to determine which case we're in.
2837 TentativeParsingAction
PA(*this);
2839 TPResult TPR
= TryParseDeclarator(/*mayBeAbstract*/false);
2842 if (TPR
!= TPResult::False
) {
2843 // The identifier is followed by a parenthesized declarator.
2844 // It's supposed to be a type.
2848 // If we're in a context where we could be declaring a constructor,
2849 // check whether this is a constructor declaration with a bogus name.
2850 if (DSC
== DeclSpecContext::DSC_class
||
2851 (DSC
== DeclSpecContext::DSC_top_level
&& SS
)) {
2852 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
2853 if (Actions
.isCurrentClassNameTypo(II
, SS
)) {
2854 Diag(Loc
, diag::err_constructor_bad_name
)
2855 << Tok
.getIdentifierInfo() << II
2856 << FixItHint::CreateReplacement(Tok
.getLocation(), II
->getName());
2857 Tok
.setIdentifierInfo(II
);
2869 // This looks like a variable or function declaration. The type is
2870 // probably missing. We're done parsing decl-specifiers.
2871 // But only if we are not in a function prototype scope.
2872 if (getCurScope()->isFunctionPrototypeScope())
2875 AnnotateScopeToken(*SS
, /*IsNewAnnotation*/false);
2879 // This is probably supposed to be a type. This includes cases like:
2881 // struct S { unsigned : 4; };
2886 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2887 // and attempt to recover.
2889 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
2890 bool IsTemplateName
= getLangOpts().CPlusPlus
&& NextToken().is(tok::less
);
2891 Actions
.DiagnoseUnknownTypeName(II
, Loc
, getCurScope(), SS
, T
,
2894 // The action has suggested that the type T could be used. Set that as
2895 // the type in the declaration specifiers, consume the would-be type
2896 // name token, and we're done.
2897 const char *PrevSpec
;
2899 DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
, DiagID
, T
,
2900 Actions
.getASTContext().getPrintingPolicy());
2901 DS
.SetRangeEnd(Tok
.getLocation());
2903 // There may be other declaration specifiers after this.
2905 } else if (II
!= Tok
.getIdentifierInfo()) {
2906 // If no type was suggested, the correction is to a keyword
2907 Tok
.setKind(II
->getTokenID());
2908 // There may be other declaration specifiers after this.
2912 // Otherwise, the action had no suggestion for us. Mark this as an error.
2913 DS
.SetTypeSpecError();
2914 DS
.SetRangeEnd(Tok
.getLocation());
2917 // Eat any following template arguments.
2918 if (IsTemplateName
) {
2919 SourceLocation LAngle
, RAngle
;
2920 TemplateArgList Args
;
2921 ParseTemplateIdAfterTemplateName(true, LAngle
, Args
, RAngle
);
2924 // TODO: Could inject an invalid typedef decl in an enclosing scope to
2925 // avoid rippling error messages on subsequent uses of the same type,
2926 // could be useful if #include was forgotten.
2930 /// Determine the declaration specifier context from the declarator
2933 /// \param Context the declarator context, which is one of the
2934 /// DeclaratorContext enumerator values.
2935 Parser::DeclSpecContext
2936 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context
) {
2938 case DeclaratorContext::Member
:
2939 return DeclSpecContext::DSC_class
;
2940 case DeclaratorContext::File
:
2941 return DeclSpecContext::DSC_top_level
;
2942 case DeclaratorContext::TemplateParam
:
2943 return DeclSpecContext::DSC_template_param
;
2944 case DeclaratorContext::TemplateArg
:
2945 return DeclSpecContext::DSC_template_arg
;
2946 case DeclaratorContext::TemplateTypeArg
:
2947 return DeclSpecContext::DSC_template_type_arg
;
2948 case DeclaratorContext::TrailingReturn
:
2949 case DeclaratorContext::TrailingReturnVar
:
2950 return DeclSpecContext::DSC_trailing
;
2951 case DeclaratorContext::AliasDecl
:
2952 case DeclaratorContext::AliasTemplate
:
2953 return DeclSpecContext::DSC_alias_declaration
;
2954 case DeclaratorContext::Association
:
2955 return DeclSpecContext::DSC_association
;
2956 case DeclaratorContext::TypeName
:
2957 return DeclSpecContext::DSC_type_specifier
;
2958 case DeclaratorContext::Condition
:
2959 return DeclSpecContext::DSC_condition
;
2960 case DeclaratorContext::ConversionId
:
2961 return DeclSpecContext::DSC_conv_operator
;
2962 case DeclaratorContext::Prototype
:
2963 case DeclaratorContext::ObjCResult
:
2964 case DeclaratorContext::ObjCParameter
:
2965 case DeclaratorContext::KNRTypeList
:
2966 case DeclaratorContext::FunctionalCast
:
2967 case DeclaratorContext::Block
:
2968 case DeclaratorContext::ForInit
:
2969 case DeclaratorContext::SelectionInit
:
2970 case DeclaratorContext::CXXNew
:
2971 case DeclaratorContext::CXXCatch
:
2972 case DeclaratorContext::ObjCCatch
:
2973 case DeclaratorContext::BlockLiteral
:
2974 case DeclaratorContext::LambdaExpr
:
2975 case DeclaratorContext::LambdaExprParameter
:
2976 case DeclaratorContext::RequiresExpr
:
2977 return DeclSpecContext::DSC_normal
;
2980 llvm_unreachable("Missing DeclaratorContext case");
2983 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2985 /// FIXME: Simply returns an alignof() expression if the argument is a
2986 /// type. Ideally, the type should be propagated directly into Sema.
2989 /// [C11] constant-expression
2990 /// [C++0x] type-id ...[opt]
2991 /// [C++0x] assignment-expression ...[opt]
2992 ExprResult
Parser::ParseAlignArgument(SourceLocation Start
,
2993 SourceLocation
&EllipsisLoc
) {
2995 if (isTypeIdInParens()) {
2996 SourceLocation TypeLoc
= Tok
.getLocation();
2997 ParsedType Ty
= ParseTypeName().get();
2998 SourceRange
TypeRange(Start
, Tok
.getLocation());
2999 ER
= Actions
.ActOnUnaryExprOrTypeTraitExpr(TypeLoc
, UETT_AlignOf
, true,
3000 Ty
.getAsOpaquePtr(), TypeRange
);
3002 ER
= ParseConstantExpression();
3004 if (getLangOpts().CPlusPlus11
)
3005 TryConsumeToken(tok::ellipsis
, EllipsisLoc
);
3010 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3011 /// attribute to Attrs.
3013 /// alignment-specifier:
3014 /// [C11] '_Alignas' '(' type-id ')'
3015 /// [C11] '_Alignas' '(' constant-expression ')'
3016 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
3017 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3018 void Parser::ParseAlignmentSpecifier(ParsedAttributes
&Attrs
,
3019 SourceLocation
*EndLoc
) {
3020 assert(Tok
.isOneOf(tok::kw_alignas
, tok::kw__Alignas
) &&
3021 "Not an alignment-specifier!");
3023 IdentifierInfo
*KWName
= Tok
.getIdentifierInfo();
3024 auto Kind
= Tok
.getKind();
3025 SourceLocation KWLoc
= ConsumeToken();
3027 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3028 if (T
.expectAndConsume())
3031 SourceLocation EllipsisLoc
;
3032 ExprResult ArgExpr
= ParseAlignArgument(T
.getOpenLocation(), EllipsisLoc
);
3033 if (ArgExpr
.isInvalid()) {
3040 *EndLoc
= T
.getCloseLocation();
3042 ArgsVector ArgExprs
;
3043 ArgExprs
.push_back(ArgExpr
.get());
3044 Attrs
.addNew(KWName
, KWLoc
, nullptr, KWLoc
, ArgExprs
.data(), 1, Kind
,
3048 ExprResult
Parser::ParseExtIntegerArgument() {
3049 assert(Tok
.isOneOf(tok::kw__ExtInt
, tok::kw__BitInt
) &&
3050 "Not an extended int type");
3053 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3054 if (T
.expectAndConsume())
3057 ExprResult ER
= ParseConstantExpression();
3058 if (ER
.isInvalid()) {
3063 if(T
.consumeClose())
3068 /// Determine whether we're looking at something that might be a declarator
3069 /// in a simple-declaration. If it can't possibly be a declarator, maybe
3070 /// diagnose a missing semicolon after a prior tag definition in the decl
3073 /// \return \c true if an error occurred and this can't be any kind of
3076 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec
&DS
, AccessSpecifier AS
,
3077 DeclSpecContext DSContext
,
3078 LateParsedAttrList
*LateAttrs
) {
3079 assert(DS
.hasTagDefinition() && "shouldn't call this");
3081 bool EnteringContext
= (DSContext
== DeclSpecContext::DSC_class
||
3082 DSContext
== DeclSpecContext::DSC_top_level
);
3084 if (getLangOpts().CPlusPlus
&&
3085 Tok
.isOneOf(tok::identifier
, tok::coloncolon
, tok::kw_decltype
,
3086 tok::annot_template_id
) &&
3087 TryAnnotateCXXScopeToken(EnteringContext
)) {
3088 SkipMalformedDecl();
3092 bool HasScope
= Tok
.is(tok::annot_cxxscope
);
3093 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3094 Token AfterScope
= HasScope
? NextToken() : Tok
;
3096 // Determine whether the following tokens could possibly be a
3098 bool MightBeDeclarator
= true;
3099 if (Tok
.isOneOf(tok::kw_typename
, tok::annot_typename
)) {
3100 // A declarator-id can't start with 'typename'.
3101 MightBeDeclarator
= false;
3102 } else if (AfterScope
.is(tok::annot_template_id
)) {
3103 // If we have a type expressed as a template-id, this cannot be a
3104 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3105 TemplateIdAnnotation
*Annot
=
3106 static_cast<TemplateIdAnnotation
*>(AfterScope
.getAnnotationValue());
3107 if (Annot
->Kind
== TNK_Type_template
)
3108 MightBeDeclarator
= false;
3109 } else if (AfterScope
.is(tok::identifier
)) {
3110 const Token
&Next
= HasScope
? GetLookAheadToken(2) : NextToken();
3112 // These tokens cannot come after the declarator-id in a
3113 // simple-declaration, and are likely to come after a type-specifier.
3114 if (Next
.isOneOf(tok::star
, tok::amp
, tok::ampamp
, tok::identifier
,
3115 tok::annot_cxxscope
, tok::coloncolon
)) {
3116 // Missing a semicolon.
3117 MightBeDeclarator
= false;
3118 } else if (HasScope
) {
3119 // If the declarator-id has a scope specifier, it must redeclare a
3120 // previously-declared entity. If that's a type (and this is not a
3121 // typedef), that's an error.
3123 Actions
.RestoreNestedNameSpecifierAnnotation(
3124 Tok
.getAnnotationValue(), Tok
.getAnnotationRange(), SS
);
3125 IdentifierInfo
*Name
= AfterScope
.getIdentifierInfo();
3126 Sema::NameClassification Classification
= Actions
.ClassifyName(
3127 getCurScope(), SS
, Name
, AfterScope
.getLocation(), Next
,
3129 switch (Classification
.getKind()) {
3130 case Sema::NC_Error
:
3131 SkipMalformedDecl();
3134 case Sema::NC_Keyword
:
3135 llvm_unreachable("typo correction is not possible here");
3138 case Sema::NC_TypeTemplate
:
3139 case Sema::NC_UndeclaredNonType
:
3140 case Sema::NC_UndeclaredTemplate
:
3141 // Not a previously-declared non-type entity.
3142 MightBeDeclarator
= false;
3145 case Sema::NC_Unknown
:
3146 case Sema::NC_NonType
:
3147 case Sema::NC_DependentNonType
:
3148 case Sema::NC_OverloadSet
:
3149 case Sema::NC_VarTemplate
:
3150 case Sema::NC_FunctionTemplate
:
3151 case Sema::NC_Concept
:
3152 // Might be a redeclaration of a prior entity.
3158 if (MightBeDeclarator
)
3161 const PrintingPolicy
&PPol
= Actions
.getASTContext().getPrintingPolicy();
3162 Diag(PP
.getLocForEndOfToken(DS
.getRepAsDecl()->getEndLoc()),
3163 diag::err_expected_after
)
3164 << DeclSpec::getSpecifierName(DS
.getTypeSpecType(), PPol
) << tok::semi
;
3166 // Try to recover from the typo, by dropping the tag definition and parsing
3167 // the problematic tokens as a type.
3169 // FIXME: Split the DeclSpec into pieces for the standalone
3170 // declaration and pieces for the following declaration, instead
3171 // of assuming that all the other pieces attach to new declaration,
3172 // and call ParsedFreeStandingDeclSpec as appropriate.
3173 DS
.ClearTypeSpecType();
3174 ParsedTemplateInfo NotATemplate
;
3175 ParseDeclarationSpecifiers(DS
, NotATemplate
, AS
, DSContext
, LateAttrs
);
3179 // Choose the apprpriate diagnostic error for why fixed point types are
3180 // disabled, set the previous specifier, and mark as invalid.
3181 static void SetupFixedPointError(const LangOptions
&LangOpts
,
3182 const char *&PrevSpec
, unsigned &DiagID
,
3184 assert(!LangOpts
.FixedPoint
);
3185 DiagID
= diag::err_fixed_point_not_enabled
;
3186 PrevSpec
= ""; // Not used by diagnostic
3190 /// ParseDeclarationSpecifiers
3191 /// declaration-specifiers: [C99 6.7]
3192 /// storage-class-specifier declaration-specifiers[opt]
3193 /// type-specifier declaration-specifiers[opt]
3194 /// [C99] function-specifier declaration-specifiers[opt]
3195 /// [C11] alignment-specifier declaration-specifiers[opt]
3196 /// [GNU] attributes declaration-specifiers[opt]
3197 /// [Clang] '__module_private__' declaration-specifiers[opt]
3198 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3200 /// storage-class-specifier: [C99 6.7.1]
3207 /// [C++11] 'thread_local'
3208 /// [C11] '_Thread_local'
3209 /// [GNU] '__thread'
3210 /// function-specifier: [C99 6.7.4]
3213 /// [C++] 'explicit'
3214 /// [OpenCL] '__kernel'
3215 /// 'friend': [C++ dcl.friend]
3216 /// 'constexpr': [C++0x dcl.constexpr]
3217 void Parser::ParseDeclarationSpecifiers(
3218 DeclSpec
&DS
, const ParsedTemplateInfo
&TemplateInfo
, AccessSpecifier AS
,
3219 DeclSpecContext DSContext
, LateParsedAttrList
*LateAttrs
,
3220 ImplicitTypenameContext AllowImplicitTypename
) {
3221 if (DS
.getSourceRange().isInvalid()) {
3222 // Start the range at the current token but make the end of the range
3223 // invalid. This will make the entire range invalid unless we successfully
3225 DS
.SetRangeStart(Tok
.getLocation());
3226 DS
.SetRangeEnd(SourceLocation());
3229 // If we are in a operator context, convert it back into a type specifier
3230 // context for better error handling later on.
3231 if (DSContext
== DeclSpecContext::DSC_conv_operator
) {
3232 // No implicit typename here.
3233 AllowImplicitTypename
= ImplicitTypenameContext::No
;
3234 DSContext
= DeclSpecContext::DSC_type_specifier
;
3237 bool EnteringContext
= (DSContext
== DeclSpecContext::DSC_class
||
3238 DSContext
== DeclSpecContext::DSC_top_level
);
3239 bool AttrsLastTime
= false;
3240 ParsedAttributes
attrs(AttrFactory
);
3241 // We use Sema's policy to get bool macros right.
3242 PrintingPolicy Policy
= Actions
.getPrintingPolicy();
3244 bool isInvalid
= false;
3245 bool isStorageClass
= false;
3246 const char *PrevSpec
= nullptr;
3247 unsigned DiagID
= 0;
3249 // This value needs to be set to the location of the last token if the last
3250 // token of the specifier is already consumed.
3251 SourceLocation ConsumedEnd
;
3253 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3254 // implementation for VS2013 uses _Atomic as an identifier for one of the
3255 // classes in <atomic>.
3257 // A typedef declaration containing _Atomic<...> is among the places where
3258 // the class is used. If we are currently parsing such a declaration, treat
3259 // the token as an identifier.
3260 if (getLangOpts().MSVCCompat
&& Tok
.is(tok::kw__Atomic
) &&
3261 DS
.getStorageClassSpec() == clang::DeclSpec::SCS_typedef
&&
3262 !DS
.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less
))
3263 Tok
.setKind(tok::identifier
);
3265 SourceLocation Loc
= Tok
.getLocation();
3267 // Helper for image types in OpenCL.
3268 auto handleOpenCLImageKW
= [&] (StringRef Ext
, TypeSpecifierType ImageTypeSpec
) {
3269 // Check if the image type is supported and otherwise turn the keyword into an identifier
3270 // because image types from extensions are not reserved identifiers.
3271 if (!StringRef(Ext
).empty() && !getActions().getOpenCLOptions().isSupported(Ext
, getLangOpts())) {
3272 Tok
.getIdentifierInfo()->revertTokenIDToIdentifier();
3273 Tok
.setKind(tok::identifier
);
3276 isInvalid
= DS
.SetTypeSpecType(ImageTypeSpec
, Loc
, PrevSpec
, DiagID
, Policy
);
3280 // Turn off usual access checking for template specializations and
3282 bool IsTemplateSpecOrInst
=
3283 (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
||
3284 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
);
3286 switch (Tok
.getKind()) {
3290 ProhibitAttributes(attrs
);
3292 // Reject C++11 / C2x attributes that aren't type attributes.
3293 for (const ParsedAttr
&PA
: attrs
) {
3294 if (!PA
.isCXX11Attribute() && !PA
.isC2xAttribute())
3296 if (PA
.getKind() == ParsedAttr::UnknownAttribute
)
3297 // We will warn about the unknown attribute elsewhere (in
3298 // SemaDeclAttr.cpp)
3300 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3301 // syntax, so we do the same.
3302 if (PA
.getKind() == ParsedAttr::AT_VectorSize
) {
3303 Diag(PA
.getLoc(), diag::warn_attribute_ignored
) << PA
;
3307 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3308 // are type attributes, because we historically haven't allowed these
3309 // to be used as type attributes in C++11 / C2x syntax.
3310 if (PA
.isTypeAttr() && PA
.getKind() != ParsedAttr::AT_LifetimeBound
&&
3311 PA
.getKind() != ParsedAttr::AT_AnyX86NoCfCheck
)
3313 Diag(PA
.getLoc(), diag::err_attribute_not_type_attr
) << PA
;
3317 DS
.takeAttributesFrom(attrs
);
3320 // If this is not a declaration specifier token, we're done reading decl
3321 // specifiers. First verify that DeclSpec's are consistent.
3322 DS
.Finish(Actions
, Policy
);
3326 case tok::kw_alignas
:
3327 if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3328 goto DoneWithDeclSpec
;
3330 ProhibitAttributes(attrs
);
3331 // FIXME: It would be good to recover by accepting the attributes,
3332 // but attempting to do that now would cause serious
3333 // madness in terms of diagnostics.
3335 attrs
.Range
= SourceRange();
3337 ParseCXX11Attributes(attrs
);
3338 AttrsLastTime
= true;
3341 case tok::code_completion
: {
3342 Sema::ParserCompletionContext CCC
= Sema::PCC_Namespace
;
3343 if (DS
.hasTypeSpecifier()) {
3344 bool AllowNonIdentifiers
3345 = (getCurScope()->getFlags() & (Scope::ControlScope
|
3347 Scope::TemplateParamScope
|
3348 Scope::FunctionPrototypeScope
|
3349 Scope::AtCatchScope
)) == 0;
3350 bool AllowNestedNameSpecifiers
3351 = DSContext
== DeclSpecContext::DSC_top_level
||
3352 (DSContext
== DeclSpecContext::DSC_class
&& DS
.isFriendSpecified());
3355 Actions
.CodeCompleteDeclSpec(getCurScope(), DS
,
3356 AllowNonIdentifiers
,
3357 AllowNestedNameSpecifiers
);
3361 // Class context can appear inside a function/block, so prioritise that.
3362 if (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
)
3363 CCC
= DSContext
== DeclSpecContext::DSC_class
? Sema::PCC_MemberTemplate
3364 : Sema::PCC_Template
;
3365 else if (DSContext
== DeclSpecContext::DSC_class
)
3366 CCC
= Sema::PCC_Class
;
3367 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3368 CCC
= Sema::PCC_LocalDeclarationSpecifiers
;
3369 else if (CurParsedObjCImpl
)
3370 CCC
= Sema::PCC_ObjCImplementation
;
3373 Actions
.CodeCompleteOrdinaryName(getCurScope(), CCC
);
3377 case tok::coloncolon
: // ::foo::bar
3378 // C++ scope specifier. Annotate and loop, or bail out on error.
3379 if (TryAnnotateCXXScopeToken(EnteringContext
)) {
3380 if (!DS
.hasTypeSpecifier())
3381 DS
.SetTypeSpecError();
3382 goto DoneWithDeclSpec
;
3384 if (Tok
.is(tok::coloncolon
)) // ::new or ::delete
3385 goto DoneWithDeclSpec
;
3388 case tok::annot_cxxscope
: {
3389 if (DS
.hasTypeSpecifier() || DS
.isTypeAltiVecVector())
3390 goto DoneWithDeclSpec
;
3393 if (TemplateInfo
.TemplateParams
)
3394 SS
.setTemplateParamLists(*TemplateInfo
.TemplateParams
);
3395 Actions
.RestoreNestedNameSpecifierAnnotation(Tok
.getAnnotationValue(),
3396 Tok
.getAnnotationRange(),
3399 // We are looking for a qualified typename.
3400 Token Next
= NextToken();
3402 TemplateIdAnnotation
*TemplateId
= Next
.is(tok::annot_template_id
)
3403 ? takeTemplateIdAnnotation(Next
)
3405 if (TemplateId
&& TemplateId
->hasInvalidName()) {
3406 // We found something like 'T::U<Args> x', but U is not a template.
3407 // Assume it was supposed to be a type.
3408 DS
.SetTypeSpecError();
3409 ConsumeAnnotationToken();
3413 if (TemplateId
&& TemplateId
->Kind
== TNK_Type_template
) {
3414 // We have a qualified template-id, e.g., N::A<int>
3416 // If this would be a valid constructor declaration with template
3417 // arguments, we will reject the attempt to form an invalid type-id
3418 // referring to the injected-class-name when we annotate the token,
3419 // per C++ [class.qual]p2.
3421 // To improve diagnostics for this case, parse the declaration as a
3422 // constructor (and reject the extra template arguments later).
3423 if ((DSContext
== DeclSpecContext::DSC_top_level
||
3424 DSContext
== DeclSpecContext::DSC_class
) &&
3426 Actions
.isCurrentClassName(*TemplateId
->Name
, getCurScope(), &SS
) &&
3427 isConstructorDeclarator(/*Unqualified=*/false,
3428 /*DeductionGuide=*/false,
3429 DS
.isFriendSpecified())) {
3430 // The user meant this to be an out-of-line constructor
3431 // definition, but template arguments are not allowed
3432 // there. Just allow this as a constructor; we'll
3433 // complain about it later.
3434 goto DoneWithDeclSpec
;
3437 DS
.getTypeSpecScope() = SS
;
3438 ConsumeAnnotationToken(); // The C++ scope.
3439 assert(Tok
.is(tok::annot_template_id
) &&
3440 "ParseOptionalCXXScopeSpecifier not working");
3441 AnnotateTemplateIdTokenAsType(SS
, AllowImplicitTypename
);
3445 if (TemplateId
&& TemplateId
->Kind
== TNK_Concept_template
) {
3446 DS
.getTypeSpecScope() = SS
;
3447 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3448 // auto ... Consume the scope annotation and continue to consume the
3449 // template-id as a placeholder-specifier. Let the next iteration
3450 // diagnose a missing auto.
3451 ConsumeAnnotationToken();
3455 if (Next
.is(tok::annot_typename
)) {
3456 DS
.getTypeSpecScope() = SS
;
3457 ConsumeAnnotationToken(); // The C++ scope.
3458 TypeResult T
= getTypeAnnotation(Tok
);
3459 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
,
3460 Tok
.getAnnotationEndLoc(),
3461 PrevSpec
, DiagID
, T
, Policy
);
3464 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
3465 ConsumeAnnotationToken(); // The typename
3468 if (AllowImplicitTypename
== ImplicitTypenameContext::Yes
&&
3469 Next
.is(tok::annot_template_id
) &&
3470 static_cast<TemplateIdAnnotation
*>(Next
.getAnnotationValue())
3471 ->Kind
== TNK_Dependent_template_name
) {
3472 DS
.getTypeSpecScope() = SS
;
3473 ConsumeAnnotationToken(); // The C++ scope.
3474 AnnotateTemplateIdTokenAsType(SS
, AllowImplicitTypename
);
3478 if (Next
.isNot(tok::identifier
))
3479 goto DoneWithDeclSpec
;
3481 // Check whether this is a constructor declaration. If we're in a
3482 // context where the identifier could be a class name, and it has the
3483 // shape of a constructor declaration, process it as one.
3484 if ((DSContext
== DeclSpecContext::DSC_top_level
||
3485 DSContext
== DeclSpecContext::DSC_class
) &&
3486 Actions
.isCurrentClassName(*Next
.getIdentifierInfo(), getCurScope(),
3488 isConstructorDeclarator(/*Unqualified=*/false,
3489 /*DeductionGuide=*/false,
3490 DS
.isFriendSpecified(),
3492 goto DoneWithDeclSpec
;
3494 // C++20 [temp.spec] 13.9/6.
3495 // This disables the access checking rules for function template explicit
3496 // instantiation and explicit specialization:
3498 SuppressAccessChecks
SAC(*this, IsTemplateSpecOrInst
);
3500 ParsedType TypeRep
= Actions
.getTypeName(
3501 *Next
.getIdentifierInfo(), Next
.getLocation(), getCurScope(), &SS
,
3502 false, false, nullptr,
3503 /*IsCtorOrDtorName=*/false,
3504 /*WantNontrivialTypeSourceInfo=*/true,
3505 isClassTemplateDeductionContext(DSContext
), AllowImplicitTypename
);
3507 if (IsTemplateSpecOrInst
)
3510 // If the referenced identifier is not a type, then this declspec is
3511 // erroneous: We already checked about that it has no type specifier, and
3512 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3515 if (TryAnnotateTypeConstraint())
3516 goto DoneWithDeclSpec
;
3517 if (Tok
.isNot(tok::annot_cxxscope
) ||
3518 NextToken().isNot(tok::identifier
))
3520 // Eat the scope spec so the identifier is current.
3521 ConsumeAnnotationToken();
3522 ParsedAttributes
Attrs(AttrFactory
);
3523 if (ParseImplicitInt(DS
, &SS
, TemplateInfo
, AS
, DSContext
, Attrs
)) {
3524 if (!Attrs
.empty()) {
3525 AttrsLastTime
= true;
3526 attrs
.takeAllFrom(Attrs
);
3530 goto DoneWithDeclSpec
;
3533 DS
.getTypeSpecScope() = SS
;
3534 ConsumeAnnotationToken(); // The C++ scope.
3536 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
3537 DiagID
, TypeRep
, Policy
);
3541 DS
.SetRangeEnd(Tok
.getLocation());
3542 ConsumeToken(); // The typename.
3547 case tok::annot_typename
: {
3548 // If we've previously seen a tag definition, we were almost surely
3549 // missing a semicolon after it.
3550 if (DS
.hasTypeSpecifier() && DS
.hasTagDefinition())
3551 goto DoneWithDeclSpec
;
3553 TypeResult T
= getTypeAnnotation(Tok
);
3554 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
3559 DS
.SetRangeEnd(Tok
.getAnnotationEndLoc());
3560 ConsumeAnnotationToken(); // The typename
3565 case tok::kw___is_signed
:
3566 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3567 // typically treats it as a trait. If we see __is_signed as it appears
3568 // in libstdc++, e.g.,
3570 // static const bool __is_signed;
3572 // then treat __is_signed as an identifier rather than as a keyword.
3573 if (DS
.getTypeSpecType() == TST_bool
&&
3574 DS
.getTypeQualifiers() == DeclSpec::TQ_const
&&
3575 DS
.getStorageClassSpec() == DeclSpec::SCS_static
)
3576 TryKeywordIdentFallback(true);
3578 // We're done with the declaration-specifiers.
3579 goto DoneWithDeclSpec
;
3582 case tok::kw___super
:
3583 case tok::kw_decltype
:
3584 case tok::identifier
:
3586 // This identifier can only be a typedef name if we haven't already seen
3587 // a type-specifier. Without this check we misparse:
3588 // typedef int X; struct Y { short X; }; as 'short int'.
3589 if (DS
.hasTypeSpecifier())
3590 goto DoneWithDeclSpec
;
3592 // If the token is an identifier named "__declspec" and Microsoft
3593 // extensions are not enabled, it is likely that there will be cascading
3594 // parse errors if this really is a __declspec attribute. Attempt to
3595 // recognize that scenario and recover gracefully.
3596 if (!getLangOpts().DeclSpecKeyword
&& Tok
.is(tok::identifier
) &&
3597 Tok
.getIdentifierInfo()->getName().equals("__declspec")) {
3598 Diag(Loc
, diag::err_ms_attributes_not_enabled
);
3600 // The next token should be an open paren. If it is, eat the entire
3601 // attribute declaration and continue.
3602 if (NextToken().is(tok::l_paren
)) {
3603 // Consume the __declspec identifier.
3606 // Eat the parens and everything between them.
3607 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3608 if (T
.consumeOpen()) {
3609 assert(false && "Not a left paren?");
3617 // In C++, check to see if this is a scope specifier like foo::bar::, if
3618 // so handle it as such. This is important for ctor parsing.
3619 if (getLangOpts().CPlusPlus
) {
3620 // C++20 [temp.spec] 13.9/6.
3621 // This disables the access checking rules for function template
3622 // explicit instantiation and explicit specialization:
3624 SuppressAccessChecks
SAC(*this, IsTemplateSpecOrInst
);
3626 const bool Success
= TryAnnotateCXXScopeToken(EnteringContext
);
3628 if (IsTemplateSpecOrInst
)
3632 if (IsTemplateSpecOrInst
)
3634 DS
.SetTypeSpecError();
3635 goto DoneWithDeclSpec
;
3638 if (!Tok
.is(tok::identifier
))
3642 // Check for need to substitute AltiVec keyword tokens.
3643 if (TryAltiVecToken(DS
, Loc
, PrevSpec
, DiagID
, isInvalid
))
3646 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3647 // allow the use of a typedef name as a type specifier.
3648 if (DS
.isTypeAltiVecVector())
3649 goto DoneWithDeclSpec
;
3651 if (DSContext
== DeclSpecContext::DSC_objc_method_result
&&
3652 isObjCInstancetype()) {
3653 ParsedType TypeRep
= Actions
.ActOnObjCInstanceType(Loc
);
3655 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
3656 DiagID
, TypeRep
, Policy
);
3660 DS
.SetRangeEnd(Loc
);
3665 // If we're in a context where the identifier could be a class name,
3666 // check whether this is a constructor declaration.
3667 if (getLangOpts().CPlusPlus
&& DSContext
== DeclSpecContext::DSC_class
&&
3668 Actions
.isCurrentClassName(*Tok
.getIdentifierInfo(), getCurScope()) &&
3669 isConstructorDeclarator(/*Unqualified=*/true,
3670 /*DeductionGuide=*/false,
3671 DS
.isFriendSpecified()))
3672 goto DoneWithDeclSpec
;
3674 ParsedType TypeRep
= Actions
.getTypeName(
3675 *Tok
.getIdentifierInfo(), Tok
.getLocation(), getCurScope(), nullptr,
3676 false, false, nullptr, false, false,
3677 isClassTemplateDeductionContext(DSContext
));
3679 // If this is not a typedef name, don't parse it as part of the declspec,
3680 // it must be an implicit int or an error.
3682 if (TryAnnotateTypeConstraint())
3683 goto DoneWithDeclSpec
;
3684 if (Tok
.isNot(tok::identifier
))
3686 ParsedAttributes
Attrs(AttrFactory
);
3687 if (ParseImplicitInt(DS
, nullptr, TemplateInfo
, AS
, DSContext
, Attrs
)) {
3688 if (!Attrs
.empty()) {
3689 AttrsLastTime
= true;
3690 attrs
.takeAllFrom(Attrs
);
3694 goto DoneWithDeclSpec
;
3697 // Likewise, if this is a context where the identifier could be a template
3698 // name, check whether this is a deduction guide declaration.
3700 if (getLangOpts().CPlusPlus17
&&
3701 (DSContext
== DeclSpecContext::DSC_class
||
3702 DSContext
== DeclSpecContext::DSC_top_level
) &&
3703 Actions
.isDeductionGuideName(getCurScope(), *Tok
.getIdentifierInfo(),
3704 Tok
.getLocation(), SS
) &&
3705 isConstructorDeclarator(/*Unqualified*/ true,
3706 /*DeductionGuide*/ true))
3707 goto DoneWithDeclSpec
;
3709 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, Loc
, PrevSpec
,
3710 DiagID
, TypeRep
, Policy
);
3714 DS
.SetRangeEnd(Tok
.getLocation());
3715 ConsumeToken(); // The identifier
3717 // Objective-C supports type arguments and protocol references
3718 // following an Objective-C object or object pointer
3719 // type. Handle either one of them.
3720 if (Tok
.is(tok::less
) && getLangOpts().ObjC
) {
3721 SourceLocation NewEndLoc
;
3722 TypeResult NewTypeRep
= parseObjCTypeArgsAndProtocolQualifiers(
3723 Loc
, TypeRep
, /*consumeLastToken=*/true,
3725 if (NewTypeRep
.isUsable()) {
3726 DS
.UpdateTypeRep(NewTypeRep
.get());
3727 DS
.SetRangeEnd(NewEndLoc
);
3731 // Need to support trailing type qualifiers (e.g. "id<p> const").
3732 // If a type specifier follows, it will be diagnosed elsewhere.
3736 // type-name or placeholder-specifier
3737 case tok::annot_template_id
: {
3738 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
3740 if (TemplateId
->hasInvalidName()) {
3741 DS
.SetTypeSpecError();
3745 if (TemplateId
->Kind
== TNK_Concept_template
) {
3746 // If we've already diagnosed that this type-constraint has invalid
3747 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3748 if (TemplateId
->hasInvalidArgs())
3749 TemplateId
= nullptr;
3751 // Any of the following tokens are likely the start of the user
3752 // forgetting 'auto' or 'decltype(auto)', so diagnose.
3753 // Note: if updating this list, please make sure we update
3754 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3756 if (NextToken().isOneOf(tok::identifier
, tok::kw_const
,
3757 tok::kw_volatile
, tok::kw_restrict
, tok::amp
,
3759 Diag(Loc
, diag::err_placeholder_expected_auto_or_decltype_auto
)
3760 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3761 // Attempt to continue as if 'auto' was placed here.
3762 isInvalid
= DS
.SetTypeSpecType(TST_auto
, Loc
, PrevSpec
, DiagID
,
3763 TemplateId
, Policy
);
3766 if (!NextToken().isOneOf(tok::kw_auto
, tok::kw_decltype
))
3767 goto DoneWithDeclSpec
;
3769 if (TemplateId
&& !isInvalid
&& Actions
.CheckTypeConstraint(TemplateId
))
3770 TemplateId
= nullptr;
3772 ConsumeAnnotationToken();
3773 SourceLocation AutoLoc
= Tok
.getLocation();
3774 if (TryConsumeToken(tok::kw_decltype
)) {
3775 BalancedDelimiterTracker
Tracker(*this, tok::l_paren
);
3776 if (Tracker
.consumeOpen()) {
3777 // Something like `void foo(Iterator decltype i)`
3778 Diag(Tok
, diag::err_expected
) << tok::l_paren
;
3780 if (!TryConsumeToken(tok::kw_auto
)) {
3781 // Something like `void foo(Iterator decltype(int) i)`
3782 Tracker
.skipToEnd();
3783 Diag(Tok
, diag::err_placeholder_expected_auto_or_decltype_auto
)
3784 << FixItHint::CreateReplacement(SourceRange(AutoLoc
,
3788 Tracker
.consumeClose();
3791 ConsumedEnd
= Tok
.getLocation();
3792 DS
.setTypeArgumentRange(Tracker
.getRange());
3793 // Even if something went wrong above, continue as if we've seen
3794 // `decltype(auto)`.
3795 isInvalid
= DS
.SetTypeSpecType(TST_decltype_auto
, Loc
, PrevSpec
,
3796 DiagID
, TemplateId
, Policy
);
3798 isInvalid
= DS
.SetTypeSpecType(TST_auto
, AutoLoc
, PrevSpec
, DiagID
,
3799 TemplateId
, Policy
);
3804 if (TemplateId
->Kind
!= TNK_Type_template
&&
3805 TemplateId
->Kind
!= TNK_Undeclared_template
) {
3806 // This template-id does not refer to a type name, so we're
3807 // done with the type-specifiers.
3808 goto DoneWithDeclSpec
;
3811 // If we're in a context where the template-id could be a
3812 // constructor name or specialization, check whether this is a
3813 // constructor declaration.
3814 if (getLangOpts().CPlusPlus
&& DSContext
== DeclSpecContext::DSC_class
&&
3815 Actions
.isCurrentClassName(*TemplateId
->Name
, getCurScope()) &&
3816 isConstructorDeclarator(/*Unqualified=*/true,
3817 /*DeductionGuide=*/false,
3818 DS
.isFriendSpecified()))
3819 goto DoneWithDeclSpec
;
3821 // Turn the template-id annotation token into a type annotation
3822 // token, then try again to parse it as a type-specifier.
3824 AnnotateTemplateIdTokenAsType(SS
, AllowImplicitTypename
);
3828 // Attributes support.
3829 case tok::kw___attribute
:
3830 case tok::kw___declspec
:
3831 ParseAttributes(PAKM_GNU
| PAKM_Declspec
, DS
.getAttributes(), LateAttrs
);
3834 // Microsoft single token adornments.
3835 case tok::kw___forceinline
: {
3836 isInvalid
= DS
.setFunctionSpecForceInline(Loc
, PrevSpec
, DiagID
);
3837 IdentifierInfo
*AttrName
= Tok
.getIdentifierInfo();
3838 SourceLocation AttrNameLoc
= Tok
.getLocation();
3839 DS
.getAttributes().addNew(AttrName
, AttrNameLoc
, nullptr, AttrNameLoc
,
3840 nullptr, 0, tok::kw___forceinline
);
3844 case tok::kw___unaligned
:
3845 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_unaligned
, Loc
, PrevSpec
, DiagID
,
3849 case tok::kw___sptr
:
3850 case tok::kw___uptr
:
3851 case tok::kw___ptr64
:
3852 case tok::kw___ptr32
:
3854 case tok::kw___cdecl
:
3855 case tok::kw___stdcall
:
3856 case tok::kw___fastcall
:
3857 case tok::kw___thiscall
:
3858 case tok::kw___regcall
:
3859 case tok::kw___vectorcall
:
3860 ParseMicrosoftTypeAttributes(DS
.getAttributes());
3863 case tok::kw___funcref
:
3864 ParseWebAssemblyFuncrefTypeAttribute(DS
.getAttributes());
3867 // Borland single token adornments.
3868 case tok::kw___pascal
:
3869 ParseBorlandTypeAttributes(DS
.getAttributes());
3872 // OpenCL single token adornments.
3873 case tok::kw___kernel
:
3874 ParseOpenCLKernelAttributes(DS
.getAttributes());
3877 // CUDA/HIP single token adornments.
3878 case tok::kw___noinline__
:
3879 ParseCUDAFunctionAttributes(DS
.getAttributes());
3882 // Nullability type specifiers.
3883 case tok::kw__Nonnull
:
3884 case tok::kw__Nullable
:
3885 case tok::kw__Nullable_result
:
3886 case tok::kw__Null_unspecified
:
3887 ParseNullabilityTypeSpecifiers(DS
.getAttributes());
3890 // Objective-C 'kindof' types.
3891 case tok::kw___kindof
:
3892 DS
.getAttributes().addNew(Tok
.getIdentifierInfo(), Loc
, nullptr, Loc
,
3893 nullptr, 0, tok::kw___kindof
);
3894 (void)ConsumeToken();
3897 // storage-class-specifier
3898 case tok::kw_typedef
:
3899 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_typedef
, Loc
,
3900 PrevSpec
, DiagID
, Policy
);
3901 isStorageClass
= true;
3903 case tok::kw_extern
:
3904 if (DS
.getThreadStorageClassSpec() == DeclSpec::TSCS___thread
)
3905 Diag(Tok
, diag::ext_thread_before
) << "extern";
3906 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_extern
, Loc
,
3907 PrevSpec
, DiagID
, Policy
);
3908 isStorageClass
= true;
3910 case tok::kw___private_extern__
:
3911 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_private_extern
,
3912 Loc
, PrevSpec
, DiagID
, Policy
);
3913 isStorageClass
= true;
3915 case tok::kw_static
:
3916 if (DS
.getThreadStorageClassSpec() == DeclSpec::TSCS___thread
)
3917 Diag(Tok
, diag::ext_thread_before
) << "static";
3918 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_static
, Loc
,
3919 PrevSpec
, DiagID
, Policy
);
3920 isStorageClass
= true;
3923 if (getLangOpts().CPlusPlus11
) {
3924 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3925 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_auto
, Loc
,
3926 PrevSpec
, DiagID
, Policy
);
3928 Diag(Tok
, diag::ext_auto_storage_class
)
3929 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
3931 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_auto
, Loc
, PrevSpec
,
3934 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_auto
, Loc
,
3935 PrevSpec
, DiagID
, Policy
);
3936 isStorageClass
= true;
3938 case tok::kw___auto_type
:
3939 Diag(Tok
, diag::ext_auto_type
);
3940 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_auto_type
, Loc
, PrevSpec
,
3943 case tok::kw_register
:
3944 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_register
, Loc
,
3945 PrevSpec
, DiagID
, Policy
);
3946 isStorageClass
= true;
3948 case tok::kw_mutable
:
3949 isInvalid
= DS
.SetStorageClassSpec(Actions
, DeclSpec::SCS_mutable
, Loc
,
3950 PrevSpec
, DiagID
, Policy
);
3951 isStorageClass
= true;
3953 case tok::kw___thread
:
3954 isInvalid
= DS
.SetStorageClassSpecThread(DeclSpec::TSCS___thread
, Loc
,
3956 isStorageClass
= true;
3958 case tok::kw_thread_local
:
3959 if (getLangOpts().C2x
)
3960 Diag(Tok
, diag::warn_c2x_compat_keyword
) << Tok
.getName();
3961 isInvalid
= DS
.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local
, Loc
,
3963 isStorageClass
= true;
3965 case tok::kw__Thread_local
:
3966 if (!getLangOpts().C11
)
3967 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
3968 isInvalid
= DS
.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local
,
3969 Loc
, PrevSpec
, DiagID
);
3970 isStorageClass
= true;
3973 // function-specifier
3974 case tok::kw_inline
:
3975 isInvalid
= DS
.setFunctionSpecInline(Loc
, PrevSpec
, DiagID
);
3977 case tok::kw_virtual
:
3978 // C++ for OpenCL does not allow virtual function qualifier, to avoid
3979 // function pointers restricted in OpenCL v2.0 s6.9.a.
3980 if (getLangOpts().OpenCLCPlusPlus
&&
3981 !getActions().getOpenCLOptions().isAvailableOption(
3982 "__cl_clang_function_pointers", getLangOpts())) {
3983 DiagID
= diag::err_openclcxx_virtual_function
;
3984 PrevSpec
= Tok
.getIdentifierInfo()->getNameStart();
3987 isInvalid
= DS
.setFunctionSpecVirtual(Loc
, PrevSpec
, DiagID
);
3990 case tok::kw_explicit
: {
3991 SourceLocation ExplicitLoc
= Loc
;
3992 SourceLocation CloseParenLoc
;
3993 ExplicitSpecifier
ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue
);
3994 ConsumedEnd
= ExplicitLoc
;
3995 ConsumeToken(); // kw_explicit
3996 if (Tok
.is(tok::l_paren
)) {
3997 if (getLangOpts().CPlusPlus20
|| isExplicitBool() == TPResult::True
) {
3998 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus20
3999 ? diag::warn_cxx17_compat_explicit_bool
4000 : diag::ext_explicit_bool
);
4002 ExprResult
ExplicitExpr(static_cast<Expr
*>(nullptr));
4003 BalancedDelimiterTracker
Tracker(*this, tok::l_paren
);
4004 Tracker
.consumeOpen();
4005 ExplicitExpr
= ParseConstantExpression();
4006 ConsumedEnd
= Tok
.getLocation();
4007 if (ExplicitExpr
.isUsable()) {
4008 CloseParenLoc
= Tok
.getLocation();
4009 Tracker
.consumeClose();
4011 Actions
.ActOnExplicitBoolSpecifier(ExplicitExpr
.get());
4013 Tracker
.skipToEnd();
4015 Diag(Tok
.getLocation(), diag::warn_cxx20_compat_explicit_bool
);
4018 isInvalid
= DS
.setFunctionSpecExplicit(ExplicitLoc
, PrevSpec
, DiagID
,
4019 ExplicitSpec
, CloseParenLoc
);
4022 case tok::kw__Noreturn
:
4023 if (!getLangOpts().C11
)
4024 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
4025 isInvalid
= DS
.setFunctionSpecNoreturn(Loc
, PrevSpec
, DiagID
);
4028 // alignment-specifier
4029 case tok::kw__Alignas
:
4030 if (!getLangOpts().C11
)
4031 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
4032 ParseAlignmentSpecifier(DS
.getAttributes());
4036 case tok::kw_friend
:
4037 if (DSContext
== DeclSpecContext::DSC_class
)
4038 isInvalid
= DS
.SetFriendSpec(Loc
, PrevSpec
, DiagID
);
4040 PrevSpec
= ""; // not actually used by the diagnostic
4041 DiagID
= diag::err_friend_invalid_in_context
;
4047 case tok::kw___module_private__
:
4048 isInvalid
= DS
.setModulePrivateSpec(Loc
, PrevSpec
, DiagID
);
4051 // constexpr, consteval, constinit specifiers
4052 case tok::kw_constexpr
:
4053 isInvalid
= DS
.SetConstexprSpec(ConstexprSpecKind::Constexpr
, Loc
,
4056 case tok::kw_consteval
:
4057 isInvalid
= DS
.SetConstexprSpec(ConstexprSpecKind::Consteval
, Loc
,
4060 case tok::kw_constinit
:
4061 isInvalid
= DS
.SetConstexprSpec(ConstexprSpecKind::Constinit
, Loc
,
4067 isInvalid
= DS
.SetTypeSpecWidth(TypeSpecifierWidth::Short
, Loc
, PrevSpec
,
4071 if (DS
.getTypeSpecWidth() != TypeSpecifierWidth::Long
)
4072 isInvalid
= DS
.SetTypeSpecWidth(TypeSpecifierWidth::Long
, Loc
, PrevSpec
,
4075 isInvalid
= DS
.SetTypeSpecWidth(TypeSpecifierWidth::LongLong
, Loc
,
4076 PrevSpec
, DiagID
, Policy
);
4078 case tok::kw___int64
:
4079 isInvalid
= DS
.SetTypeSpecWidth(TypeSpecifierWidth::LongLong
, Loc
,
4080 PrevSpec
, DiagID
, Policy
);
4082 case tok::kw_signed
:
4084 DS
.SetTypeSpecSign(TypeSpecifierSign::Signed
, Loc
, PrevSpec
, DiagID
);
4086 case tok::kw_unsigned
:
4087 isInvalid
= DS
.SetTypeSpecSign(TypeSpecifierSign::Unsigned
, Loc
, PrevSpec
,
4090 case tok::kw__Complex
:
4091 if (!getLangOpts().C99
)
4092 Diag(Tok
, diag::ext_c99_feature
) << Tok
.getName();
4093 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_complex
, Loc
, PrevSpec
,
4096 case tok::kw__Imaginary
:
4097 if (!getLangOpts().C99
)
4098 Diag(Tok
, diag::ext_c99_feature
) << Tok
.getName();
4099 isInvalid
= DS
.SetTypeSpecComplex(DeclSpec::TSC_imaginary
, Loc
, PrevSpec
,
4103 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_void
, Loc
, PrevSpec
,
4107 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char
, Loc
, PrevSpec
,
4111 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, PrevSpec
,
4114 case tok::kw__ExtInt
:
4115 case tok::kw__BitInt
: {
4116 DiagnoseBitIntUse(Tok
);
4117 ExprResult ER
= ParseExtIntegerArgument();
4120 isInvalid
= DS
.SetBitIntType(Loc
, ER
.get(), PrevSpec
, DiagID
, Policy
);
4121 ConsumedEnd
= PrevTokLocation
;
4124 case tok::kw___int128
:
4125 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_int128
, Loc
, PrevSpec
,
4129 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_half
, Loc
, PrevSpec
,
4132 case tok::kw___bf16
:
4133 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_BFloat16
, Loc
, PrevSpec
,
4137 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_float
, Loc
, PrevSpec
,
4140 case tok::kw_double
:
4141 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_double
, Loc
, PrevSpec
,
4144 case tok::kw__Float16
:
4145 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_float16
, Loc
, PrevSpec
,
4148 case tok::kw__Accum
:
4149 if (!getLangOpts().FixedPoint
) {
4150 SetupFixedPointError(getLangOpts(), PrevSpec
, DiagID
, isInvalid
);
4152 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_accum
, Loc
, PrevSpec
,
4156 case tok::kw__Fract
:
4157 if (!getLangOpts().FixedPoint
) {
4158 SetupFixedPointError(getLangOpts(), PrevSpec
, DiagID
, isInvalid
);
4160 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_fract
, Loc
, PrevSpec
,
4165 if (!getLangOpts().FixedPoint
) {
4166 SetupFixedPointError(getLangOpts(), PrevSpec
, DiagID
, isInvalid
);
4168 isInvalid
= DS
.SetTypeSpecSat(Loc
, PrevSpec
, DiagID
);
4171 case tok::kw___float128
:
4172 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_float128
, Loc
, PrevSpec
,
4175 case tok::kw___ibm128
:
4176 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_ibm128
, Loc
, PrevSpec
,
4179 case tok::kw_wchar_t
:
4180 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_wchar
, Loc
, PrevSpec
,
4183 case tok::kw_char8_t
:
4184 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char8
, Loc
, PrevSpec
,
4187 case tok::kw_char16_t
:
4188 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char16
, Loc
, PrevSpec
,
4191 case tok::kw_char32_t
:
4192 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_char32
, Loc
, PrevSpec
,
4196 if (getLangOpts().C2x
)
4197 Diag(Tok
, diag::warn_c2x_compat_keyword
) << Tok
.getName();
4200 if (Tok
.is(tok::kw__Bool
) && !getLangOpts().C99
)
4201 Diag(Tok
, diag::ext_c99_feature
) << Tok
.getName();
4203 if (Tok
.is(tok::kw_bool
) &&
4204 DS
.getTypeSpecType() != DeclSpec::TST_unspecified
&&
4205 DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
4206 PrevSpec
= ""; // Not used by the diagnostic.
4207 DiagID
= diag::err_bool_redeclaration
;
4208 // For better error recovery.
4209 Tok
.setKind(tok::identifier
);
4212 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_bool
, Loc
, PrevSpec
,
4216 case tok::kw__Decimal32
:
4217 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal32
, Loc
, PrevSpec
,
4220 case tok::kw__Decimal64
:
4221 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal64
, Loc
, PrevSpec
,
4224 case tok::kw__Decimal128
:
4225 isInvalid
= DS
.SetTypeSpecType(DeclSpec::TST_decimal128
, Loc
, PrevSpec
,
4228 case tok::kw___vector
:
4229 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
, Policy
);
4231 case tok::kw___pixel
:
4232 isInvalid
= DS
.SetTypeAltiVecPixel(true, Loc
, PrevSpec
, DiagID
, Policy
);
4234 case tok::kw___bool
:
4235 isInvalid
= DS
.SetTypeAltiVecBool(true, Loc
, PrevSpec
, DiagID
, Policy
);
4238 if (!getLangOpts().OpenCL
||
4239 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4240 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4241 // should support the "pipe" word as identifier.
4242 Tok
.getIdentifierInfo()->revertTokenIDToIdentifier();
4243 Tok
.setKind(tok::identifier
);
4244 goto DoneWithDeclSpec
;
4245 } else if (!getLangOpts().OpenCLPipes
) {
4246 DiagID
= diag::err_opencl_unknown_type_specifier
;
4247 PrevSpec
= Tok
.getIdentifierInfo()->getNameStart();
4250 isInvalid
= DS
.SetTypePipe(true, Loc
, PrevSpec
, DiagID
, Policy
);
4252 // We only need to enumerate each image type once.
4253 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4254 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
4255 #define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4256 case tok::kw_##ImgType##_t: \
4257 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4258 goto DoneWithDeclSpec; \
4260 #include "clang/Basic/OpenCLImageTypes.def"
4261 case tok::kw___unknown_anytype
:
4262 isInvalid
= DS
.SetTypeSpecType(TST_unknown_anytype
, Loc
,
4263 PrevSpec
, DiagID
, Policy
);
4268 case tok::kw_struct
:
4269 case tok::kw___interface
:
4270 case tok::kw_union
: {
4271 tok::TokenKind Kind
= Tok
.getKind();
4274 // These are attributes following class specifiers.
4275 // To produce better diagnostic, we parse them when
4276 // parsing class specifier.
4277 ParsedAttributes
Attributes(AttrFactory
);
4278 ParseClassSpecifier(Kind
, Loc
, DS
, TemplateInfo
, AS
,
4279 EnteringContext
, DSContext
, Attributes
);
4281 // If there are attributes following class specifier,
4282 // take them over and handle them here.
4283 if (!Attributes
.empty()) {
4284 AttrsLastTime
= true;
4285 attrs
.takeAllFrom(Attributes
);
4293 ParseEnumSpecifier(Loc
, DS
, TemplateInfo
, AS
, DSContext
);
4298 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_const
, Loc
, PrevSpec
, DiagID
,
4301 case tok::kw_volatile
:
4302 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_volatile
, Loc
, PrevSpec
, DiagID
,
4305 case tok::kw_restrict
:
4306 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_restrict
, Loc
, PrevSpec
, DiagID
,
4310 // C++ typename-specifier:
4311 case tok::kw_typename
:
4312 if (TryAnnotateTypeOrScopeToken()) {
4313 DS
.SetTypeSpecError();
4314 goto DoneWithDeclSpec
;
4316 if (!Tok
.is(tok::kw_typename
))
4320 // C2x/GNU typeof support.
4321 case tok::kw_typeof
:
4322 case tok::kw_typeof_unqual
:
4323 ParseTypeofSpecifier(DS
);
4326 case tok::annot_decltype
:
4327 ParseDecltypeSpecifier(DS
);
4330 case tok::annot_pragma_pack
:
4334 case tok::annot_pragma_ms_pragma
:
4335 HandlePragmaMSPragma();
4338 case tok::annot_pragma_ms_vtordisp
:
4339 HandlePragmaMSVtorDisp();
4342 case tok::annot_pragma_ms_pointers_to_members
:
4343 HandlePragmaMSPointersToMembers();
4346 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4347 #include "clang/Basic/TransformTypeTraits.def"
4348 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4349 // work around this by expecting all transform type traits to be suffixed
4350 // with '('. They're an identifier otherwise.
4351 if (!MaybeParseTypeTransformTypeSpecifier(DS
))
4352 goto ParseIdentifier
;
4355 case tok::kw__Atomic
:
4357 // If the _Atomic keyword is immediately followed by a left parenthesis,
4358 // it is interpreted as a type specifier (with a type name), not as a
4360 if (!getLangOpts().C11
)
4361 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
4363 if (NextToken().is(tok::l_paren
)) {
4364 ParseAtomicSpecifier(DS
);
4367 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_atomic
, Loc
, PrevSpec
, DiagID
,
4371 // OpenCL address space qualifiers:
4372 case tok::kw___generic
:
4373 // generic address space is introduced only in OpenCL v2.0
4374 // see OpenCL C Spec v2.0 s6.5.5
4375 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4376 // feature macro to indicate if generic address space is supported
4377 if (!Actions
.getLangOpts().OpenCLGenericAddressSpace
) {
4378 DiagID
= diag::err_opencl_unknown_type_specifier
;
4379 PrevSpec
= Tok
.getIdentifierInfo()->getNameStart();
4384 case tok::kw_private
:
4385 // It's fine (but redundant) to check this for __generic on the
4386 // fallthrough path; we only form the __generic token in OpenCL mode.
4387 if (!getLangOpts().OpenCL
)
4388 goto DoneWithDeclSpec
;
4390 case tok::kw___private
:
4391 case tok::kw___global
:
4392 case tok::kw___local
:
4393 case tok::kw___constant
:
4394 // OpenCL access qualifiers:
4395 case tok::kw___read_only
:
4396 case tok::kw___write_only
:
4397 case tok::kw___read_write
:
4398 ParseOpenCLQualifiers(DS
.getAttributes());
4401 case tok::kw_groupshared
:
4402 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4403 ParseHLSLQualifiers(DS
.getAttributes());
4407 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4408 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4409 // but we support it.
4410 if (DS
.hasTypeSpecifier() || !getLangOpts().ObjC
)
4411 goto DoneWithDeclSpec
;
4413 SourceLocation StartLoc
= Tok
.getLocation();
4414 SourceLocation EndLoc
;
4415 TypeResult Type
= parseObjCProtocolQualifierType(EndLoc
);
4416 if (Type
.isUsable()) {
4417 if (DS
.SetTypeSpecType(DeclSpec::TST_typename
, StartLoc
, StartLoc
,
4418 PrevSpec
, DiagID
, Type
.get(),
4419 Actions
.getASTContext().getPrintingPolicy()))
4420 Diag(StartLoc
, DiagID
) << PrevSpec
;
4422 DS
.SetRangeEnd(EndLoc
);
4424 DS
.SetTypeSpecError();
4427 // Need to support trailing type qualifiers (e.g. "id<p> const").
4428 // If a type specifier follows, it will be diagnosed elsewhere.
4432 DS
.SetRangeEnd(ConsumedEnd
.isValid() ? ConsumedEnd
: Tok
.getLocation());
4434 // If the specifier wasn't legal, issue a diagnostic.
4436 assert(PrevSpec
&& "Method did not return previous specifier!");
4439 if (DiagID
== diag::ext_duplicate_declspec
||
4440 DiagID
== diag::ext_warn_duplicate_declspec
||
4441 DiagID
== diag::err_duplicate_declspec
)
4442 Diag(Loc
, DiagID
) << PrevSpec
4443 << FixItHint::CreateRemoval(
4444 SourceRange(Loc
, DS
.getEndLoc()));
4445 else if (DiagID
== diag::err_opencl_unknown_type_specifier
) {
4446 Diag(Loc
, DiagID
) << getLangOpts().getOpenCLVersionString() << PrevSpec
4449 Diag(Loc
, DiagID
) << PrevSpec
;
4452 if (DiagID
!= diag::err_bool_redeclaration
&& ConsumedEnd
.isInvalid())
4453 // After an error the next token can be an annotation token.
4456 AttrsLastTime
= false;
4460 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4463 /// Note that a struct declaration refers to a declaration in a struct,
4464 /// not to the declaration of a struct.
4466 /// struct-declaration:
4467 /// [C2x] attributes-specifier-seq[opt]
4468 /// specifier-qualifier-list struct-declarator-list
4469 /// [GNU] __extension__ struct-declaration
4470 /// [GNU] specifier-qualifier-list
4471 /// struct-declarator-list:
4472 /// struct-declarator
4473 /// struct-declarator-list ',' struct-declarator
4474 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4475 /// struct-declarator:
4477 /// [GNU] declarator attributes[opt]
4478 /// declarator[opt] ':' constant-expression
4479 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4481 void Parser::ParseStructDeclaration(
4482 ParsingDeclSpec
&DS
,
4483 llvm::function_ref
<void(ParsingFieldDeclarator
&)> FieldsCallback
) {
4485 if (Tok
.is(tok::kw___extension__
)) {
4486 // __extension__ silences extension warnings in the subexpression.
4487 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
4489 return ParseStructDeclaration(DS
, FieldsCallback
);
4492 // Parse leading attributes.
4493 ParsedAttributes
Attrs(AttrFactory
);
4494 MaybeParseCXX11Attributes(Attrs
);
4496 // Parse the common specifier-qualifiers-list piece.
4497 ParseSpecifierQualifierList(DS
);
4499 // If there are no declarators, this is a free-standing declaration
4500 // specifier. Let the actions module cope with it.
4501 if (Tok
.is(tok::semi
)) {
4502 // C2x 6.7.2.1p9 : "The optional attribute specifier sequence in a
4503 // member declaration appertains to each of the members declared by the
4504 // member declarator list; it shall not appear if the optional member
4505 // declarator list is omitted."
4506 ProhibitAttributes(Attrs
);
4507 RecordDecl
*AnonRecord
= nullptr;
4508 Decl
*TheDecl
= Actions
.ParsedFreeStandingDeclSpec(
4509 getCurScope(), AS_none
, DS
, ParsedAttributesView::none(), AnonRecord
);
4510 assert(!AnonRecord
&& "Did not expect anonymous struct or union here");
4511 DS
.complete(TheDecl
);
4515 // Read struct-declarators until we find the semicolon.
4516 bool FirstDeclarator
= true;
4517 SourceLocation CommaLoc
;
4519 ParsingFieldDeclarator
DeclaratorInfo(*this, DS
, Attrs
);
4520 DeclaratorInfo
.D
.setCommaLoc(CommaLoc
);
4522 // Attributes are only allowed here on successive declarators.
4523 if (!FirstDeclarator
) {
4524 // However, this does not apply for [[]] attributes (which could show up
4525 // before or after the __attribute__ attributes).
4526 DiagnoseAndSkipCXX11Attributes();
4527 MaybeParseGNUAttributes(DeclaratorInfo
.D
);
4528 DiagnoseAndSkipCXX11Attributes();
4531 /// struct-declarator: declarator
4532 /// struct-declarator: declarator[opt] ':' constant-expression
4533 if (Tok
.isNot(tok::colon
)) {
4534 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4535 ColonProtectionRAIIObject
X(*this);
4536 ParseDeclarator(DeclaratorInfo
.D
);
4538 DeclaratorInfo
.D
.SetIdentifier(nullptr, Tok
.getLocation());
4540 if (TryConsumeToken(tok::colon
)) {
4541 ExprResult
Res(ParseConstantExpression());
4542 if (Res
.isInvalid())
4543 SkipUntil(tok::semi
, StopBeforeMatch
);
4545 DeclaratorInfo
.BitfieldSize
= Res
.get();
4548 // If attributes exist after the declarator, parse them.
4549 MaybeParseGNUAttributes(DeclaratorInfo
.D
);
4551 // We're done with this declarator; invoke the callback.
4552 FieldsCallback(DeclaratorInfo
);
4554 // If we don't have a comma, it is either the end of the list (a ';')
4555 // or an error, bail out.
4556 if (!TryConsumeToken(tok::comma
, CommaLoc
))
4559 FirstDeclarator
= false;
4563 /// ParseStructUnionBody
4564 /// struct-contents:
4565 /// struct-declaration-list
4567 /// [GNU] "struct-declaration-list" without terminating ';'
4568 /// struct-declaration-list:
4569 /// struct-declaration
4570 /// struct-declaration-list struct-declaration
4571 /// [OBC] '@' 'defs' '(' class-name ')'
4573 void Parser::ParseStructUnionBody(SourceLocation RecordLoc
,
4574 DeclSpec::TST TagType
, RecordDecl
*TagDecl
) {
4575 PrettyDeclStackTraceEntry
CrashInfo(Actions
.Context
, TagDecl
, RecordLoc
,
4576 "parsing struct/union body");
4577 assert(!getLangOpts().CPlusPlus
&& "C++ declarations not supported");
4579 BalancedDelimiterTracker
T(*this, tok::l_brace
);
4580 if (T
.consumeOpen())
4583 ParseScope
StructScope(this, Scope::ClassScope
|Scope::DeclScope
);
4584 Actions
.ActOnTagStartDefinition(getCurScope(), TagDecl
);
4586 // While we still have something to read, read the declarations in the struct.
4587 while (!tryParseMisplacedModuleImport() && Tok
.isNot(tok::r_brace
) &&
4588 Tok
.isNot(tok::eof
)) {
4589 // Each iteration of this loop reads one struct-declaration.
4591 // Check for extraneous top-level semicolon.
4592 if (Tok
.is(tok::semi
)) {
4593 ConsumeExtraSemi(InsideStruct
, TagType
);
4597 // Parse _Static_assert declaration.
4598 if (Tok
.isOneOf(tok::kw__Static_assert
, tok::kw_static_assert
)) {
4599 SourceLocation DeclEnd
;
4600 ParseStaticAssertDeclaration(DeclEnd
);
4604 if (Tok
.is(tok::annot_pragma_pack
)) {
4609 if (Tok
.is(tok::annot_pragma_align
)) {
4610 HandlePragmaAlign();
4614 if (Tok
.isOneOf(tok::annot_pragma_openmp
, tok::annot_attr_openmp
)) {
4615 // Result can be ignored, because it must be always empty.
4616 AccessSpecifier AS
= AS_none
;
4617 ParsedAttributes
Attrs(AttrFactory
);
4618 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS
, Attrs
);
4622 if (tok::isPragmaAnnotation(Tok
.getKind())) {
4623 Diag(Tok
.getLocation(), diag::err_pragma_misplaced_in_decl
)
4624 << DeclSpec::getSpecifierName(
4625 TagType
, Actions
.getASTContext().getPrintingPolicy());
4626 ConsumeAnnotationToken();
4630 if (!Tok
.is(tok::at
)) {
4631 auto CFieldCallback
= [&](ParsingFieldDeclarator
&FD
) {
4632 // Install the declarator into the current TagDecl.
4634 Actions
.ActOnField(getCurScope(), TagDecl
,
4635 FD
.D
.getDeclSpec().getSourceRange().getBegin(),
4636 FD
.D
, FD
.BitfieldSize
);
4640 // Parse all the comma separated declarators.
4641 ParsingDeclSpec
DS(*this);
4642 ParseStructDeclaration(DS
, CFieldCallback
);
4643 } else { // Handle @defs
4645 if (!Tok
.isObjCAtKeyword(tok::objc_defs
)) {
4646 Diag(Tok
, diag::err_unexpected_at
);
4647 SkipUntil(tok::semi
);
4651 ExpectAndConsume(tok::l_paren
);
4652 if (!Tok
.is(tok::identifier
)) {
4653 Diag(Tok
, diag::err_expected
) << tok::identifier
;
4654 SkipUntil(tok::semi
);
4657 SmallVector
<Decl
*, 16> Fields
;
4658 Actions
.ActOnDefs(getCurScope(), TagDecl
, Tok
.getLocation(),
4659 Tok
.getIdentifierInfo(), Fields
);
4661 ExpectAndConsume(tok::r_paren
);
4664 if (TryConsumeToken(tok::semi
))
4667 if (Tok
.is(tok::r_brace
)) {
4668 ExpectAndConsume(tok::semi
, diag::ext_expected_semi_decl_list
);
4672 ExpectAndConsume(tok::semi
, diag::err_expected_semi_decl_list
);
4673 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4674 SkipUntil(tok::r_brace
, StopAtSemi
| StopBeforeMatch
);
4675 // If we stopped at a ';', eat it.
4676 TryConsumeToken(tok::semi
);
4681 ParsedAttributes
attrs(AttrFactory
);
4682 // If attributes exist after struct contents, parse them.
4683 MaybeParseGNUAttributes(attrs
);
4685 SmallVector
<Decl
*, 32> FieldDecls(TagDecl
->fields());
4687 Actions
.ActOnFields(getCurScope(), RecordLoc
, TagDecl
, FieldDecls
,
4688 T
.getOpenLocation(), T
.getCloseLocation(), attrs
);
4690 Actions
.ActOnTagFinishDefinition(getCurScope(), TagDecl
, T
.getRange());
4693 /// ParseEnumSpecifier
4694 /// enum-specifier: [C99 6.7.2.2]
4695 /// 'enum' identifier[opt] '{' enumerator-list '}'
4696 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4697 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4698 /// '}' attributes[opt]
4699 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4701 /// 'enum' identifier
4702 /// [GNU] 'enum' attributes[opt] identifier
4704 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4705 /// [C++11] enum-head '{' enumerator-list ',' '}'
4707 /// enum-head: [C++11]
4708 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4709 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4710 /// identifier enum-base[opt]
4712 /// enum-key: [C++11]
4717 /// enum-base: [C++11]
4718 /// ':' type-specifier-seq
4720 /// [C++] elaborated-type-specifier:
4721 /// [C++] 'enum' nested-name-specifier[opt] identifier
4723 void Parser::ParseEnumSpecifier(SourceLocation StartLoc
, DeclSpec
&DS
,
4724 const ParsedTemplateInfo
&TemplateInfo
,
4725 AccessSpecifier AS
, DeclSpecContext DSC
) {
4726 // Parse the tag portion of this.
4727 if (Tok
.is(tok::code_completion
)) {
4728 // Code completion for an enum name.
4730 Actions
.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum
);
4731 DS
.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4735 // If attributes exist after tag, parse them.
4736 ParsedAttributes
attrs(AttrFactory
);
4737 MaybeParseAttributes(PAKM_GNU
| PAKM_Declspec
| PAKM_CXX11
, attrs
);
4739 SourceLocation ScopedEnumKWLoc
;
4740 bool IsScopedUsingClassTag
= false;
4742 // In C++11, recognize 'enum class' and 'enum struct'.
4743 if (Tok
.isOneOf(tok::kw_class
, tok::kw_struct
) && getLangOpts().CPlusPlus
) {
4744 Diag(Tok
, getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_scoped_enum
4745 : diag::ext_scoped_enum
);
4746 IsScopedUsingClassTag
= Tok
.is(tok::kw_class
);
4747 ScopedEnumKWLoc
= ConsumeToken();
4749 // Attributes are not allowed between these keywords. Diagnose,
4750 // but then just treat them like they appeared in the right place.
4751 ProhibitAttributes(attrs
);
4753 // They are allowed afterwards, though.
4754 MaybeParseAttributes(PAKM_GNU
| PAKM_Declspec
| PAKM_CXX11
, attrs
);
4757 // C++11 [temp.explicit]p12:
4758 // The usual access controls do not apply to names used to specify
4759 // explicit instantiations.
4760 // We extend this to also cover explicit specializations. Note that
4761 // we don't suppress if this turns out to be an elaborated type
4763 bool shouldDelayDiagsInTag
=
4764 (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
||
4765 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
);
4766 SuppressAccessChecks
diagsFromTag(*this, shouldDelayDiagsInTag
);
4768 // Determine whether this declaration is permitted to have an enum-base.
4769 AllowDefiningTypeSpec AllowEnumSpecifier
=
4770 isDefiningTypeSpecifierContext(DSC
, getLangOpts().CPlusPlus
);
4771 bool CanBeOpaqueEnumDeclaration
=
4772 DS
.isEmpty() && isOpaqueEnumDeclarationContext(DSC
);
4773 bool CanHaveEnumBase
= (getLangOpts().CPlusPlus11
|| getLangOpts().ObjC
||
4774 getLangOpts().MicrosoftExt
) &&
4775 (AllowEnumSpecifier
== AllowDefiningTypeSpec::Yes
||
4776 CanBeOpaqueEnumDeclaration
);
4778 CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
4779 if (getLangOpts().CPlusPlus
) {
4780 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4781 ColonProtectionRAIIObject
X(*this);
4784 if (ParseOptionalCXXScopeSpecifier(Spec
, /*ObjectType=*/nullptr,
4785 /*ObjectHasErrors=*/false,
4786 /*EnteringContext=*/true))
4789 if (Spec
.isSet() && Tok
.isNot(tok::identifier
)) {
4790 Diag(Tok
, diag::err_expected
) << tok::identifier
;
4791 DS
.SetTypeSpecError();
4792 if (Tok
.isNot(tok::l_brace
)) {
4793 // Has no name and is not a definition.
4794 // Skip the rest of this declarator, up until the comma or semicolon.
4795 SkipUntil(tok::comma
, StopAtSemi
);
4803 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4804 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::l_brace
) &&
4805 Tok
.isNot(tok::colon
)) {
4806 Diag(Tok
, diag::err_expected_either
) << tok::identifier
<< tok::l_brace
;
4808 DS
.SetTypeSpecError();
4809 // Skip the rest of this declarator, up until the comma or semicolon.
4810 SkipUntil(tok::comma
, StopAtSemi
);
4814 // If an identifier is present, consume and remember it.
4815 IdentifierInfo
*Name
= nullptr;
4816 SourceLocation NameLoc
;
4817 if (Tok
.is(tok::identifier
)) {
4818 Name
= Tok
.getIdentifierInfo();
4819 NameLoc
= ConsumeToken();
4822 if (!Name
&& ScopedEnumKWLoc
.isValid()) {
4823 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4824 // declaration of a scoped enumeration.
4825 Diag(Tok
, diag::err_scoped_enum_missing_identifier
);
4826 ScopedEnumKWLoc
= SourceLocation();
4827 IsScopedUsingClassTag
= false;
4830 // Okay, end the suppression area. We'll decide whether to emit the
4831 // diagnostics in a second.
4832 if (shouldDelayDiagsInTag
)
4833 diagsFromTag
.done();
4835 TypeResult BaseType
;
4836 SourceRange BaseRange
;
4838 bool CanBeBitfield
=
4839 getCurScope()->isClassScope() && ScopedEnumKWLoc
.isInvalid() && Name
;
4841 // Parse the fixed underlying type.
4842 if (Tok
.is(tok::colon
)) {
4843 // This might be an enum-base or part of some unrelated enclosing context.
4845 // 'enum E : base' is permitted in two circumstances:
4847 // 1) As a defining-type-specifier, when followed by '{'.
4848 // 2) As the sole constituent of a complete declaration -- when DS is empty
4849 // and the next token is ';'.
4851 // The restriction to defining-type-specifiers is important to allow parsing
4852 // a ? new enum E : int{}
4853 // _Generic(a, enum E : int{})
4856 // One additional consideration applies:
4858 // C++ [dcl.enum]p1:
4859 // A ':' following "enum nested-name-specifier[opt] identifier" within
4860 // the decl-specifier-seq of a member-declaration is parsed as part of
4863 // Other language modes supporting enumerations with fixed underlying types
4864 // do not have clear rules on this, so we disambiguate to determine whether
4865 // the tokens form a bit-field width or an enum-base.
4867 if (CanBeBitfield
&& !isEnumBase(CanBeOpaqueEnumDeclaration
)) {
4868 // Outside C++11, do not interpret the tokens as an enum-base if they do
4869 // not make sense as one. In C++11, it's an error if this happens.
4870 if (getLangOpts().CPlusPlus11
)
4871 Diag(Tok
.getLocation(), diag::err_anonymous_enum_bitfield
);
4872 } else if (CanHaveEnumBase
|| !ColonIsSacred
) {
4873 SourceLocation ColonLoc
= ConsumeToken();
4875 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4876 // because under -fms-extensions,
4878 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4879 DeclSpec
DS(AttrFactory
);
4880 // enum-base is not assumed to be a type and therefore requires the
4881 // typename keyword [p0634r3].
4882 ParseSpecifierQualifierList(DS
, ImplicitTypenameContext::No
, AS
,
4883 DeclSpecContext::DSC_type_specifier
);
4884 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
4885 DeclaratorContext::TypeName
);
4886 BaseType
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
4888 BaseRange
= SourceRange(ColonLoc
, DeclaratorInfo
.getSourceRange().getEnd());
4890 if (!getLangOpts().ObjC
) {
4891 if (getLangOpts().CPlusPlus11
)
4892 Diag(ColonLoc
, diag::warn_cxx98_compat_enum_fixed_underlying_type
)
4894 else if (getLangOpts().CPlusPlus
)
4895 Diag(ColonLoc
, diag::ext_cxx11_enum_fixed_underlying_type
)
4897 else if (getLangOpts().MicrosoftExt
)
4898 Diag(ColonLoc
, diag::ext_ms_c_enum_fixed_underlying_type
)
4901 Diag(ColonLoc
, diag::ext_clang_c_enum_fixed_underlying_type
)
4907 // There are four options here. If we have 'friend enum foo;' then this is a
4908 // friend declaration, and cannot have an accompanying definition. If we have
4909 // 'enum foo;', then this is a forward declaration. If we have
4910 // 'enum foo {...' then this is a definition. Otherwise we have something
4911 // like 'enum foo xyz', a reference.
4913 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4914 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4915 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4917 Sema::TagUseKind TUK
;
4918 if (AllowEnumSpecifier
== AllowDefiningTypeSpec::No
)
4919 TUK
= Sema::TUK_Reference
;
4920 else if (Tok
.is(tok::l_brace
)) {
4921 if (DS
.isFriendSpecified()) {
4922 Diag(Tok
.getLocation(), diag::err_friend_decl_defines_type
)
4923 << SourceRange(DS
.getFriendSpecLoc());
4925 SkipUntil(tok::r_brace
, StopAtSemi
);
4926 // Discard any other definition-only pieces.
4928 ScopedEnumKWLoc
= SourceLocation();
4929 IsScopedUsingClassTag
= false;
4930 BaseType
= TypeResult();
4931 TUK
= Sema::TUK_Friend
;
4933 TUK
= Sema::TUK_Definition
;
4935 } else if (!isTypeSpecifier(DSC
) &&
4936 (Tok
.is(tok::semi
) ||
4937 (Tok
.isAtStartOfLine() &&
4938 !isValidAfterTypeSpecifier(CanBeBitfield
)))) {
4939 // An opaque-enum-declaration is required to be standalone (no preceding or
4940 // following tokens in the declaration). Sema enforces this separately by
4941 // diagnosing anything else in the DeclSpec.
4942 TUK
= DS
.isFriendSpecified() ? Sema::TUK_Friend
: Sema::TUK_Declaration
;
4943 if (Tok
.isNot(tok::semi
)) {
4944 // A semicolon was missing after this declaration. Diagnose and recover.
4945 ExpectAndConsume(tok::semi
, diag::err_expected_after
, "enum");
4946 PP
.EnterToken(Tok
, /*IsReinject=*/true);
4947 Tok
.setKind(tok::semi
);
4950 TUK
= Sema::TUK_Reference
;
4953 bool IsElaboratedTypeSpecifier
=
4954 TUK
== Sema::TUK_Reference
|| TUK
== Sema::TUK_Friend
;
4956 // If this is an elaborated type specifier nested in a larger declaration,
4957 // and we delayed diagnostics before, just merge them into the current pool.
4958 if (TUK
== Sema::TUK_Reference
&& shouldDelayDiagsInTag
) {
4959 diagsFromTag
.redelay();
4962 MultiTemplateParamsArg TParams
;
4963 if (TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
&&
4964 TUK
!= Sema::TUK_Reference
) {
4965 if (!getLangOpts().CPlusPlus11
|| !SS
.isSet()) {
4966 // Skip the rest of this declarator, up until the comma or semicolon.
4967 Diag(Tok
, diag::err_enum_template
);
4968 SkipUntil(tok::comma
, StopAtSemi
);
4972 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
4973 // Enumerations can't be explicitly instantiated.
4974 DS
.SetTypeSpecError();
4975 Diag(StartLoc
, diag::err_explicit_instantiation_enum
);
4979 assert(TemplateInfo
.TemplateParams
&& "no template parameters");
4980 TParams
= MultiTemplateParamsArg(TemplateInfo
.TemplateParams
->data(),
4981 TemplateInfo
.TemplateParams
->size());
4982 SS
.setTemplateParamLists(TParams
);
4985 if (!Name
&& TUK
!= Sema::TUK_Definition
) {
4986 Diag(Tok
, diag::err_enumerator_unnamed_no_def
);
4988 DS
.SetTypeSpecError();
4989 // Skip the rest of this declarator, up until the comma or semicolon.
4990 SkipUntil(tok::comma
, StopAtSemi
);
4994 // An elaborated-type-specifier has a much more constrained grammar:
4996 // 'enum' nested-name-specifier[opt] identifier
4998 // If we parsed any other bits, reject them now.
5000 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5001 // or opaque-enum-declaration anywhere.
5002 if (IsElaboratedTypeSpecifier
&& !getLangOpts().MicrosoftExt
&&
5003 !getLangOpts().ObjC
) {
5004 ProhibitCXX11Attributes(attrs
, diag::err_attributes_not_allowed
,
5005 /*DiagnoseEmptyAttrs=*/true);
5006 if (BaseType
.isUsable())
5007 Diag(BaseRange
.getBegin(), diag::ext_enum_base_in_type_specifier
)
5008 << (AllowEnumSpecifier
== AllowDefiningTypeSpec::Yes
) << BaseRange
;
5009 else if (ScopedEnumKWLoc
.isValid())
5010 Diag(ScopedEnumKWLoc
, diag::ext_elaborated_enum_class
)
5011 << FixItHint::CreateRemoval(ScopedEnumKWLoc
) << IsScopedUsingClassTag
;
5014 stripTypeAttributesOffDeclSpec(attrs
, DS
, TUK
);
5016 Sema::SkipBodyInfo SkipBody
;
5017 if (!Name
&& TUK
== Sema::TUK_Definition
&& Tok
.is(tok::l_brace
) &&
5018 NextToken().is(tok::identifier
))
5019 SkipBody
= Actions
.shouldSkipAnonEnumBody(getCurScope(),
5020 NextToken().getIdentifierInfo(),
5021 NextToken().getLocation());
5024 bool IsDependent
= false;
5025 const char *PrevSpec
= nullptr;
5028 Actions
.ActOnTag(getCurScope(), DeclSpec::TST_enum
, TUK
, StartLoc
, SS
,
5029 Name
, NameLoc
, attrs
, AS
, DS
.getModulePrivateSpecLoc(),
5030 TParams
, Owned
, IsDependent
, ScopedEnumKWLoc
,
5031 IsScopedUsingClassTag
,
5032 BaseType
, DSC
== DeclSpecContext::DSC_type_specifier
,
5033 DSC
== DeclSpecContext::DSC_template_param
||
5034 DSC
== DeclSpecContext::DSC_template_type_arg
,
5035 OffsetOfState
, &SkipBody
).get();
5037 if (SkipBody
.ShouldSkip
) {
5038 assert(TUK
== Sema::TUK_Definition
&& "can only skip a definition");
5040 BalancedDelimiterTracker
T(*this, tok::l_brace
);
5044 if (DS
.SetTypeSpecType(DeclSpec::TST_enum
, StartLoc
,
5045 NameLoc
.isValid() ? NameLoc
: StartLoc
,
5046 PrevSpec
, DiagID
, TagDecl
, Owned
,
5047 Actions
.getASTContext().getPrintingPolicy()))
5048 Diag(StartLoc
, DiagID
) << PrevSpec
;
5053 // This enum has a dependent nested-name-specifier. Handle it as a
5056 DS
.SetTypeSpecError();
5057 Diag(Tok
, diag::err_expected_type_name_after_typename
);
5061 TypeResult Type
= Actions
.ActOnDependentTag(
5062 getCurScope(), DeclSpec::TST_enum
, TUK
, SS
, Name
, StartLoc
, NameLoc
);
5063 if (Type
.isInvalid()) {
5064 DS
.SetTypeSpecError();
5068 if (DS
.SetTypeSpecType(DeclSpec::TST_typename
, StartLoc
,
5069 NameLoc
.isValid() ? NameLoc
: StartLoc
,
5070 PrevSpec
, DiagID
, Type
.get(),
5071 Actions
.getASTContext().getPrintingPolicy()))
5072 Diag(StartLoc
, DiagID
) << PrevSpec
;
5078 // The action failed to produce an enumeration tag. If this is a
5079 // definition, consume the entire definition.
5080 if (Tok
.is(tok::l_brace
) && TUK
!= Sema::TUK_Reference
) {
5082 SkipUntil(tok::r_brace
, StopAtSemi
);
5085 DS
.SetTypeSpecError();
5089 if (Tok
.is(tok::l_brace
) && TUK
== Sema::TUK_Definition
) {
5090 Decl
*D
= SkipBody
.CheckSameAsPrevious
? SkipBody
.New
: TagDecl
;
5091 ParseEnumBody(StartLoc
, D
);
5092 if (SkipBody
.CheckSameAsPrevious
&&
5093 !Actions
.ActOnDuplicateDefinition(TagDecl
, SkipBody
)) {
5094 DS
.SetTypeSpecError();
5099 if (DS
.SetTypeSpecType(DeclSpec::TST_enum
, StartLoc
,
5100 NameLoc
.isValid() ? NameLoc
: StartLoc
,
5101 PrevSpec
, DiagID
, TagDecl
, Owned
,
5102 Actions
.getASTContext().getPrintingPolicy()))
5103 Diag(StartLoc
, DiagID
) << PrevSpec
;
5106 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
5107 /// enumerator-list:
5109 /// enumerator-list ',' enumerator
5111 /// enumeration-constant attributes[opt]
5112 /// enumeration-constant attributes[opt] '=' constant-expression
5113 /// enumeration-constant:
5116 void Parser::ParseEnumBody(SourceLocation StartLoc
, Decl
*EnumDecl
) {
5117 // Enter the scope of the enum body and start the definition.
5118 ParseScope
EnumScope(this, Scope::DeclScope
| Scope::EnumScope
);
5119 Actions
.ActOnTagStartDefinition(getCurScope(), EnumDecl
);
5121 BalancedDelimiterTracker
T(*this, tok::l_brace
);
5124 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5125 if (Tok
.is(tok::r_brace
) && !getLangOpts().CPlusPlus
)
5126 Diag(Tok
, diag::err_empty_enum
);
5128 SmallVector
<Decl
*, 32> EnumConstantDecls
;
5129 SmallVector
<SuppressAccessChecks
, 32> EnumAvailabilityDiags
;
5131 Decl
*LastEnumConstDecl
= nullptr;
5133 // Parse the enumerator-list.
5134 while (Tok
.isNot(tok::r_brace
)) {
5135 // Parse enumerator. If failed, try skipping till the start of the next
5136 // enumerator definition.
5137 if (Tok
.isNot(tok::identifier
)) {
5138 Diag(Tok
.getLocation(), diag::err_expected
) << tok::identifier
;
5139 if (SkipUntil(tok::comma
, tok::r_brace
, StopBeforeMatch
) &&
5140 TryConsumeToken(tok::comma
))
5144 IdentifierInfo
*Ident
= Tok
.getIdentifierInfo();
5145 SourceLocation IdentLoc
= ConsumeToken();
5147 // If attributes exist after the enumerator, parse them.
5148 ParsedAttributes
attrs(AttrFactory
);
5149 MaybeParseGNUAttributes(attrs
);
5150 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
5151 if (getLangOpts().CPlusPlus
)
5152 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus17
5153 ? diag::warn_cxx14_compat_ns_enum_attribute
5154 : diag::ext_ns_enum_attribute
)
5155 << 1 /*enumerator*/;
5156 ParseCXX11Attributes(attrs
);
5159 SourceLocation EqualLoc
;
5160 ExprResult AssignedVal
;
5161 EnumAvailabilityDiags
.emplace_back(*this);
5163 EnterExpressionEvaluationContext
ConstantEvaluated(
5164 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
5165 if (TryConsumeToken(tok::equal
, EqualLoc
)) {
5166 AssignedVal
= ParseConstantExpressionInExprEvalContext();
5167 if (AssignedVal
.isInvalid())
5168 SkipUntil(tok::comma
, tok::r_brace
, StopBeforeMatch
);
5171 // Install the enumerator constant into EnumDecl.
5172 Decl
*EnumConstDecl
= Actions
.ActOnEnumConstant(
5173 getCurScope(), EnumDecl
, LastEnumConstDecl
, IdentLoc
, Ident
, attrs
,
5174 EqualLoc
, AssignedVal
.get());
5175 EnumAvailabilityDiags
.back().done();
5177 EnumConstantDecls
.push_back(EnumConstDecl
);
5178 LastEnumConstDecl
= EnumConstDecl
;
5180 if (Tok
.is(tok::identifier
)) {
5181 // We're missing a comma between enumerators.
5182 SourceLocation Loc
= getEndOfPreviousToken();
5183 Diag(Loc
, diag::err_enumerator_list_missing_comma
)
5184 << FixItHint::CreateInsertion(Loc
, ", ");
5188 // Emumerator definition must be finished, only comma or r_brace are
5190 SourceLocation CommaLoc
;
5191 if (Tok
.isNot(tok::r_brace
) && !TryConsumeToken(tok::comma
, CommaLoc
)) {
5192 if (EqualLoc
.isValid())
5193 Diag(Tok
.getLocation(), diag::err_expected_either
) << tok::r_brace
5196 Diag(Tok
.getLocation(), diag::err_expected_end_of_enumerator
);
5197 if (SkipUntil(tok::comma
, tok::r_brace
, StopBeforeMatch
)) {
5198 if (TryConsumeToken(tok::comma
, CommaLoc
))
5205 // If comma is followed by r_brace, emit appropriate warning.
5206 if (Tok
.is(tok::r_brace
) && CommaLoc
.isValid()) {
5207 if (!getLangOpts().C99
&& !getLangOpts().CPlusPlus11
)
5208 Diag(CommaLoc
, getLangOpts().CPlusPlus
?
5209 diag::ext_enumerator_list_comma_cxx
:
5210 diag::ext_enumerator_list_comma_c
)
5211 << FixItHint::CreateRemoval(CommaLoc
);
5212 else if (getLangOpts().CPlusPlus11
)
5213 Diag(CommaLoc
, diag::warn_cxx98_compat_enumerator_list_comma
)
5214 << FixItHint::CreateRemoval(CommaLoc
);
5222 // If attributes exist after the identifier list, parse them.
5223 ParsedAttributes
attrs(AttrFactory
);
5224 MaybeParseGNUAttributes(attrs
);
5226 Actions
.ActOnEnumBody(StartLoc
, T
.getRange(), EnumDecl
, EnumConstantDecls
,
5227 getCurScope(), attrs
);
5229 // Now handle enum constant availability diagnostics.
5230 assert(EnumConstantDecls
.size() == EnumAvailabilityDiags
.size());
5231 for (size_t i
= 0, e
= EnumConstantDecls
.size(); i
!= e
; ++i
) {
5232 ParsingDeclRAIIObject
PD(*this, ParsingDeclRAIIObject::NoParent
);
5233 EnumAvailabilityDiags
[i
].redelay();
5234 PD
.complete(EnumConstantDecls
[i
]);
5238 Actions
.ActOnTagFinishDefinition(getCurScope(), EnumDecl
, T
.getRange());
5240 // The next token must be valid after an enum definition. If not, a ';'
5241 // was probably forgotten.
5242 bool CanBeBitfield
= getCurScope()->isClassScope();
5243 if (!isValidAfterTypeSpecifier(CanBeBitfield
)) {
5244 ExpectAndConsume(tok::semi
, diag::err_expected_after
, "enum");
5245 // Push this token back into the preprocessor and change our current token
5246 // to ';' so that the rest of the code recovers as though there were an
5247 // ';' after the definition.
5248 PP
.EnterToken(Tok
, /*IsReinject=*/true);
5249 Tok
.setKind(tok::semi
);
5253 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5254 /// is definitely a type-specifier. Return false if it isn't part of a type
5255 /// specifier or if we're not sure.
5256 bool Parser::isKnownToBeTypeSpecifier(const Token
&Tok
) const {
5257 switch (Tok
.getKind()) {
5258 default: return false;
5262 case tok::kw___int64
:
5263 case tok::kw___int128
:
5264 case tok::kw_signed
:
5265 case tok::kw_unsigned
:
5266 case tok::kw__Complex
:
5267 case tok::kw__Imaginary
:
5270 case tok::kw_wchar_t
:
5271 case tok::kw_char8_t
:
5272 case tok::kw_char16_t
:
5273 case tok::kw_char32_t
:
5275 case tok::kw__ExtInt
:
5276 case tok::kw__BitInt
:
5277 case tok::kw___bf16
:
5280 case tok::kw_double
:
5281 case tok::kw__Accum
:
5282 case tok::kw__Fract
:
5283 case tok::kw__Float16
:
5284 case tok::kw___float128
:
5285 case tok::kw___ibm128
:
5288 case tok::kw__Decimal32
:
5289 case tok::kw__Decimal64
:
5290 case tok::kw__Decimal128
:
5291 case tok::kw___vector
:
5292 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5293 #include "clang/Basic/OpenCLImageTypes.def"
5295 // struct-or-union-specifier (C99) or class-specifier (C++)
5297 case tok::kw_struct
:
5298 case tok::kw___interface
:
5304 case tok::annot_typename
:
5309 /// isTypeSpecifierQualifier - Return true if the current token could be the
5310 /// start of a specifier-qualifier-list.
5311 bool Parser::isTypeSpecifierQualifier() {
5312 switch (Tok
.getKind()) {
5313 default: return false;
5315 case tok::identifier
: // foo::bar
5316 if (TryAltiVecVectorToken())
5319 case tok::kw_typename
: // typename T::type
5320 // Annotate typenames and C++ scope specifiers. If we get one, just
5321 // recurse to handle whatever we get.
5322 if (TryAnnotateTypeOrScopeToken())
5324 if (Tok
.is(tok::identifier
))
5326 return isTypeSpecifierQualifier();
5328 case tok::coloncolon
: // ::foo::bar
5329 if (NextToken().is(tok::kw_new
) || // ::new
5330 NextToken().is(tok::kw_delete
)) // ::delete
5333 if (TryAnnotateTypeOrScopeToken())
5335 return isTypeSpecifierQualifier();
5337 // GNU attributes support.
5338 case tok::kw___attribute
:
5339 // C2x/GNU typeof support.
5340 case tok::kw_typeof
:
5341 case tok::kw_typeof_unqual
:
5346 case tok::kw___int64
:
5347 case tok::kw___int128
:
5348 case tok::kw_signed
:
5349 case tok::kw_unsigned
:
5350 case tok::kw__Complex
:
5351 case tok::kw__Imaginary
:
5354 case tok::kw_wchar_t
:
5355 case tok::kw_char8_t
:
5356 case tok::kw_char16_t
:
5357 case tok::kw_char32_t
:
5359 case tok::kw__ExtInt
:
5360 case tok::kw__BitInt
:
5362 case tok::kw___bf16
:
5364 case tok::kw_double
:
5365 case tok::kw__Accum
:
5366 case tok::kw__Fract
:
5367 case tok::kw__Float16
:
5368 case tok::kw___float128
:
5369 case tok::kw___ibm128
:
5372 case tok::kw__Decimal32
:
5373 case tok::kw__Decimal64
:
5374 case tok::kw__Decimal128
:
5375 case tok::kw___vector
:
5376 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5377 #include "clang/Basic/OpenCLImageTypes.def"
5379 // struct-or-union-specifier (C99) or class-specifier (C++)
5381 case tok::kw_struct
:
5382 case tok::kw___interface
:
5389 case tok::kw_volatile
:
5390 case tok::kw_restrict
:
5393 // Debugger support.
5394 case tok::kw___unknown_anytype
:
5397 case tok::annot_typename
:
5400 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5402 return getLangOpts().ObjC
;
5404 case tok::kw___cdecl
:
5405 case tok::kw___stdcall
:
5406 case tok::kw___fastcall
:
5407 case tok::kw___thiscall
:
5408 case tok::kw___regcall
:
5409 case tok::kw___vectorcall
:
5411 case tok::kw___ptr64
:
5412 case tok::kw___ptr32
:
5413 case tok::kw___pascal
:
5414 case tok::kw___unaligned
:
5416 case tok::kw__Nonnull
:
5417 case tok::kw__Nullable
:
5418 case tok::kw__Nullable_result
:
5419 case tok::kw__Null_unspecified
:
5421 case tok::kw___kindof
:
5423 case tok::kw___private
:
5424 case tok::kw___local
:
5425 case tok::kw___global
:
5426 case tok::kw___constant
:
5427 case tok::kw___generic
:
5428 case tok::kw___read_only
:
5429 case tok::kw___read_write
:
5430 case tok::kw___write_only
:
5431 case tok::kw___funcref
:
5432 case tok::kw_groupshared
:
5435 case tok::kw_private
:
5436 return getLangOpts().OpenCL
;
5439 case tok::kw__Atomic
:
5444 Parser::DeclGroupPtrTy
Parser::ParseTopLevelStmtDecl() {
5445 assert(PP
.isIncrementalProcessingEnabled() && "Not in incremental mode");
5447 // Parse a top-level-stmt.
5448 Parser::StmtVector Stmts
;
5449 ParsedStmtContext SubStmtCtx
= ParsedStmtContext();
5450 Actions
.PushFunctionScope();
5451 StmtResult R
= ParseStatementOrDeclaration(Stmts
, SubStmtCtx
);
5452 Actions
.PopFunctionScopeInfo();
5456 SmallVector
<Decl
*, 2> DeclsInGroup
;
5457 DeclsInGroup
.push_back(Actions
.ActOnTopLevelStmtDecl(R
.get()));
5458 // Currently happens for things like -fms-extensions and use `__if_exists`.
5459 for (Stmt
*S
: Stmts
)
5460 DeclsInGroup
.push_back(Actions
.ActOnTopLevelStmtDecl(S
));
5462 return Actions
.BuildDeclaratorGroup(DeclsInGroup
);
5465 /// isDeclarationSpecifier() - Return true if the current token is part of a
5466 /// declaration specifier.
5468 /// \param AllowImplicitTypename whether this is a context where T::type [T
5469 /// dependent] can appear.
5470 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5471 /// this check is to disambiguate between an expression and a declaration.
5472 bool Parser::isDeclarationSpecifier(
5473 ImplicitTypenameContext AllowImplicitTypename
,
5474 bool DisambiguatingWithExpression
) {
5475 switch (Tok
.getKind()) {
5476 default: return false;
5478 // OpenCL 2.0 and later define this keyword.
5480 return getLangOpts().OpenCL
&&
5481 getLangOpts().getOpenCLCompatibleVersion() >= 200;
5483 case tok::identifier
: // foo::bar
5484 // Unfortunate hack to support "Class.factoryMethod" notation.
5485 if (getLangOpts().ObjC
&& NextToken().is(tok::period
))
5487 if (TryAltiVecVectorToken())
5490 case tok::kw_decltype
: // decltype(T())::type
5491 case tok::kw_typename
: // typename T::type
5492 // Annotate typenames and C++ scope specifiers. If we get one, just
5493 // recurse to handle whatever we get.
5494 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename
))
5496 if (TryAnnotateTypeConstraint())
5498 if (Tok
.is(tok::identifier
))
5501 // If we're in Objective-C and we have an Objective-C class type followed
5502 // by an identifier and then either ':' or ']', in a place where an
5503 // expression is permitted, then this is probably a class message send
5504 // missing the initial '['. In this case, we won't consider this to be
5505 // the start of a declaration.
5506 if (DisambiguatingWithExpression
&&
5507 isStartOfObjCClassMessageMissingOpenBracket())
5510 return isDeclarationSpecifier(AllowImplicitTypename
);
5512 case tok::coloncolon
: // ::foo::bar
5513 if (!getLangOpts().CPlusPlus
)
5515 if (NextToken().is(tok::kw_new
) || // ::new
5516 NextToken().is(tok::kw_delete
)) // ::delete
5519 // Annotate typenames and C++ scope specifiers. If we get one, just
5520 // recurse to handle whatever we get.
5521 if (TryAnnotateTypeOrScopeToken())
5523 return isDeclarationSpecifier(ImplicitTypenameContext::No
);
5525 // storage-class-specifier
5526 case tok::kw_typedef
:
5527 case tok::kw_extern
:
5528 case tok::kw___private_extern__
:
5529 case tok::kw_static
:
5531 case tok::kw___auto_type
:
5532 case tok::kw_register
:
5533 case tok::kw___thread
:
5534 case tok::kw_thread_local
:
5535 case tok::kw__Thread_local
:
5538 case tok::kw___module_private__
:
5541 case tok::kw___unknown_anytype
:
5546 case tok::kw___int64
:
5547 case tok::kw___int128
:
5548 case tok::kw_signed
:
5549 case tok::kw_unsigned
:
5550 case tok::kw__Complex
:
5551 case tok::kw__Imaginary
:
5554 case tok::kw_wchar_t
:
5555 case tok::kw_char8_t
:
5556 case tok::kw_char16_t
:
5557 case tok::kw_char32_t
:
5560 case tok::kw__ExtInt
:
5561 case tok::kw__BitInt
:
5563 case tok::kw___bf16
:
5565 case tok::kw_double
:
5566 case tok::kw__Accum
:
5567 case tok::kw__Fract
:
5568 case tok::kw__Float16
:
5569 case tok::kw___float128
:
5570 case tok::kw___ibm128
:
5573 case tok::kw__Decimal32
:
5574 case tok::kw__Decimal64
:
5575 case tok::kw__Decimal128
:
5576 case tok::kw___vector
:
5578 // struct-or-union-specifier (C99) or class-specifier (C++)
5580 case tok::kw_struct
:
5582 case tok::kw___interface
:
5588 case tok::kw_volatile
:
5589 case tok::kw_restrict
:
5592 // function-specifier
5593 case tok::kw_inline
:
5594 case tok::kw_virtual
:
5595 case tok::kw_explicit
:
5596 case tok::kw__Noreturn
:
5598 // alignment-specifier
5599 case tok::kw__Alignas
:
5602 case tok::kw_friend
:
5604 // static_assert-declaration
5605 case tok::kw_static_assert
:
5606 case tok::kw__Static_assert
:
5608 // C2x/GNU typeof support.
5609 case tok::kw_typeof
:
5610 case tok::kw_typeof_unqual
:
5613 case tok::kw___attribute
:
5615 // C++11 decltype and constexpr.
5616 case tok::annot_decltype
:
5617 case tok::kw_constexpr
:
5619 // C++20 consteval and constinit.
5620 case tok::kw_consteval
:
5621 case tok::kw_constinit
:
5624 case tok::kw__Atomic
:
5627 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5629 return getLangOpts().ObjC
;
5632 case tok::annot_typename
:
5633 return !DisambiguatingWithExpression
||
5634 !isStartOfObjCClassMessageMissingOpenBracket();
5636 // placeholder-type-specifier
5637 case tok::annot_template_id
: {
5638 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
5639 if (TemplateId
->hasInvalidName())
5641 // FIXME: What about type templates that have only been annotated as
5642 // annot_template_id, not as annot_typename?
5643 return isTypeConstraintAnnotation() &&
5644 (NextToken().is(tok::kw_auto
) || NextToken().is(tok::kw_decltype
));
5647 case tok::annot_cxxscope
: {
5648 TemplateIdAnnotation
*TemplateId
=
5649 NextToken().is(tok::annot_template_id
)
5650 ? takeTemplateIdAnnotation(NextToken())
5652 if (TemplateId
&& TemplateId
->hasInvalidName())
5654 // FIXME: What about type templates that have only been annotated as
5655 // annot_template_id, not as annot_typename?
5656 if (NextToken().is(tok::identifier
) && TryAnnotateTypeConstraint())
5658 return isTypeConstraintAnnotation() &&
5659 GetLookAheadToken(2).isOneOf(tok::kw_auto
, tok::kw_decltype
);
5662 case tok::kw___declspec
:
5663 case tok::kw___cdecl
:
5664 case tok::kw___stdcall
:
5665 case tok::kw___fastcall
:
5666 case tok::kw___thiscall
:
5667 case tok::kw___regcall
:
5668 case tok::kw___vectorcall
:
5670 case tok::kw___sptr
:
5671 case tok::kw___uptr
:
5672 case tok::kw___ptr64
:
5673 case tok::kw___ptr32
:
5674 case tok::kw___forceinline
:
5675 case tok::kw___pascal
:
5676 case tok::kw___unaligned
:
5678 case tok::kw__Nonnull
:
5679 case tok::kw__Nullable
:
5680 case tok::kw__Nullable_result
:
5681 case tok::kw__Null_unspecified
:
5683 case tok::kw___kindof
:
5685 case tok::kw___private
:
5686 case tok::kw___local
:
5687 case tok::kw___global
:
5688 case tok::kw___constant
:
5689 case tok::kw___generic
:
5690 case tok::kw___read_only
:
5691 case tok::kw___read_write
:
5692 case tok::kw___write_only
:
5693 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5694 #include "clang/Basic/OpenCLImageTypes.def"
5696 case tok::kw___funcref
:
5697 case tok::kw_groupshared
:
5700 case tok::kw_private
:
5701 return getLangOpts().OpenCL
;
5705 bool Parser::isConstructorDeclarator(bool IsUnqualified
, bool DeductionGuide
,
5706 DeclSpec::FriendSpecified IsFriend
,
5707 const ParsedTemplateInfo
*TemplateInfo
) {
5708 TentativeParsingAction
TPA(*this);
5710 // Parse the C++ scope specifier.
5712 if (TemplateInfo
&& TemplateInfo
->TemplateParams
)
5713 SS
.setTemplateParamLists(*TemplateInfo
->TemplateParams
);
5715 if (ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
5716 /*ObjectHasErrors=*/false,
5717 /*EnteringContext=*/true)) {
5722 // Parse the constructor name.
5723 if (Tok
.is(tok::identifier
)) {
5724 // We already know that we have a constructor name; just consume
5727 } else if (Tok
.is(tok::annot_template_id
)) {
5728 ConsumeAnnotationToken();
5734 // There may be attributes here, appertaining to the constructor name or type
5735 // we just stepped past.
5736 SkipCXX11Attributes();
5738 // Current class name must be followed by a left parenthesis.
5739 if (Tok
.isNot(tok::l_paren
)) {
5745 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5746 // that we have a constructor.
5747 if (Tok
.is(tok::r_paren
) ||
5748 (Tok
.is(tok::ellipsis
) && NextToken().is(tok::r_paren
))) {
5753 // A C++11 attribute here signals that we have a constructor, and is an
5754 // attribute on the first constructor parameter.
5755 if (getLangOpts().CPlusPlus11
&&
5756 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5757 /*OuterMightBeMessageSend*/ true)) {
5762 // If we need to, enter the specified scope.
5763 DeclaratorScopeObj
DeclScopeObj(*this, SS
);
5764 if (SS
.isSet() && Actions
.ShouldEnterDeclaratorScope(getCurScope(), SS
))
5765 DeclScopeObj
.EnterDeclaratorScope();
5767 // Optionally skip Microsoft attributes.
5768 ParsedAttributes
Attrs(AttrFactory
);
5769 MaybeParseMicrosoftAttributes(Attrs
);
5771 // Check whether the next token(s) are part of a declaration
5772 // specifier, in which case we have the start of a parameter and,
5773 // therefore, we know that this is a constructor.
5774 // Due to an ambiguity with implicit typename, the above is not enough.
5775 // Additionally, check to see if we are a friend.
5776 bool IsConstructor
= false;
5777 if (isDeclarationSpecifier(IsFriend
? ImplicitTypenameContext::No
5778 : ImplicitTypenameContext::Yes
))
5779 IsConstructor
= true;
5780 else if (Tok
.is(tok::identifier
) ||
5781 (Tok
.is(tok::annot_cxxscope
) && NextToken().is(tok::identifier
))) {
5782 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5783 // This might be a parenthesized member name, but is more likely to
5784 // be a constructor declaration with an invalid argument type. Keep
5786 if (Tok
.is(tok::annot_cxxscope
))
5787 ConsumeAnnotationToken();
5790 // If this is not a constructor, we must be parsing a declarator,
5791 // which must have one of the following syntactic forms (see the
5792 // grammar extract at the start of ParseDirectDeclarator):
5793 switch (Tok
.getKind()) {
5798 // C(X [ [attribute]]);
5799 case tok::coloncolon
:
5802 // Assume this isn't a constructor, rather than assuming it's a
5803 // constructor with an unnamed parameter of an ill-formed type.
5809 // Skip past the right-paren and any following attributes to get to
5810 // the function body or trailing-return-type.
5812 SkipCXX11Attributes();
5814 if (DeductionGuide
) {
5815 // C(X) -> ... is a deduction guide.
5816 IsConstructor
= Tok
.is(tok::arrow
);
5819 if (Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
)) {
5820 // Assume these were meant to be constructors:
5821 // C(X) : (the name of a bit-field cannot be parenthesized).
5822 // C(X) try (this is otherwise ill-formed).
5823 IsConstructor
= true;
5825 if (Tok
.is(tok::semi
) || Tok
.is(tok::l_brace
)) {
5826 // If we have a constructor name within the class definition,
5827 // assume these were meant to be constructors:
5830 // ... because otherwise we would be declaring a non-static data
5831 // member that is ill-formed because it's of the same type as its
5832 // surrounding class.
5834 // FIXME: We can actually do this whether or not the name is qualified,
5835 // because if it is qualified in this context it must be being used as
5836 // a constructor name.
5837 // currently, so we're somewhat conservative here.
5838 IsConstructor
= IsUnqualified
;
5843 IsConstructor
= true;
5849 return IsConstructor
;
5852 /// ParseTypeQualifierListOpt
5853 /// type-qualifier-list: [C99 6.7.5]
5855 /// [vendor] attributes
5856 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5857 /// type-qualifier-list type-qualifier
5858 /// [vendor] type-qualifier-list attributes
5859 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5860 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5861 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5862 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5863 /// AttrRequirements bitmask values.
5864 void Parser::ParseTypeQualifierListOpt(
5865 DeclSpec
&DS
, unsigned AttrReqs
, bool AtomicAllowed
,
5866 bool IdentifierRequired
,
5867 std::optional
<llvm::function_ref
<void()>> CodeCompletionHandler
) {
5868 if (standardAttributesAllowed() && (AttrReqs
& AR_CXX11AttributesParsed
) &&
5869 isCXX11AttributeSpecifier()) {
5870 ParsedAttributes
Attrs(AttrFactory
);
5871 ParseCXX11Attributes(Attrs
);
5872 DS
.takeAttributesFrom(Attrs
);
5875 SourceLocation EndLoc
;
5878 bool isInvalid
= false;
5879 const char *PrevSpec
= nullptr;
5880 unsigned DiagID
= 0;
5881 SourceLocation Loc
= Tok
.getLocation();
5883 switch (Tok
.getKind()) {
5884 case tok::code_completion
:
5886 if (CodeCompletionHandler
)
5887 (*CodeCompletionHandler
)();
5889 Actions
.CodeCompleteTypeQualifiers(DS
);
5893 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_const
, Loc
, PrevSpec
, DiagID
,
5896 case tok::kw_volatile
:
5897 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_volatile
, Loc
, PrevSpec
, DiagID
,
5900 case tok::kw_restrict
:
5901 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_restrict
, Loc
, PrevSpec
, DiagID
,
5904 case tok::kw__Atomic
:
5906 goto DoneWithTypeQuals
;
5907 if (!getLangOpts().C11
)
5908 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
5909 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_atomic
, Loc
, PrevSpec
, DiagID
,
5913 // OpenCL qualifiers:
5914 case tok::kw_private
:
5915 if (!getLangOpts().OpenCL
)
5916 goto DoneWithTypeQuals
;
5918 case tok::kw___private
:
5919 case tok::kw___global
:
5920 case tok::kw___local
:
5921 case tok::kw___constant
:
5922 case tok::kw___generic
:
5923 case tok::kw___read_only
:
5924 case tok::kw___write_only
:
5925 case tok::kw___read_write
:
5926 ParseOpenCLQualifiers(DS
.getAttributes());
5929 case tok::kw_groupshared
:
5930 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
5931 ParseHLSLQualifiers(DS
.getAttributes());
5934 case tok::kw___unaligned
:
5935 isInvalid
= DS
.SetTypeQual(DeclSpec::TQ_unaligned
, Loc
, PrevSpec
, DiagID
,
5938 case tok::kw___uptr
:
5939 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5940 // with the MS modifier keyword.
5941 if ((AttrReqs
& AR_DeclspecAttributesParsed
) && !getLangOpts().CPlusPlus
&&
5942 IdentifierRequired
&& DS
.isEmpty() && NextToken().is(tok::semi
)) {
5943 if (TryKeywordIdentFallback(false))
5947 case tok::kw___sptr
:
5949 case tok::kw___ptr64
:
5950 case tok::kw___ptr32
:
5951 case tok::kw___cdecl
:
5952 case tok::kw___stdcall
:
5953 case tok::kw___fastcall
:
5954 case tok::kw___thiscall
:
5955 case tok::kw___regcall
:
5956 case tok::kw___vectorcall
:
5957 if (AttrReqs
& AR_DeclspecAttributesParsed
) {
5958 ParseMicrosoftTypeAttributes(DS
.getAttributes());
5961 goto DoneWithTypeQuals
;
5963 case tok::kw___funcref
:
5964 ParseWebAssemblyFuncrefTypeAttribute(DS
.getAttributes());
5966 goto DoneWithTypeQuals
;
5968 case tok::kw___pascal
:
5969 if (AttrReqs
& AR_VendorAttributesParsed
) {
5970 ParseBorlandTypeAttributes(DS
.getAttributes());
5973 goto DoneWithTypeQuals
;
5975 // Nullability type specifiers.
5976 case tok::kw__Nonnull
:
5977 case tok::kw__Nullable
:
5978 case tok::kw__Nullable_result
:
5979 case tok::kw__Null_unspecified
:
5980 ParseNullabilityTypeSpecifiers(DS
.getAttributes());
5983 // Objective-C 'kindof' types.
5984 case tok::kw___kindof
:
5985 DS
.getAttributes().addNew(Tok
.getIdentifierInfo(), Loc
, nullptr, Loc
,
5986 nullptr, 0, tok::kw___kindof
);
5987 (void)ConsumeToken();
5990 case tok::kw___attribute
:
5991 if (AttrReqs
& AR_GNUAttributesParsedAndRejected
)
5992 // When GNU attributes are expressly forbidden, diagnose their usage.
5993 Diag(Tok
, diag::err_attributes_not_allowed
);
5995 // Parse the attributes even if they are rejected to ensure that error
5996 // recovery is graceful.
5997 if (AttrReqs
& AR_GNUAttributesParsed
||
5998 AttrReqs
& AR_GNUAttributesParsedAndRejected
) {
5999 ParseGNUAttributes(DS
.getAttributes());
6000 continue; // do *not* consume the next token!
6002 // otherwise, FALL THROUGH!
6006 // If this is not a type-qualifier token, we're done reading type
6007 // qualifiers. First verify that DeclSpec's are consistent.
6008 DS
.Finish(Actions
, Actions
.getASTContext().getPrintingPolicy());
6009 if (EndLoc
.isValid())
6010 DS
.SetRangeEnd(EndLoc
);
6014 // If the specifier combination wasn't legal, issue a diagnostic.
6016 assert(PrevSpec
&& "Method did not return previous specifier!");
6017 Diag(Tok
, DiagID
) << PrevSpec
;
6019 EndLoc
= ConsumeToken();
6023 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
6024 void Parser::ParseDeclarator(Declarator
&D
) {
6025 /// This implements the 'declarator' production in the C grammar, then checks
6026 /// for well-formedness and issues diagnostics.
6027 Actions
.runWithSufficientStackSpace(D
.getBeginLoc(), [&] {
6028 ParseDeclaratorInternal(D
, &Parser::ParseDirectDeclarator
);
6032 static bool isPtrOperatorToken(tok::TokenKind Kind
, const LangOptions
&Lang
,
6033 DeclaratorContext TheContext
) {
6034 if (Kind
== tok::star
|| Kind
== tok::caret
)
6037 // OpenCL 2.0 and later define this keyword.
6038 if (Kind
== tok::kw_pipe
&& Lang
.OpenCL
&&
6039 Lang
.getOpenCLCompatibleVersion() >= 200)
6042 if (!Lang
.CPlusPlus
)
6045 if (Kind
== tok::amp
)
6048 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6049 // But we must not parse them in conversion-type-ids and new-type-ids, since
6050 // those can be legitimately followed by a && operator.
6051 // (The same thing can in theory happen after a trailing-return-type, but
6052 // since those are a C++11 feature, there is no rejects-valid issue there.)
6053 if (Kind
== tok::ampamp
)
6054 return Lang
.CPlusPlus11
|| (TheContext
!= DeclaratorContext::ConversionId
&&
6055 TheContext
!= DeclaratorContext::CXXNew
);
6060 // Indicates whether the given declarator is a pipe declarator.
6061 static bool isPipeDeclarator(const Declarator
&D
) {
6062 const unsigned NumTypes
= D
.getNumTypeObjects();
6064 for (unsigned Idx
= 0; Idx
!= NumTypes
; ++Idx
)
6065 if (DeclaratorChunk::Pipe
== D
.getTypeObject(Idx
).Kind
)
6071 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
6072 /// is parsed by the function passed to it. Pass null, and the direct-declarator
6073 /// isn't parsed at all, making this function effectively parse the C++
6074 /// ptr-operator production.
6076 /// If the grammar of this construct is extended, matching changes must also be
6077 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
6078 /// isConstructorDeclarator.
6080 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
6081 /// [C] pointer[opt] direct-declarator
6082 /// [C++] direct-declarator
6083 /// [C++] ptr-operator declarator
6085 /// pointer: [C99 6.7.5]
6086 /// '*' type-qualifier-list[opt]
6087 /// '*' type-qualifier-list[opt] pointer
6090 /// '*' cv-qualifier-seq[opt]
6093 /// [GNU] '&' restrict[opt] attributes[opt]
6094 /// [GNU?] '&&' restrict[opt] attributes[opt]
6095 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
6096 void Parser::ParseDeclaratorInternal(Declarator
&D
,
6097 DirectDeclParseFunction DirectDeclParser
) {
6098 if (Diags
.hasAllExtensionsSilenced())
6101 // C++ member pointers start with a '::' or a nested-name.
6102 // Member pointers get special handling, since there's no place for the
6103 // scope spec in the generic path below.
6104 if (getLangOpts().CPlusPlus
&&
6105 (Tok
.is(tok::coloncolon
) || Tok
.is(tok::kw_decltype
) ||
6106 (Tok
.is(tok::identifier
) &&
6107 (NextToken().is(tok::coloncolon
) || NextToken().is(tok::less
))) ||
6108 Tok
.is(tok::annot_cxxscope
))) {
6109 bool EnteringContext
= D
.getContext() == DeclaratorContext::File
||
6110 D
.getContext() == DeclaratorContext::Member
;
6112 SS
.setTemplateParamLists(D
.getTemplateParameterLists());
6113 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
6114 /*ObjectHasErrors=*/false, EnteringContext
);
6116 if (SS
.isNotEmpty()) {
6117 if (Tok
.isNot(tok::star
)) {
6118 // The scope spec really belongs to the direct-declarator.
6119 if (D
.mayHaveIdentifier())
6120 D
.getCXXScopeSpec() = SS
;
6122 AnnotateScopeToken(SS
, true);
6124 if (DirectDeclParser
)
6125 (this->*DirectDeclParser
)(D
);
6130 checkCompoundToken(SS
.getEndLoc(), tok::coloncolon
,
6131 CompoundToken::MemberPtr
);
6134 SourceLocation StarLoc
= ConsumeToken();
6135 D
.SetRangeEnd(StarLoc
);
6136 DeclSpec
DS(AttrFactory
);
6137 ParseTypeQualifierListOpt(DS
);
6138 D
.ExtendWithDeclSpec(DS
);
6140 // Recurse to parse whatever is left.
6141 Actions
.runWithSufficientStackSpace(D
.getBeginLoc(), [&] {
6142 ParseDeclaratorInternal(D
, DirectDeclParser
);
6145 // Sema will have to catch (syntactically invalid) pointers into global
6146 // scope. It has to catch pointers into namespace scope anyway.
6147 D
.AddTypeInfo(DeclaratorChunk::getMemberPointer(
6148 SS
, DS
.getTypeQualifiers(), StarLoc
, DS
.getEndLoc()),
6149 std::move(DS
.getAttributes()),
6150 /* Don't replace range end. */ SourceLocation());
6155 tok::TokenKind Kind
= Tok
.getKind();
6157 if (D
.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D
)) {
6158 DeclSpec
DS(AttrFactory
);
6159 ParseTypeQualifierListOpt(DS
);
6162 DeclaratorChunk::getPipe(DS
.getTypeQualifiers(), DS
.getPipeLoc()),
6163 std::move(DS
.getAttributes()), SourceLocation());
6166 // Not a pointer, C++ reference, or block.
6167 if (!isPtrOperatorToken(Kind
, getLangOpts(), D
.getContext())) {
6168 if (DirectDeclParser
)
6169 (this->*DirectDeclParser
)(D
);
6173 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6174 // '&&' -> rvalue reference
6175 SourceLocation Loc
= ConsumeToken(); // Eat the *, ^, & or &&.
6178 if (Kind
== tok::star
|| Kind
== tok::caret
) {
6180 DeclSpec
DS(AttrFactory
);
6182 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6183 // C++11 attributes are allowed.
6184 unsigned Reqs
= AR_CXX11AttributesParsed
| AR_DeclspecAttributesParsed
|
6185 ((D
.getContext() != DeclaratorContext::CXXNew
)
6186 ? AR_GNUAttributesParsed
6187 : AR_GNUAttributesParsedAndRejected
);
6188 ParseTypeQualifierListOpt(DS
, Reqs
, true, !D
.mayOmitIdentifier());
6189 D
.ExtendWithDeclSpec(DS
);
6191 // Recursively parse the declarator.
6192 Actions
.runWithSufficientStackSpace(
6193 D
.getBeginLoc(), [&] { ParseDeclaratorInternal(D
, DirectDeclParser
); });
6194 if (Kind
== tok::star
)
6195 // Remember that we parsed a pointer type, and remember the type-quals.
6196 D
.AddTypeInfo(DeclaratorChunk::getPointer(
6197 DS
.getTypeQualifiers(), Loc
, DS
.getConstSpecLoc(),
6198 DS
.getVolatileSpecLoc(), DS
.getRestrictSpecLoc(),
6199 DS
.getAtomicSpecLoc(), DS
.getUnalignedSpecLoc()),
6200 std::move(DS
.getAttributes()), SourceLocation());
6202 // Remember that we parsed a Block type, and remember the type-quals.
6204 DeclaratorChunk::getBlockPointer(DS
.getTypeQualifiers(), Loc
),
6205 std::move(DS
.getAttributes()), SourceLocation());
6208 DeclSpec
DS(AttrFactory
);
6210 // Complain about rvalue references in C++03, but then go on and build
6212 if (Kind
== tok::ampamp
)
6213 Diag(Loc
, getLangOpts().CPlusPlus11
?
6214 diag::warn_cxx98_compat_rvalue_reference
:
6215 diag::ext_rvalue_reference
);
6217 // GNU-style and C++11 attributes are allowed here, as is restrict.
6218 ParseTypeQualifierListOpt(DS
);
6219 D
.ExtendWithDeclSpec(DS
);
6221 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6222 // cv-qualifiers are introduced through the use of a typedef or of a
6223 // template type argument, in which case the cv-qualifiers are ignored.
6224 if (DS
.getTypeQualifiers() != DeclSpec::TQ_unspecified
) {
6225 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
6226 Diag(DS
.getConstSpecLoc(),
6227 diag::err_invalid_reference_qualifier_application
) << "const";
6228 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
6229 Diag(DS
.getVolatileSpecLoc(),
6230 diag::err_invalid_reference_qualifier_application
) << "volatile";
6231 // 'restrict' is permitted as an extension.
6232 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
6233 Diag(DS
.getAtomicSpecLoc(),
6234 diag::err_invalid_reference_qualifier_application
) << "_Atomic";
6237 // Recursively parse the declarator.
6238 Actions
.runWithSufficientStackSpace(
6239 D
.getBeginLoc(), [&] { ParseDeclaratorInternal(D
, DirectDeclParser
); });
6241 if (D
.getNumTypeObjects() > 0) {
6242 // C++ [dcl.ref]p4: There shall be no references to references.
6243 DeclaratorChunk
& InnerChunk
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
6244 if (InnerChunk
.Kind
== DeclaratorChunk::Reference
) {
6245 if (const IdentifierInfo
*II
= D
.getIdentifier())
6246 Diag(InnerChunk
.Loc
, diag::err_illegal_decl_reference_to_reference
)
6249 Diag(InnerChunk
.Loc
, diag::err_illegal_decl_reference_to_reference
)
6252 // Once we've complained about the reference-to-reference, we
6253 // can go ahead and build the (technically ill-formed)
6254 // declarator: reference collapsing will take care of it.
6258 // Remember that we parsed a reference type.
6259 D
.AddTypeInfo(DeclaratorChunk::getReference(DS
.getTypeQualifiers(), Loc
,
6261 std::move(DS
.getAttributes()), SourceLocation());
6265 // When correcting from misplaced brackets before the identifier, the location
6266 // is saved inside the declarator so that other diagnostic messages can use
6267 // them. This extracts and returns that location, or returns the provided
6268 // location if a stored location does not exist.
6269 static SourceLocation
getMissingDeclaratorIdLoc(Declarator
&D
,
6270 SourceLocation Loc
) {
6271 if (D
.getName().StartLocation
.isInvalid() &&
6272 D
.getName().EndLocation
.isValid())
6273 return D
.getName().EndLocation
;
6278 /// ParseDirectDeclarator
6279 /// direct-declarator: [C99 6.7.5]
6280 /// [C99] identifier
6281 /// '(' declarator ')'
6282 /// [GNU] '(' attributes declarator ')'
6283 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6284 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6285 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6286 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6287 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6288 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6289 /// attribute-specifier-seq[opt]
6290 /// direct-declarator '(' parameter-type-list ')'
6291 /// direct-declarator '(' identifier-list[opt] ')'
6292 /// [GNU] direct-declarator '(' parameter-forward-declarations
6293 /// parameter-type-list[opt] ')'
6294 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
6295 /// cv-qualifier-seq[opt] exception-specification[opt]
6296 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
6297 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
6298 /// ref-qualifier[opt] exception-specification[opt]
6299 /// [C++] declarator-id
6300 /// [C++11] declarator-id attribute-specifier-seq[opt]
6302 /// declarator-id: [C++ 8]
6303 /// '...'[opt] id-expression
6304 /// '::'[opt] nested-name-specifier[opt] type-name
6306 /// id-expression: [C++ 5.1]
6310 /// unqualified-id: [C++ 5.1]
6312 /// operator-function-id
6313 /// conversion-function-id
6317 /// C++17 adds the following, which we also handle here:
6319 /// simple-declaration:
6320 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6322 /// Note, any additional constructs added here may need corresponding changes
6323 /// in isConstructorDeclarator.
6324 void Parser::ParseDirectDeclarator(Declarator
&D
) {
6325 DeclaratorScopeObj
DeclScopeObj(*this, D
.getCXXScopeSpec());
6327 if (getLangOpts().CPlusPlus
&& D
.mayHaveIdentifier()) {
6328 // This might be a C++17 structured binding.
6329 if (Tok
.is(tok::l_square
) && !D
.mayOmitIdentifier() &&
6330 D
.getCXXScopeSpec().isEmpty())
6331 return ParseDecompositionDeclarator(D
);
6333 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6334 // this context it is a bitfield. Also in range-based for statement colon
6335 // may delimit for-range-declaration.
6336 ColonProtectionRAIIObject
X(
6337 *this, D
.getContext() == DeclaratorContext::Member
||
6338 (D
.getContext() == DeclaratorContext::ForInit
&&
6339 getLangOpts().CPlusPlus11
));
6341 // ParseDeclaratorInternal might already have parsed the scope.
6342 if (D
.getCXXScopeSpec().isEmpty()) {
6343 bool EnteringContext
= D
.getContext() == DeclaratorContext::File
||
6344 D
.getContext() == DeclaratorContext::Member
;
6345 ParseOptionalCXXScopeSpecifier(
6346 D
.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6347 /*ObjectHasErrors=*/false, EnteringContext
);
6350 if (D
.getCXXScopeSpec().isValid()) {
6351 if (Actions
.ShouldEnterDeclaratorScope(getCurScope(),
6352 D
.getCXXScopeSpec()))
6353 // Change the declaration context for name lookup, until this function
6354 // is exited (and the declarator has been parsed).
6355 DeclScopeObj
.EnterDeclaratorScope();
6356 else if (getObjCDeclContext()) {
6357 // Ensure that we don't interpret the next token as an identifier when
6358 // dealing with declarations in an Objective-C container.
6359 D
.SetIdentifier(nullptr, Tok
.getLocation());
6360 D
.setInvalidType(true);
6362 goto PastIdentifier
;
6366 // C++0x [dcl.fct]p14:
6367 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6368 // parameter-declaration-clause without a preceding comma. In this case,
6369 // the ellipsis is parsed as part of the abstract-declarator if the type
6370 // of the parameter either names a template parameter pack that has not
6371 // been expanded or contains auto; otherwise, it is parsed as part of the
6372 // parameter-declaration-clause.
6373 if (Tok
.is(tok::ellipsis
) && D
.getCXXScopeSpec().isEmpty() &&
6374 !((D
.getContext() == DeclaratorContext::Prototype
||
6375 D
.getContext() == DeclaratorContext::LambdaExprParameter
||
6376 D
.getContext() == DeclaratorContext::BlockLiteral
) &&
6377 NextToken().is(tok::r_paren
) && !D
.hasGroupingParens() &&
6378 !Actions
.containsUnexpandedParameterPacks(D
) &&
6379 D
.getDeclSpec().getTypeSpecType() != TST_auto
)) {
6380 SourceLocation EllipsisLoc
= ConsumeToken();
6381 if (isPtrOperatorToken(Tok
.getKind(), getLangOpts(), D
.getContext())) {
6382 // The ellipsis was put in the wrong place. Recover, and explain to
6383 // the user what they should have done.
6385 if (EllipsisLoc
.isValid())
6386 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc
, D
);
6389 D
.setEllipsisLoc(EllipsisLoc
);
6391 // The ellipsis can't be followed by a parenthesized declarator. We
6392 // check for that in ParseParenDeclarator, after we have disambiguated
6393 // the l_paren token.
6396 if (Tok
.isOneOf(tok::identifier
, tok::kw_operator
, tok::annot_template_id
,
6398 // We found something that indicates the start of an unqualified-id.
6399 // Parse that unqualified-id.
6400 bool AllowConstructorName
;
6401 bool AllowDeductionGuide
;
6402 if (D
.getDeclSpec().hasTypeSpecifier()) {
6403 AllowConstructorName
= false;
6404 AllowDeductionGuide
= false;
6405 } else if (D
.getCXXScopeSpec().isSet()) {
6406 AllowConstructorName
= (D
.getContext() == DeclaratorContext::File
||
6407 D
.getContext() == DeclaratorContext::Member
);
6408 AllowDeductionGuide
= false;
6410 AllowConstructorName
= (D
.getContext() == DeclaratorContext::Member
);
6411 AllowDeductionGuide
= (D
.getContext() == DeclaratorContext::File
||
6412 D
.getContext() == DeclaratorContext::Member
);
6415 bool HadScope
= D
.getCXXScopeSpec().isValid();
6416 if (ParseUnqualifiedId(D
.getCXXScopeSpec(),
6417 /*ObjectType=*/nullptr,
6418 /*ObjectHadErrors=*/false,
6419 /*EnteringContext=*/true,
6420 /*AllowDestructorName=*/true, AllowConstructorName
,
6421 AllowDeductionGuide
, nullptr, D
.getName()) ||
6422 // Once we're past the identifier, if the scope was bad, mark the
6423 // whole declarator bad.
6424 D
.getCXXScopeSpec().isInvalid()) {
6425 D
.SetIdentifier(nullptr, Tok
.getLocation());
6426 D
.setInvalidType(true);
6428 // ParseUnqualifiedId might have parsed a scope specifier during error
6429 // recovery. If it did so, enter that scope.
6430 if (!HadScope
&& D
.getCXXScopeSpec().isValid() &&
6431 Actions
.ShouldEnterDeclaratorScope(getCurScope(),
6432 D
.getCXXScopeSpec()))
6433 DeclScopeObj
.EnterDeclaratorScope();
6435 // Parsed the unqualified-id; update range information and move along.
6436 if (D
.getSourceRange().getBegin().isInvalid())
6437 D
.SetRangeBegin(D
.getName().getSourceRange().getBegin());
6438 D
.SetRangeEnd(D
.getName().getSourceRange().getEnd());
6440 goto PastIdentifier
;
6443 if (D
.getCXXScopeSpec().isNotEmpty()) {
6444 // We have a scope specifier but no following unqualified-id.
6445 Diag(PP
.getLocForEndOfToken(D
.getCXXScopeSpec().getEndLoc()),
6446 diag::err_expected_unqualified_id
)
6448 D
.SetIdentifier(nullptr, Tok
.getLocation());
6449 goto PastIdentifier
;
6451 } else if (Tok
.is(tok::identifier
) && D
.mayHaveIdentifier()) {
6452 assert(!getLangOpts().CPlusPlus
&&
6453 "There's a C++-specific check for tok::identifier above");
6454 assert(Tok
.getIdentifierInfo() && "Not an identifier?");
6455 D
.SetIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
6456 D
.SetRangeEnd(Tok
.getLocation());
6458 goto PastIdentifier
;
6459 } else if (Tok
.is(tok::identifier
) && !D
.mayHaveIdentifier()) {
6460 // We're not allowed an identifier here, but we got one. Try to figure out
6461 // if the user was trying to attach a name to the type, or whether the name
6462 // is some unrelated trailing syntax.
6463 bool DiagnoseIdentifier
= false;
6464 if (D
.hasGroupingParens())
6465 // An identifier within parens is unlikely to be intended to be anything
6466 // other than a name being "declared".
6467 DiagnoseIdentifier
= true;
6468 else if (D
.getContext() == DeclaratorContext::TemplateArg
)
6469 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6470 DiagnoseIdentifier
=
6471 NextToken().isOneOf(tok::comma
, tok::greater
, tok::greatergreater
);
6472 else if (D
.getContext() == DeclaratorContext::AliasDecl
||
6473 D
.getContext() == DeclaratorContext::AliasTemplate
)
6474 // The most likely error is that the ';' was forgotten.
6475 DiagnoseIdentifier
= NextToken().isOneOf(tok::comma
, tok::semi
);
6476 else if ((D
.getContext() == DeclaratorContext::TrailingReturn
||
6477 D
.getContext() == DeclaratorContext::TrailingReturnVar
) &&
6478 !isCXX11VirtSpecifier(Tok
))
6479 DiagnoseIdentifier
= NextToken().isOneOf(
6480 tok::comma
, tok::semi
, tok::equal
, tok::l_brace
, tok::kw_try
);
6481 if (DiagnoseIdentifier
) {
6482 Diag(Tok
.getLocation(), diag::err_unexpected_unqualified_id
)
6483 << FixItHint::CreateRemoval(Tok
.getLocation());
6484 D
.SetIdentifier(nullptr, Tok
.getLocation());
6486 goto PastIdentifier
;
6490 if (Tok
.is(tok::l_paren
)) {
6491 // If this might be an abstract-declarator followed by a direct-initializer,
6492 // check whether this is a valid declarator chunk. If it can't be, assume
6493 // that it's an initializer instead.
6494 if (D
.mayOmitIdentifier() && D
.mayBeFollowedByCXXDirectInit()) {
6495 RevertingTentativeParsingAction
PA(*this);
6496 if (TryParseDeclarator(true, D
.mayHaveIdentifier(), true) ==
6498 D
.SetIdentifier(nullptr, Tok
.getLocation());
6499 goto PastIdentifier
;
6503 // direct-declarator: '(' declarator ')'
6504 // direct-declarator: '(' attributes declarator ')'
6505 // Example: 'char (*X)' or 'int (*XX)(void)'
6506 ParseParenDeclarator(D
);
6508 // If the declarator was parenthesized, we entered the declarator
6509 // scope when parsing the parenthesized declarator, then exited
6510 // the scope already. Re-enter the scope, if we need to.
6511 if (D
.getCXXScopeSpec().isSet()) {
6512 // If there was an error parsing parenthesized declarator, declarator
6513 // scope may have been entered before. Don't do it again.
6514 if (!D
.isInvalidType() &&
6515 Actions
.ShouldEnterDeclaratorScope(getCurScope(),
6516 D
.getCXXScopeSpec()))
6517 // Change the declaration context for name lookup, until this function
6518 // is exited (and the declarator has been parsed).
6519 DeclScopeObj
.EnterDeclaratorScope();
6521 } else if (D
.mayOmitIdentifier()) {
6522 // This could be something simple like "int" (in which case the declarator
6523 // portion is empty), if an abstract-declarator is allowed.
6524 D
.SetIdentifier(nullptr, Tok
.getLocation());
6526 // The grammar for abstract-pack-declarator does not allow grouping parens.
6527 // FIXME: Revisit this once core issue 1488 is resolved.
6528 if (D
.hasEllipsis() && D
.hasGroupingParens())
6529 Diag(PP
.getLocForEndOfToken(D
.getEllipsisLoc()),
6530 diag::ext_abstract_pack_declarator_parens
);
6532 if (Tok
.getKind() == tok::annot_pragma_parser_crash
)
6534 if (Tok
.is(tok::l_square
))
6535 return ParseMisplacedBracketDeclarator(D
);
6536 if (D
.getContext() == DeclaratorContext::Member
) {
6537 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6538 // treating these keyword as valid member names.
6539 if (getLangOpts().ObjC
&& getLangOpts().CPlusPlus
&&
6540 Tok
.getIdentifierInfo() &&
6541 Tok
.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6542 Diag(getMissingDeclaratorIdLoc(D
, Tok
.getLocation()),
6543 diag::err_expected_member_name_or_semi_objcxx_keyword
)
6544 << Tok
.getIdentifierInfo()
6545 << (D
.getDeclSpec().isEmpty() ? SourceRange()
6546 : D
.getDeclSpec().getSourceRange());
6547 D
.SetIdentifier(Tok
.getIdentifierInfo(), Tok
.getLocation());
6548 D
.SetRangeEnd(Tok
.getLocation());
6550 goto PastIdentifier
;
6552 Diag(getMissingDeclaratorIdLoc(D
, Tok
.getLocation()),
6553 diag::err_expected_member_name_or_semi
)
6554 << (D
.getDeclSpec().isEmpty() ? SourceRange()
6555 : D
.getDeclSpec().getSourceRange());
6557 if (Tok
.getKind() == tok::TokenKind::kw_while
) {
6558 Diag(Tok
, diag::err_while_loop_outside_of_a_function
);
6559 } else if (getLangOpts().CPlusPlus
) {
6560 if (Tok
.isOneOf(tok::period
, tok::arrow
))
6561 Diag(Tok
, diag::err_invalid_operator_on_type
) << Tok
.is(tok::arrow
);
6563 SourceLocation Loc
= D
.getCXXScopeSpec().getEndLoc();
6564 if (Tok
.isAtStartOfLine() && Loc
.isValid())
6565 Diag(PP
.getLocForEndOfToken(Loc
), diag::err_expected_unqualified_id
)
6566 << getLangOpts().CPlusPlus
;
6568 Diag(getMissingDeclaratorIdLoc(D
, Tok
.getLocation()),
6569 diag::err_expected_unqualified_id
)
6570 << getLangOpts().CPlusPlus
;
6573 Diag(getMissingDeclaratorIdLoc(D
, Tok
.getLocation()),
6574 diag::err_expected_either
)
6575 << tok::identifier
<< tok::l_paren
;
6578 D
.SetIdentifier(nullptr, Tok
.getLocation());
6579 D
.setInvalidType(true);
6583 assert(D
.isPastIdentifier() &&
6584 "Haven't past the location of the identifier yet?");
6586 // Don't parse attributes unless we have parsed an unparenthesized name.
6587 if (D
.hasName() && !D
.getNumTypeObjects())
6588 MaybeParseCXX11Attributes(D
);
6591 if (Tok
.is(tok::l_paren
)) {
6592 bool IsFunctionDeclaration
= D
.isFunctionDeclaratorAFunctionDeclaration();
6593 // Enter function-declaration scope, limiting any declarators to the
6594 // function prototype scope, including parameter declarators.
6595 ParseScope
PrototypeScope(this,
6596 Scope::FunctionPrototypeScope
|Scope::DeclScope
|
6597 (IsFunctionDeclaration
6598 ? Scope::FunctionDeclarationScope
: 0));
6600 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6601 // In such a case, check if we actually have a function declarator; if it
6602 // is not, the declarator has been fully parsed.
6603 bool IsAmbiguous
= false;
6604 if (getLangOpts().CPlusPlus
&& D
.mayBeFollowedByCXXDirectInit()) {
6605 // C++2a [temp.res]p5
6606 // A qualified-id is assumed to name a type if
6608 // - it is a decl-specifier of the decl-specifier-seq of a
6610 // - parameter-declaration in a member-declaration [...]
6611 // - parameter-declaration in a declarator of a function or function
6612 // template declaration whose declarator-id is qualified [...]
6613 auto AllowImplicitTypename
= ImplicitTypenameContext::No
;
6614 if (D
.getCXXScopeSpec().isSet())
6615 AllowImplicitTypename
=
6616 (ImplicitTypenameContext
)Actions
.isDeclaratorFunctionLike(D
);
6617 else if (D
.getContext() == DeclaratorContext::Member
) {
6618 AllowImplicitTypename
= ImplicitTypenameContext::Yes
;
6621 // The name of the declarator, if any, is tentatively declared within
6622 // a possible direct initializer.
6623 TentativelyDeclaredIdentifiers
.push_back(D
.getIdentifier());
6624 bool IsFunctionDecl
=
6625 isCXXFunctionDeclarator(&IsAmbiguous
, AllowImplicitTypename
);
6626 TentativelyDeclaredIdentifiers
.pop_back();
6627 if (!IsFunctionDecl
)
6630 ParsedAttributes
attrs(AttrFactory
);
6631 BalancedDelimiterTracker
T(*this, tok::l_paren
);
6633 if (IsFunctionDeclaration
)
6634 Actions
.ActOnStartFunctionDeclarationDeclarator(D
,
6635 TemplateParameterDepth
);
6636 ParseFunctionDeclarator(D
, attrs
, T
, IsAmbiguous
);
6637 if (IsFunctionDeclaration
)
6638 Actions
.ActOnFinishFunctionDeclarationDeclarator(D
);
6639 PrototypeScope
.Exit();
6640 } else if (Tok
.is(tok::l_square
)) {
6641 ParseBracketDeclarator(D
);
6642 } else if (Tok
.is(tok::kw_requires
) && D
.hasGroupingParens()) {
6643 // This declarator is declaring a function, but the requires clause is
6644 // in the wrong place:
6645 // void (f() requires true);
6647 // void f() requires true;
6649 // void (f()) requires true;
6650 Diag(Tok
, diag::err_requires_clause_inside_parens
);
6652 ExprResult TrailingRequiresClause
= Actions
.CorrectDelayedTyposInExpr(
6653 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6654 if (TrailingRequiresClause
.isUsable() && D
.isFunctionDeclarator() &&
6655 !D
.hasTrailingRequiresClause())
6656 // We're already ill-formed if we got here but we'll accept it anyway.
6657 D
.setTrailingRequiresClause(TrailingRequiresClause
.get());
6664 void Parser::ParseDecompositionDeclarator(Declarator
&D
) {
6665 assert(Tok
.is(tok::l_square
));
6667 // If this doesn't look like a structured binding, maybe it's a misplaced
6668 // array declarator.
6669 // FIXME: Consume the l_square first so we don't need extra lookahead for
6671 if (!(NextToken().is(tok::identifier
) &&
6672 GetLookAheadToken(2).isOneOf(tok::comma
, tok::r_square
)) &&
6673 !(NextToken().is(tok::r_square
) &&
6674 GetLookAheadToken(2).isOneOf(tok::equal
, tok::l_brace
)))
6675 return ParseMisplacedBracketDeclarator(D
);
6677 BalancedDelimiterTracker
T(*this, tok::l_square
);
6680 SmallVector
<DecompositionDeclarator::Binding
, 32> Bindings
;
6681 while (Tok
.isNot(tok::r_square
)) {
6682 if (!Bindings
.empty()) {
6683 if (Tok
.is(tok::comma
))
6686 if (Tok
.is(tok::identifier
)) {
6687 SourceLocation EndLoc
= getEndOfPreviousToken();
6688 Diag(EndLoc
, diag::err_expected
)
6689 << tok::comma
<< FixItHint::CreateInsertion(EndLoc
, ",");
6691 Diag(Tok
, diag::err_expected_comma_or_rsquare
);
6694 SkipUntil(tok::r_square
, tok::comma
, tok::identifier
,
6695 StopAtSemi
| StopBeforeMatch
);
6696 if (Tok
.is(tok::comma
))
6698 else if (Tok
.isNot(tok::identifier
))
6703 if (Tok
.isNot(tok::identifier
)) {
6704 Diag(Tok
, diag::err_expected
) << tok::identifier
;
6708 Bindings
.push_back({Tok
.getIdentifierInfo(), Tok
.getLocation()});
6712 if (Tok
.isNot(tok::r_square
))
6713 // We've already diagnosed a problem here.
6716 // C++17 does not allow the identifier-list in a structured binding
6718 if (Bindings
.empty())
6719 Diag(Tok
.getLocation(), diag::ext_decomp_decl_empty
);
6724 return D
.setDecompositionBindings(T
.getOpenLocation(), Bindings
,
6725 T
.getCloseLocation());
6728 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6729 /// only called before the identifier, so these are most likely just grouping
6730 /// parens for precedence. If we find that these are actually function
6731 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6733 /// direct-declarator:
6734 /// '(' declarator ')'
6735 /// [GNU] '(' attributes declarator ')'
6736 /// direct-declarator '(' parameter-type-list ')'
6737 /// direct-declarator '(' identifier-list[opt] ')'
6738 /// [GNU] direct-declarator '(' parameter-forward-declarations
6739 /// parameter-type-list[opt] ')'
6741 void Parser::ParseParenDeclarator(Declarator
&D
) {
6742 BalancedDelimiterTracker
T(*this, tok::l_paren
);
6745 assert(!D
.isPastIdentifier() && "Should be called before passing identifier");
6747 // Eat any attributes before we look at whether this is a grouping or function
6748 // declarator paren. If this is a grouping paren, the attribute applies to
6749 // the type being built up, for example:
6750 // int (__attribute__(()) *x)(long y)
6751 // If this ends up not being a grouping paren, the attribute applies to the
6752 // first argument, for example:
6753 // int (__attribute__(()) int x)
6754 // In either case, we need to eat any attributes to be able to determine what
6755 // sort of paren this is.
6757 ParsedAttributes
attrs(AttrFactory
);
6758 bool RequiresArg
= false;
6759 if (Tok
.is(tok::kw___attribute
)) {
6760 ParseGNUAttributes(attrs
);
6762 // We require that the argument list (if this is a non-grouping paren) be
6763 // present even if the attribute list was empty.
6767 // Eat any Microsoft extensions.
6768 ParseMicrosoftTypeAttributes(attrs
);
6770 // Eat any Borland extensions.
6771 if (Tok
.is(tok::kw___pascal
))
6772 ParseBorlandTypeAttributes(attrs
);
6774 // If we haven't past the identifier yet (or where the identifier would be
6775 // stored, if this is an abstract declarator), then this is probably just
6776 // grouping parens. However, if this could be an abstract-declarator, then
6777 // this could also be the start of function arguments (consider 'void()').
6780 if (!D
.mayOmitIdentifier()) {
6781 // If this can't be an abstract-declarator, this *must* be a grouping
6782 // paren, because we haven't seen the identifier yet.
6784 } else if (Tok
.is(tok::r_paren
) || // 'int()' is a function.
6785 (getLangOpts().CPlusPlus
&& Tok
.is(tok::ellipsis
) &&
6786 NextToken().is(tok::r_paren
)) || // C++ int(...)
6787 isDeclarationSpecifier(
6788 ImplicitTypenameContext::No
) || // 'int(int)' is a function.
6789 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6790 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6791 // considered to be a type, not a K&R identifier-list.
6794 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6798 // If this is a grouping paren, handle:
6799 // direct-declarator: '(' declarator ')'
6800 // direct-declarator: '(' attributes declarator ')'
6802 SourceLocation EllipsisLoc
= D
.getEllipsisLoc();
6803 D
.setEllipsisLoc(SourceLocation());
6805 bool hadGroupingParens
= D
.hasGroupingParens();
6806 D
.setGroupingParens(true);
6807 ParseDeclaratorInternal(D
, &Parser::ParseDirectDeclarator
);
6811 DeclaratorChunk::getParen(T
.getOpenLocation(), T
.getCloseLocation()),
6812 std::move(attrs
), T
.getCloseLocation());
6814 D
.setGroupingParens(hadGroupingParens
);
6816 // An ellipsis cannot be placed outside parentheses.
6817 if (EllipsisLoc
.isValid())
6818 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc
, D
);
6823 // Okay, if this wasn't a grouping paren, it must be the start of a function
6824 // argument list. Recognize that this declarator will never have an
6825 // identifier (and remember where it would have been), then call into
6826 // ParseFunctionDeclarator to handle of argument list.
6827 D
.SetIdentifier(nullptr, Tok
.getLocation());
6829 // Enter function-declaration scope, limiting any declarators to the
6830 // function prototype scope, including parameter declarators.
6831 ParseScope
PrototypeScope(this,
6832 Scope::FunctionPrototypeScope
| Scope::DeclScope
|
6833 (D
.isFunctionDeclaratorAFunctionDeclaration()
6834 ? Scope::FunctionDeclarationScope
: 0));
6835 ParseFunctionDeclarator(D
, attrs
, T
, false, RequiresArg
);
6836 PrototypeScope
.Exit();
6839 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6840 const Declarator
&D
, const DeclSpec
&DS
,
6841 std::optional
<Sema::CXXThisScopeRAII
> &ThisScope
) {
6842 // C++11 [expr.prim.general]p3:
6843 // If a declaration declares a member function or member function
6844 // template of a class X, the expression this is a prvalue of type
6845 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6846 // and the end of the function-definition, member-declarator, or
6848 // FIXME: currently, "static" case isn't handled correctly.
6849 bool IsCXX11MemberFunction
=
6850 getLangOpts().CPlusPlus11
&&
6851 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
6852 (D
.getContext() == DeclaratorContext::Member
6853 ? !D
.getDeclSpec().isFriendSpecified()
6854 : D
.getContext() == DeclaratorContext::File
&&
6855 D
.getCXXScopeSpec().isValid() &&
6856 Actions
.CurContext
->isRecord());
6857 if (!IsCXX11MemberFunction
)
6860 Qualifiers Q
= Qualifiers::fromCVRUMask(DS
.getTypeQualifiers());
6861 if (D
.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14
)
6863 // FIXME: Collect C++ address spaces.
6864 // If there are multiple different address spaces, the source is invalid.
6865 // Carry on using the first addr space for the qualifiers of 'this'.
6866 // The diagnostic will be given later while creating the function
6867 // prototype for the method.
6868 if (getLangOpts().OpenCLCPlusPlus
) {
6869 for (ParsedAttr
&attr
: DS
.getAttributes()) {
6870 LangAS ASIdx
= attr
.asOpenCLLangAS();
6871 if (ASIdx
!= LangAS::Default
) {
6872 Q
.addAddressSpace(ASIdx
);
6877 ThisScope
.emplace(Actions
, dyn_cast
<CXXRecordDecl
>(Actions
.CurContext
), Q
,
6878 IsCXX11MemberFunction
);
6881 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6882 /// declarator D up to a paren, which indicates that we are parsing function
6885 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
6886 /// immediately after the open paren - they will be applied to the DeclSpec
6887 /// of the first parameter.
6889 /// If RequiresArg is true, then the first argument of the function is required
6890 /// to be present and required to not be an identifier list.
6892 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6893 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6894 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6895 /// (C++2a) the trailing requires-clause.
6897 /// [C++11] exception-specification:
6898 /// dynamic-exception-specification
6899 /// noexcept-specification
6901 void Parser::ParseFunctionDeclarator(Declarator
&D
,
6902 ParsedAttributes
&FirstArgAttrs
,
6903 BalancedDelimiterTracker
&Tracker
,
6906 assert(getCurScope()->isFunctionPrototypeScope() &&
6907 "Should call from a Function scope");
6908 // lparen is already consumed!
6909 assert(D
.isPastIdentifier() && "Should not call before identifier!");
6911 // This should be true when the function has typed arguments.
6912 // Otherwise, it is treated as a K&R-style function.
6913 bool HasProto
= false;
6914 // Build up an array of information about the parsed arguments.
6915 SmallVector
<DeclaratorChunk::ParamInfo
, 16> ParamInfo
;
6916 // Remember where we see an ellipsis, if any.
6917 SourceLocation EllipsisLoc
;
6919 DeclSpec
DS(AttrFactory
);
6920 bool RefQualifierIsLValueRef
= true;
6921 SourceLocation RefQualifierLoc
;
6922 ExceptionSpecificationType ESpecType
= EST_None
;
6923 SourceRange ESpecRange
;
6924 SmallVector
<ParsedType
, 2> DynamicExceptions
;
6925 SmallVector
<SourceRange
, 2> DynamicExceptionRanges
;
6926 ExprResult NoexceptExpr
;
6927 CachedTokens
*ExceptionSpecTokens
= nullptr;
6928 ParsedAttributes
FnAttrs(AttrFactory
);
6929 TypeResult TrailingReturnType
;
6930 SourceLocation TrailingReturnTypeLoc
;
6932 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6933 EndLoc is the end location for the function declarator.
6934 They differ for trailing return types. */
6935 SourceLocation StartLoc
, LocalEndLoc
, EndLoc
;
6936 SourceLocation LParenLoc
, RParenLoc
;
6937 LParenLoc
= Tracker
.getOpenLocation();
6938 StartLoc
= LParenLoc
;
6940 if (isFunctionDeclaratorIdentifierList()) {
6942 Diag(Tok
, diag::err_argument_required_after_attribute
);
6944 ParseFunctionDeclaratorIdentifierList(D
, ParamInfo
);
6946 Tracker
.consumeClose();
6947 RParenLoc
= Tracker
.getCloseLocation();
6948 LocalEndLoc
= RParenLoc
;
6951 // If there are attributes following the identifier list, parse them and
6953 MaybeParseCXX11Attributes(FnAttrs
);
6954 ProhibitAttributes(FnAttrs
);
6956 if (Tok
.isNot(tok::r_paren
))
6957 ParseParameterDeclarationClause(D
, FirstArgAttrs
, ParamInfo
, EllipsisLoc
);
6958 else if (RequiresArg
)
6959 Diag(Tok
, diag::err_argument_required_after_attribute
);
6961 // OpenCL disallows functions without a prototype, but it doesn't enforce
6962 // strict prototypes as in C2x because it allows a function definition to
6963 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
6964 HasProto
= ParamInfo
.size() || getLangOpts().requiresStrictPrototypes() ||
6965 getLangOpts().OpenCL
;
6967 // If we have the closing ')', eat it.
6968 Tracker
.consumeClose();
6969 RParenLoc
= Tracker
.getCloseLocation();
6970 LocalEndLoc
= RParenLoc
;
6973 if (getLangOpts().CPlusPlus
) {
6974 // FIXME: Accept these components in any order, and produce fixits to
6975 // correct the order if the user gets it wrong. Ideally we should deal
6976 // with the pure-specifier in the same way.
6978 // Parse cv-qualifier-seq[opt].
6979 ParseTypeQualifierListOpt(DS
, AR_NoAttributesParsed
,
6980 /*AtomicAllowed*/ false,
6981 /*IdentifierRequired=*/false,
6982 llvm::function_ref
<void()>([&]() {
6983 Actions
.CodeCompleteFunctionQualifiers(DS
, D
);
6985 if (!DS
.getSourceRange().getEnd().isInvalid()) {
6986 EndLoc
= DS
.getSourceRange().getEnd();
6989 // Parse ref-qualifier[opt].
6990 if (ParseRefQualifier(RefQualifierIsLValueRef
, RefQualifierLoc
))
6991 EndLoc
= RefQualifierLoc
;
6993 std::optional
<Sema::CXXThisScopeRAII
> ThisScope
;
6994 InitCXXThisScopeForDeclaratorIfRelevant(D
, DS
, ThisScope
);
6996 // Parse exception-specification[opt].
6997 // FIXME: Per [class.mem]p6, all exception-specifications at class scope
6998 // should be delayed, including those for non-members (eg, friend
6999 // declarations). But only applying this to member declarations is
7000 // consistent with what other implementations do.
7001 bool Delayed
= D
.isFirstDeclarationOfMember() &&
7002 D
.isFunctionDeclaratorAFunctionDeclaration();
7003 if (Delayed
&& Actions
.isLibstdcxxEagerExceptionSpecHack(D
) &&
7004 GetLookAheadToken(0).is(tok::kw_noexcept
) &&
7005 GetLookAheadToken(1).is(tok::l_paren
) &&
7006 GetLookAheadToken(2).is(tok::kw_noexcept
) &&
7007 GetLookAheadToken(3).is(tok::l_paren
) &&
7008 GetLookAheadToken(4).is(tok::identifier
) &&
7009 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7010 // HACK: We've got an exception-specification
7011 // noexcept(noexcept(swap(...)))
7013 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7014 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7015 // for 'swap' will only find the function we're currently declaring,
7016 // whereas it expects to find a non-member swap through ADL. Turn off
7017 // delayed parsing to give it a chance to find what it expects.
7020 ESpecType
= tryParseExceptionSpecification(Delayed
,
7023 DynamicExceptionRanges
,
7025 ExceptionSpecTokens
);
7026 if (ESpecType
!= EST_None
)
7027 EndLoc
= ESpecRange
.getEnd();
7029 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7030 // after the exception-specification.
7031 MaybeParseCXX11Attributes(FnAttrs
);
7033 // Parse trailing-return-type[opt].
7034 LocalEndLoc
= EndLoc
;
7035 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::arrow
)) {
7036 Diag(Tok
, diag::warn_cxx98_compat_trailing_return_type
);
7037 if (D
.getDeclSpec().getTypeSpecType() == TST_auto
)
7038 StartLoc
= D
.getDeclSpec().getTypeSpecTypeLoc();
7039 LocalEndLoc
= Tok
.getLocation();
7041 TrailingReturnType
=
7042 ParseTrailingReturnType(Range
, D
.mayBeFollowedByCXXDirectInit());
7043 TrailingReturnTypeLoc
= Range
.getBegin();
7044 EndLoc
= Range
.getEnd();
7046 } else if (standardAttributesAllowed()) {
7047 MaybeParseCXX11Attributes(FnAttrs
);
7051 // Collect non-parameter declarations from the prototype if this is a function
7052 // declaration. They will be moved into the scope of the function. Only do
7053 // this in C and not C++, where the decls will continue to live in the
7054 // surrounding context.
7055 SmallVector
<NamedDecl
*, 0> DeclsInPrototype
;
7056 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus
) {
7057 for (Decl
*D
: getCurScope()->decls()) {
7058 NamedDecl
*ND
= dyn_cast
<NamedDecl
>(D
);
7059 if (!ND
|| isa
<ParmVarDecl
>(ND
))
7061 DeclsInPrototype
.push_back(ND
);
7063 // Sort DeclsInPrototype based on raw encoding of the source location.
7064 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7065 // moving to DeclContext. This provides a stable ordering for traversing
7066 // Decls in DeclContext, which is important for tasks like ASTWriter for
7067 // deterministic output.
7068 llvm::sort(DeclsInPrototype
, [](Decl
*D1
, Decl
*D2
) {
7069 return D1
->getLocation().getRawEncoding() <
7070 D2
->getLocation().getRawEncoding();
7074 // Remember that we parsed a function type, and remember the attributes.
7075 D
.AddTypeInfo(DeclaratorChunk::getFunction(
7076 HasProto
, IsAmbiguous
, LParenLoc
, ParamInfo
.data(),
7077 ParamInfo
.size(), EllipsisLoc
, RParenLoc
,
7078 RefQualifierIsLValueRef
, RefQualifierLoc
,
7079 /*MutableLoc=*/SourceLocation(),
7080 ESpecType
, ESpecRange
, DynamicExceptions
.data(),
7081 DynamicExceptionRanges
.data(), DynamicExceptions
.size(),
7082 NoexceptExpr
.isUsable() ? NoexceptExpr
.get() : nullptr,
7083 ExceptionSpecTokens
, DeclsInPrototype
, StartLoc
,
7084 LocalEndLoc
, D
, TrailingReturnType
, TrailingReturnTypeLoc
,
7086 std::move(FnAttrs
), EndLoc
);
7089 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
7090 /// true if a ref-qualifier is found.
7091 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef
,
7092 SourceLocation
&RefQualifierLoc
) {
7093 if (Tok
.isOneOf(tok::amp
, tok::ampamp
)) {
7094 Diag(Tok
, getLangOpts().CPlusPlus11
?
7095 diag::warn_cxx98_compat_ref_qualifier
:
7096 diag::ext_ref_qualifier
);
7098 RefQualifierIsLValueRef
= Tok
.is(tok::amp
);
7099 RefQualifierLoc
= ConsumeToken();
7105 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
7106 /// identifier list form for a K&R-style function: void foo(a,b,c)
7108 /// Note that identifier-lists are only allowed for normal declarators, not for
7109 /// abstract-declarators.
7110 bool Parser::isFunctionDeclaratorIdentifierList() {
7111 return !getLangOpts().requiresStrictPrototypes()
7112 && Tok
.is(tok::identifier
)
7113 && !TryAltiVecVectorToken()
7114 // K&R identifier lists can't have typedefs as identifiers, per C99
7116 && (TryAnnotateTypeOrScopeToken() || !Tok
.is(tok::annot_typename
))
7117 // Identifier lists follow a really simple grammar: the identifiers can
7118 // be followed *only* by a ", identifier" or ")". However, K&R
7119 // identifier lists are really rare in the brave new modern world, and
7120 // it is very common for someone to typo a type in a non-K&R style
7121 // list. If we are presented with something like: "void foo(intptr x,
7122 // float y)", we don't want to start parsing the function declarator as
7123 // though it is a K&R style declarator just because intptr is an
7126 // To handle this, we check to see if the token after the first
7127 // identifier is a "," or ")". Only then do we parse it as an
7129 && (!Tok
.is(tok::eof
) &&
7130 (NextToken().is(tok::comma
) || NextToken().is(tok::r_paren
)));
7133 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
7134 /// we found a K&R-style identifier list instead of a typed parameter list.
7136 /// After returning, ParamInfo will hold the parsed parameters.
7138 /// identifier-list: [C99 6.7.5]
7140 /// identifier-list ',' identifier
7142 void Parser::ParseFunctionDeclaratorIdentifierList(
7144 SmallVectorImpl
<DeclaratorChunk::ParamInfo
> &ParamInfo
) {
7145 // We should never reach this point in C2x or C++.
7146 assert(!getLangOpts().requiresStrictPrototypes() &&
7147 "Cannot parse an identifier list in C2x or C++");
7149 // If there was no identifier specified for the declarator, either we are in
7150 // an abstract-declarator, or we are in a parameter declarator which was found
7151 // to be abstract. In abstract-declarators, identifier lists are not valid:
7153 if (!D
.getIdentifier())
7154 Diag(Tok
, diag::ext_ident_list_in_param
);
7156 // Maintain an efficient lookup of params we have seen so far.
7157 llvm::SmallSet
<const IdentifierInfo
*, 16> ParamsSoFar
;
7160 // If this isn't an identifier, report the error and skip until ')'.
7161 if (Tok
.isNot(tok::identifier
)) {
7162 Diag(Tok
, diag::err_expected
) << tok::identifier
;
7163 SkipUntil(tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
7164 // Forget we parsed anything.
7169 IdentifierInfo
*ParmII
= Tok
.getIdentifierInfo();
7171 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7172 if (Actions
.getTypeName(*ParmII
, Tok
.getLocation(), getCurScope()))
7173 Diag(Tok
, diag::err_unexpected_typedef_ident
) << ParmII
;
7175 // Verify that the argument identifier has not already been mentioned.
7176 if (!ParamsSoFar
.insert(ParmII
).second
) {
7177 Diag(Tok
, diag::err_param_redefinition
) << ParmII
;
7179 // Remember this identifier in ParamInfo.
7180 ParamInfo
.push_back(DeclaratorChunk::ParamInfo(ParmII
,
7185 // Eat the identifier.
7187 // The list continues if we see a comma.
7188 } while (TryConsumeToken(tok::comma
));
7191 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
7192 /// after the opening parenthesis. This function will not parse a K&R-style
7193 /// identifier list.
7195 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
7196 /// is non-null, then the caller parsed those attributes immediately after the
7197 /// open paren - they will be applied to the DeclSpec of the first parameter.
7199 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
7200 /// be the location of the ellipsis, if any was parsed.
7202 /// parameter-type-list: [C99 6.7.5]
7204 /// parameter-list ',' '...'
7205 /// [C++] parameter-list '...'
7207 /// parameter-list: [C99 6.7.5]
7208 /// parameter-declaration
7209 /// parameter-list ',' parameter-declaration
7211 /// parameter-declaration: [C99 6.7.5]
7212 /// declaration-specifiers declarator
7213 /// [C++] declaration-specifiers declarator '=' assignment-expression
7214 /// [C++11] initializer-clause
7215 /// [GNU] declaration-specifiers declarator attributes
7216 /// declaration-specifiers abstract-declarator[opt]
7217 /// [C++] declaration-specifiers abstract-declarator[opt]
7218 /// '=' assignment-expression
7219 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
7220 /// [C++11] attribute-specifier-seq parameter-declaration
7222 void Parser::ParseParameterDeclarationClause(
7223 DeclaratorContext DeclaratorCtx
, ParsedAttributes
&FirstArgAttrs
,
7224 SmallVectorImpl
<DeclaratorChunk::ParamInfo
> &ParamInfo
,
7225 SourceLocation
&EllipsisLoc
, bool IsACXXFunctionDeclaration
) {
7227 // Avoid exceeding the maximum function scope depth.
7228 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7229 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7230 // getFunctionPrototypeDepth() - 1.
7231 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7232 ParmVarDecl::getMaxFunctionScopeDepth()) {
7233 Diag(Tok
.getLocation(), diag::err_function_scope_depth_exceeded
)
7234 << ParmVarDecl::getMaxFunctionScopeDepth();
7239 // C++2a [temp.res]p5
7240 // A qualified-id is assumed to name a type if
7242 // - it is a decl-specifier of the decl-specifier-seq of a
7244 // - parameter-declaration in a member-declaration [...]
7245 // - parameter-declaration in a declarator of a function or function
7246 // template declaration whose declarator-id is qualified [...]
7247 // - parameter-declaration in a lambda-declarator [...]
7248 auto AllowImplicitTypename
= ImplicitTypenameContext::No
;
7249 if (DeclaratorCtx
== DeclaratorContext::Member
||
7250 DeclaratorCtx
== DeclaratorContext::LambdaExpr
||
7251 DeclaratorCtx
== DeclaratorContext::RequiresExpr
||
7252 IsACXXFunctionDeclaration
) {
7253 AllowImplicitTypename
= ImplicitTypenameContext::Yes
;
7257 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7258 // before deciding this was a parameter-declaration-clause.
7259 if (TryConsumeToken(tok::ellipsis
, EllipsisLoc
))
7262 // Parse the declaration-specifiers.
7263 // Just use the ParsingDeclaration "scope" of the declarator.
7264 DeclSpec
DS(AttrFactory
);
7266 ParsedAttributes
ArgDeclAttrs(AttrFactory
);
7267 ParsedAttributes
ArgDeclSpecAttrs(AttrFactory
);
7269 if (FirstArgAttrs
.Range
.isValid()) {
7270 // If the caller parsed attributes for the first argument, add them now.
7271 // Take them so that we only apply the attributes to the first parameter.
7272 // We have already started parsing the decl-specifier sequence, so don't
7273 // parse any parameter-declaration pieces that precede it.
7274 ArgDeclSpecAttrs
.takeAllFrom(FirstArgAttrs
);
7276 // Parse any C++11 attributes.
7277 MaybeParseCXX11Attributes(ArgDeclAttrs
);
7279 // Skip any Microsoft attributes before a param.
7280 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs
);
7283 SourceLocation DSStart
= Tok
.getLocation();
7285 ParseDeclarationSpecifiers(DS
, /*TemplateInfo=*/ParsedTemplateInfo(),
7286 AS_none
, DeclSpecContext::DSC_normal
,
7287 /*LateAttrs=*/nullptr, AllowImplicitTypename
);
7288 DS
.takeAttributesFrom(ArgDeclSpecAttrs
);
7290 // Parse the declarator. This is "PrototypeContext" or
7291 // "LambdaExprParameterContext", because we must accept either
7292 // 'declarator' or 'abstract-declarator' here.
7293 Declarator
ParmDeclarator(DS
, ArgDeclAttrs
,
7294 DeclaratorCtx
== DeclaratorContext::RequiresExpr
7295 ? DeclaratorContext::RequiresExpr
7296 : DeclaratorCtx
== DeclaratorContext::LambdaExpr
7297 ? DeclaratorContext::LambdaExprParameter
7298 : DeclaratorContext::Prototype
);
7299 ParseDeclarator(ParmDeclarator
);
7301 // Parse GNU attributes, if present.
7302 MaybeParseGNUAttributes(ParmDeclarator
);
7303 if (getLangOpts().HLSL
)
7304 MaybeParseHLSLSemantics(DS
.getAttributes());
7306 if (Tok
.is(tok::kw_requires
)) {
7307 // User tried to define a requires clause in a parameter declaration,
7308 // which is surely not a function declaration.
7309 // void f(int (*g)(int, int) requires true);
7311 diag::err_requires_clause_on_declarator_not_declaring_a_function
);
7313 Actions
.CorrectDelayedTyposInExpr(
7314 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7317 // Remember this parsed parameter in ParamInfo.
7318 IdentifierInfo
*ParmII
= ParmDeclarator
.getIdentifier();
7320 // DefArgToks is used when the parsing of default arguments needs
7322 std::unique_ptr
<CachedTokens
> DefArgToks
;
7324 // If no parameter was specified, verify that *something* was specified,
7325 // otherwise we have a missing type and identifier.
7326 if (DS
.isEmpty() && ParmDeclarator
.getIdentifier() == nullptr &&
7327 ParmDeclarator
.getNumTypeObjects() == 0) {
7328 // Completely missing, emit error.
7329 Diag(DSStart
, diag::err_missing_param
);
7331 // Otherwise, we have something. Add it and let semantic analysis try
7332 // to grok it and add the result to the ParamInfo we are building.
7334 // Last chance to recover from a misplaced ellipsis in an attempted
7335 // parameter pack declaration.
7336 if (Tok
.is(tok::ellipsis
) &&
7337 (NextToken().isNot(tok::r_paren
) ||
7338 (!ParmDeclarator
.getEllipsisLoc().isValid() &&
7339 !Actions
.isUnexpandedParameterPackPermitted())) &&
7340 Actions
.containsUnexpandedParameterPacks(ParmDeclarator
))
7341 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator
);
7343 // Now we are at the point where declarator parsing is finished.
7345 // Try to catch keywords in place of the identifier in a declarator, and
7346 // in particular the common case where:
7347 // 1 identifier comes at the end of the declarator
7348 // 2 if the identifier is dropped, the declarator is valid but anonymous
7350 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7351 // which is never valid in a param list (e.g. missing a ',')
7352 // And we can't handle this in ParseDeclarator because in general keywords
7353 // may be allowed to follow the declarator. (And in some cases there'd be
7354 // better recovery like inserting punctuation). ParseDeclarator is just
7355 // treating this as an anonymous parameter, and fortunately at this point
7356 // we've already almost done that.
7358 // We care about case 1) where the declarator type should be known, and
7359 // the identifier should be null.
7360 if (!ParmDeclarator
.isInvalidType() && !ParmDeclarator
.hasName() &&
7361 Tok
.isNot(tok::raw_identifier
) && !Tok
.isAnnotation() &&
7362 Tok
.getIdentifierInfo() &&
7363 Tok
.getIdentifierInfo()->isKeyword(getLangOpts())) {
7364 Diag(Tok
, diag::err_keyword_as_parameter
) << PP
.getSpelling(Tok
);
7365 // Consume the keyword.
7368 // Inform the actions module about the parameter declarator, so it gets
7369 // added to the current scope.
7370 Decl
*Param
= Actions
.ActOnParamDeclarator(getCurScope(), ParmDeclarator
);
7371 // Parse the default argument, if any. We parse the default
7372 // arguments in all dialects; the semantic analysis in
7373 // ActOnParamDefaultArgument will reject the default argument in
7375 if (Tok
.is(tok::equal
)) {
7376 SourceLocation EqualLoc
= Tok
.getLocation();
7378 // Parse the default argument
7379 if (DeclaratorCtx
== DeclaratorContext::Member
) {
7380 // If we're inside a class definition, cache the tokens
7381 // corresponding to the default argument. We'll actually parse
7382 // them when we see the end of the class definition.
7383 DefArgToks
.reset(new CachedTokens
);
7385 SourceLocation ArgStartLoc
= NextToken().getLocation();
7386 ConsumeAndStoreInitializer(*DefArgToks
, CIK_DefaultArgument
);
7387 Actions
.ActOnParamUnparsedDefaultArgument(Param
, EqualLoc
,
7393 // The argument isn't actually potentially evaluated unless it is
7395 EnterExpressionEvaluationContext
Eval(
7397 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
,
7400 ExprResult DefArgResult
;
7401 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
7402 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
7403 DefArgResult
= ParseBraceInitializer();
7405 if (Tok
.is(tok::l_paren
) && NextToken().is(tok::l_brace
)) {
7406 Diag(Tok
, diag::err_stmt_expr_in_default_arg
) << 0;
7407 Actions
.ActOnParamDefaultArgumentError(Param
, EqualLoc
);
7408 // Skip the statement expression and continue parsing
7409 SkipUntil(tok::comma
, StopBeforeMatch
);
7412 DefArgResult
= ParseAssignmentExpression();
7414 DefArgResult
= Actions
.CorrectDelayedTyposInExpr(DefArgResult
);
7415 if (DefArgResult
.isInvalid()) {
7416 Actions
.ActOnParamDefaultArgumentError(Param
, EqualLoc
);
7417 SkipUntil(tok::comma
, tok::r_paren
, StopAtSemi
| StopBeforeMatch
);
7419 // Inform the actions module about the default argument
7420 Actions
.ActOnParamDefaultArgument(Param
, EqualLoc
,
7421 DefArgResult
.get());
7426 ParamInfo
.push_back(DeclaratorChunk::ParamInfo(ParmII
,
7427 ParmDeclarator
.getIdentifierLoc(),
7428 Param
, std::move(DefArgToks
)));
7431 if (TryConsumeToken(tok::ellipsis
, EllipsisLoc
)) {
7432 if (!getLangOpts().CPlusPlus
) {
7433 // We have ellipsis without a preceding ',', which is ill-formed
7434 // in C. Complain and provide the fix.
7435 Diag(EllipsisLoc
, diag::err_missing_comma_before_ellipsis
)
7436 << FixItHint::CreateInsertion(EllipsisLoc
, ", ");
7437 } else if (ParmDeclarator
.getEllipsisLoc().isValid() ||
7438 Actions
.containsUnexpandedParameterPacks(ParmDeclarator
)) {
7439 // It looks like this was supposed to be a parameter pack. Warn and
7440 // point out where the ellipsis should have gone.
7441 SourceLocation ParmEllipsis
= ParmDeclarator
.getEllipsisLoc();
7442 Diag(EllipsisLoc
, diag::warn_misplaced_ellipsis_vararg
)
7443 << ParmEllipsis
.isValid() << ParmEllipsis
;
7444 if (ParmEllipsis
.isValid()) {
7446 diag::note_misplaced_ellipsis_vararg_existing_ellipsis
);
7448 Diag(ParmDeclarator
.getIdentifierLoc(),
7449 diag::note_misplaced_ellipsis_vararg_add_ellipsis
)
7450 << FixItHint::CreateInsertion(ParmDeclarator
.getIdentifierLoc(),
7452 << !ParmDeclarator
.hasName();
7454 Diag(EllipsisLoc
, diag::note_misplaced_ellipsis_vararg_add_comma
)
7455 << FixItHint::CreateInsertion(EllipsisLoc
, ", ");
7458 // We can't have any more parameters after an ellipsis.
7462 // If the next token is a comma, consume it and keep reading arguments.
7463 } while (TryConsumeToken(tok::comma
));
7466 /// [C90] direct-declarator '[' constant-expression[opt] ']'
7467 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
7468 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
7469 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
7470 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
7471 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
7472 /// attribute-specifier-seq[opt]
7473 void Parser::ParseBracketDeclarator(Declarator
&D
) {
7474 if (CheckProhibitedCXX11Attribute())
7477 BalancedDelimiterTracker
T(*this, tok::l_square
);
7480 // C array syntax has many features, but by-far the most common is [] and [4].
7481 // This code does a fast path to handle some of the most obvious cases.
7482 if (Tok
.getKind() == tok::r_square
) {
7484 ParsedAttributes
attrs(AttrFactory
);
7485 MaybeParseCXX11Attributes(attrs
);
7487 // Remember that we parsed the empty array type.
7488 D
.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7489 T
.getOpenLocation(),
7490 T
.getCloseLocation()),
7491 std::move(attrs
), T
.getCloseLocation());
7493 } else if (Tok
.getKind() == tok::numeric_constant
&&
7494 GetLookAheadToken(1).is(tok::r_square
)) {
7495 // [4] is very common. Parse the numeric constant expression.
7496 ExprResult
ExprRes(Actions
.ActOnNumericConstant(Tok
, getCurScope()));
7500 ParsedAttributes
attrs(AttrFactory
);
7501 MaybeParseCXX11Attributes(attrs
);
7503 // Remember that we parsed a array type, and remember its features.
7504 D
.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes
.get(),
7505 T
.getOpenLocation(),
7506 T
.getCloseLocation()),
7507 std::move(attrs
), T
.getCloseLocation());
7509 } else if (Tok
.getKind() == tok::code_completion
) {
7511 Actions
.CodeCompleteBracketDeclarator(getCurScope());
7515 // If valid, this location is the position where we read the 'static' keyword.
7516 SourceLocation StaticLoc
;
7517 TryConsumeToken(tok::kw_static
, StaticLoc
);
7519 // If there is a type-qualifier-list, read it now.
7520 // Type qualifiers in an array subscript are a C99 feature.
7521 DeclSpec
DS(AttrFactory
);
7522 ParseTypeQualifierListOpt(DS
, AR_CXX11AttributesParsed
);
7524 // If we haven't already read 'static', check to see if there is one after the
7525 // type-qualifier-list.
7526 if (!StaticLoc
.isValid())
7527 TryConsumeToken(tok::kw_static
, StaticLoc
);
7529 // Handle "direct-declarator [ type-qual-list[opt] * ]".
7530 bool isStar
= false;
7531 ExprResult NumElements
;
7533 // Handle the case where we have '[*]' as the array size. However, a leading
7534 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
7535 // the token after the star is a ']'. Since stars in arrays are
7536 // infrequent, use of lookahead is not costly here.
7537 if (Tok
.is(tok::star
) && GetLookAheadToken(1).is(tok::r_square
)) {
7538 ConsumeToken(); // Eat the '*'.
7540 if (StaticLoc
.isValid()) {
7541 Diag(StaticLoc
, diag::err_unspecified_vla_size_with_static
);
7542 StaticLoc
= SourceLocation(); // Drop the static.
7545 } else if (Tok
.isNot(tok::r_square
)) {
7546 // Note, in C89, this production uses the constant-expr production instead
7547 // of assignment-expr. The only difference is that assignment-expr allows
7548 // things like '=' and '*='. Sema rejects these in C89 mode because they
7549 // are not i-c-e's, so we don't need to distinguish between the two here.
7551 // Parse the constant-expression or assignment-expression now (depending
7553 if (getLangOpts().CPlusPlus
) {
7554 NumElements
= ParseConstantExpression();
7556 EnterExpressionEvaluationContext
Unevaluated(
7557 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
7559 Actions
.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
7562 if (StaticLoc
.isValid()) {
7563 Diag(StaticLoc
, diag::err_unspecified_size_with_static
);
7564 StaticLoc
= SourceLocation(); // Drop the static.
7568 // If there was an error parsing the assignment-expression, recover.
7569 if (NumElements
.isInvalid()) {
7570 D
.setInvalidType(true);
7571 // If the expression was invalid, skip it.
7572 SkipUntil(tok::r_square
, StopAtSemi
);
7578 MaybeParseCXX11Attributes(DS
.getAttributes());
7580 // Remember that we parsed a array type, and remember its features.
7582 DeclaratorChunk::getArray(DS
.getTypeQualifiers(), StaticLoc
.isValid(),
7583 isStar
, NumElements
.get(), T
.getOpenLocation(),
7584 T
.getCloseLocation()),
7585 std::move(DS
.getAttributes()), T
.getCloseLocation());
7588 /// Diagnose brackets before an identifier.
7589 void Parser::ParseMisplacedBracketDeclarator(Declarator
&D
) {
7590 assert(Tok
.is(tok::l_square
) && "Missing opening bracket");
7591 assert(!D
.mayOmitIdentifier() && "Declarator cannot omit identifier");
7593 SourceLocation StartBracketLoc
= Tok
.getLocation();
7594 Declarator
TempDeclarator(D
.getDeclSpec(), ParsedAttributesView::none(),
7597 while (Tok
.is(tok::l_square
)) {
7598 ParseBracketDeclarator(TempDeclarator
);
7601 // Stuff the location of the start of the brackets into the Declarator.
7602 // The diagnostics from ParseDirectDeclarator will make more sense if
7603 // they use this location instead.
7604 if (Tok
.is(tok::semi
))
7605 D
.getName().EndLocation
= StartBracketLoc
;
7607 SourceLocation SuggestParenLoc
= Tok
.getLocation();
7609 // Now that the brackets are removed, try parsing the declarator again.
7610 ParseDeclaratorInternal(D
, &Parser::ParseDirectDeclarator
);
7612 // Something went wrong parsing the brackets, in which case,
7613 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7615 if (TempDeclarator
.getNumTypeObjects() == 0)
7618 // Determine if parens will need to be suggested in the diagnostic.
7619 bool NeedParens
= false;
7620 if (D
.getNumTypeObjects() != 0) {
7621 switch (D
.getTypeObject(D
.getNumTypeObjects() - 1).Kind
) {
7622 case DeclaratorChunk::Pointer
:
7623 case DeclaratorChunk::Reference
:
7624 case DeclaratorChunk::BlockPointer
:
7625 case DeclaratorChunk::MemberPointer
:
7626 case DeclaratorChunk::Pipe
:
7629 case DeclaratorChunk::Array
:
7630 case DeclaratorChunk::Function
:
7631 case DeclaratorChunk::Paren
:
7637 // Create a DeclaratorChunk for the inserted parens.
7638 SourceLocation EndLoc
= PP
.getLocForEndOfToken(D
.getEndLoc());
7639 D
.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc
, EndLoc
),
7643 // Adding back the bracket info to the end of the Declarator.
7644 for (unsigned i
= 0, e
= TempDeclarator
.getNumTypeObjects(); i
< e
; ++i
) {
7645 const DeclaratorChunk
&Chunk
= TempDeclarator
.getTypeObject(i
);
7646 D
.AddTypeInfo(Chunk
, SourceLocation());
7649 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7650 // If parentheses are required, always suggest them.
7651 if (!D
.getIdentifier() && !NeedParens
)
7654 SourceLocation EndBracketLoc
= TempDeclarator
.getEndLoc();
7656 // Generate the move bracket error message.
7657 SourceRange
BracketRange(StartBracketLoc
, EndBracketLoc
);
7658 SourceLocation EndLoc
= PP
.getLocForEndOfToken(D
.getEndLoc());
7661 Diag(EndLoc
, diag::err_brackets_go_after_unqualified_id
)
7662 << getLangOpts().CPlusPlus
7663 << FixItHint::CreateInsertion(SuggestParenLoc
, "(")
7664 << FixItHint::CreateInsertion(EndLoc
, ")")
7665 << FixItHint::CreateInsertionFromRange(
7666 EndLoc
, CharSourceRange(BracketRange
, true))
7667 << FixItHint::CreateRemoval(BracketRange
);
7669 Diag(EndLoc
, diag::err_brackets_go_after_unqualified_id
)
7670 << getLangOpts().CPlusPlus
7671 << FixItHint::CreateInsertionFromRange(
7672 EndLoc
, CharSourceRange(BracketRange
, true))
7673 << FixItHint::CreateRemoval(BracketRange
);
7677 /// [GNU] typeof-specifier:
7678 /// typeof ( expressions )
7679 /// typeof ( type-name )
7680 /// [GNU/C++] typeof unary-expression
7681 /// [C2x] typeof-specifier:
7682 /// typeof '(' typeof-specifier-argument ')'
7683 /// typeof_unqual '(' typeof-specifier-argument ')'
7685 /// typeof-specifier-argument:
7689 void Parser::ParseTypeofSpecifier(DeclSpec
&DS
) {
7690 assert(Tok
.isOneOf(tok::kw_typeof
, tok::kw_typeof_unqual
) &&
7691 "Not a typeof specifier");
7693 bool IsUnqual
= Tok
.is(tok::kw_typeof_unqual
);
7694 const IdentifierInfo
*II
= Tok
.getIdentifierInfo();
7695 if (getLangOpts().C2x
&& !II
->getName().startswith("__"))
7696 Diag(Tok
.getLocation(), diag::warn_c2x_compat_keyword
) << Tok
.getName();
7699 SourceLocation StartLoc
= ConsumeToken();
7700 bool HasParens
= Tok
.is(tok::l_paren
);
7702 EnterExpressionEvaluationContext
Unevaluated(
7703 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
,
7704 Sema::ReuseLambdaContextDecl
);
7708 SourceRange CastRange
;
7709 ExprResult Operand
= Actions
.CorrectDelayedTyposInExpr(
7710 ParseExprAfterUnaryExprOrTypeTrait(OpTok
, isCastExpr
, CastTy
, CastRange
));
7712 DS
.setTypeArgumentRange(CastRange
);
7714 if (CastRange
.getEnd().isInvalid())
7715 // FIXME: Not accurate, the range gets one token more than it should.
7716 DS
.SetRangeEnd(Tok
.getLocation());
7718 DS
.SetRangeEnd(CastRange
.getEnd());
7722 DS
.SetTypeSpecError();
7726 const char *PrevSpec
= nullptr;
7728 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7729 if (DS
.SetTypeSpecType(IsUnqual
? DeclSpec::TST_typeof_unqualType
7730 : DeclSpec::TST_typeofType
,
7733 Actions
.getASTContext().getPrintingPolicy()))
7734 Diag(StartLoc
, DiagID
) << PrevSpec
;
7738 // If we get here, the operand to the typeof was an expression.
7739 if (Operand
.isInvalid()) {
7740 DS
.SetTypeSpecError();
7744 // We might need to transform the operand if it is potentially evaluated.
7745 Operand
= Actions
.HandleExprEvaluationContextForTypeof(Operand
.get());
7746 if (Operand
.isInvalid()) {
7747 DS
.SetTypeSpecError();
7751 const char *PrevSpec
= nullptr;
7753 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7754 if (DS
.SetTypeSpecType(IsUnqual
? DeclSpec::TST_typeof_unqualExpr
7755 : DeclSpec::TST_typeofExpr
,
7757 DiagID
, Operand
.get(),
7758 Actions
.getASTContext().getPrintingPolicy()))
7759 Diag(StartLoc
, DiagID
) << PrevSpec
;
7762 /// [C11] atomic-specifier:
7763 /// _Atomic ( type-name )
7765 void Parser::ParseAtomicSpecifier(DeclSpec
&DS
) {
7766 assert(Tok
.is(tok::kw__Atomic
) && NextToken().is(tok::l_paren
) &&
7767 "Not an atomic specifier");
7769 SourceLocation StartLoc
= ConsumeToken();
7770 BalancedDelimiterTracker
T(*this, tok::l_paren
);
7771 if (T
.consumeOpen())
7774 TypeResult Result
= ParseTypeName();
7775 if (Result
.isInvalid()) {
7776 SkipUntil(tok::r_paren
, StopAtSemi
);
7783 if (T
.getCloseLocation().isInvalid())
7786 DS
.setTypeArgumentRange(T
.getRange());
7787 DS
.SetRangeEnd(T
.getCloseLocation());
7789 const char *PrevSpec
= nullptr;
7791 if (DS
.SetTypeSpecType(DeclSpec::TST_atomic
, StartLoc
, PrevSpec
,
7792 DiagID
, Result
.get(),
7793 Actions
.getASTContext().getPrintingPolicy()))
7794 Diag(StartLoc
, DiagID
) << PrevSpec
;
7797 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7798 /// from TryAltiVecVectorToken.
7799 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7800 Token Next
= NextToken();
7801 switch (Next
.getKind()) {
7802 default: return false;
7805 case tok::kw_signed
:
7806 case tok::kw_unsigned
:
7811 case tok::kw_double
:
7814 case tok::kw___bool
:
7815 case tok::kw___pixel
:
7816 Tok
.setKind(tok::kw___vector
);
7818 case tok::identifier
:
7819 if (Next
.getIdentifierInfo() == Ident_pixel
) {
7820 Tok
.setKind(tok::kw___vector
);
7823 if (Next
.getIdentifierInfo() == Ident_bool
||
7824 Next
.getIdentifierInfo() == Ident_Bool
) {
7825 Tok
.setKind(tok::kw___vector
);
7832 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec
&DS
, SourceLocation Loc
,
7833 const char *&PrevSpec
, unsigned &DiagID
,
7835 const PrintingPolicy
&Policy
= Actions
.getASTContext().getPrintingPolicy();
7836 if (Tok
.getIdentifierInfo() == Ident_vector
) {
7837 Token Next
= NextToken();
7838 switch (Next
.getKind()) {
7841 case tok::kw_signed
:
7842 case tok::kw_unsigned
:
7847 case tok::kw_double
:
7850 case tok::kw___bool
:
7851 case tok::kw___pixel
:
7852 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
, Policy
);
7854 case tok::identifier
:
7855 if (Next
.getIdentifierInfo() == Ident_pixel
) {
7856 isInvalid
= DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
,Policy
);
7859 if (Next
.getIdentifierInfo() == Ident_bool
||
7860 Next
.getIdentifierInfo() == Ident_Bool
) {
7862 DS
.SetTypeAltiVecVector(true, Loc
, PrevSpec
, DiagID
, Policy
);
7869 } else if ((Tok
.getIdentifierInfo() == Ident_pixel
) &&
7870 DS
.isTypeAltiVecVector()) {
7871 isInvalid
= DS
.SetTypeAltiVecPixel(true, Loc
, PrevSpec
, DiagID
, Policy
);
7873 } else if ((Tok
.getIdentifierInfo() == Ident_bool
) &&
7874 DS
.isTypeAltiVecVector()) {
7875 isInvalid
= DS
.SetTypeAltiVecBool(true, Loc
, PrevSpec
, DiagID
, Policy
);
7881 void Parser::DiagnoseBitIntUse(const Token
&Tok
) {
7882 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
7883 // the token is about _BitInt and gets (potentially) diagnosed as use of an
7885 assert(Tok
.isOneOf(tok::kw__ExtInt
, tok::kw__BitInt
) &&
7886 "expected either an _ExtInt or _BitInt token!");
7888 SourceLocation Loc
= Tok
.getLocation();
7889 if (Tok
.is(tok::kw__ExtInt
)) {
7890 Diag(Loc
, diag::warn_ext_int_deprecated
)
7891 << FixItHint::CreateReplacement(Loc
, "_BitInt");
7893 // In C2x mode, diagnose that the use is not compatible with pre-C2x modes.
7894 // Otherwise, diagnose that the use is a Clang extension.
7895 if (getLangOpts().C2x
)
7896 Diag(Loc
, diag::warn_c2x_compat_keyword
) << Tok
.getName();
7898 Diag(Loc
, diag::ext_bit_int
) << getLangOpts().CPlusPlus
;