[clang-repl] Consider the scope spec in template lookups for deduction guides.
[llvm-project.git] / clang / lib / Parse / ParseDecl.cpp
blob2bbe2ba82139d47cd8947a3697a0931a667656df
1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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"
32 #include <optional>
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // C99 6.7: Declarations.
38 //===----------------------------------------------------------------------===//
40 /// ParseTypeName
41 /// type-name: [C99 6.7.6]
42 /// specifier-qualifier-list abstract-declarator[opt]
43 ///
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);
54 if (Attrs)
55 DS.addAttributes(*Attrs);
56 ParseSpecifierQualifierList(DS, AS, DSC);
57 if (OwnedType)
58 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
60 // Move declspec attributes to ParsedAttributes
61 if (Attrs) {
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);
75 if (Range)
76 *Range = DeclaratorInfo.getSourceRange();
78 if (DeclaratorInfo.isInvalidType())
79 return true;
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);
88 return Name;
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"
97 .Default(false);
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())
105 return false;
107 SourceManager &SM = PP.getSourceManager();
108 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
109 return false;
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) {
120 bool MoreToParse;
121 do {
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.
124 MoreToParse = false;
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:
137 /// attribute
138 /// attributes attribute
140 /// [GNU] attribute:
141 /// '__attribute__' '(' '(' attribute-list ')' ')'
143 /// [GNU] attribute-list:
144 /// attrib
145 /// attribute_list ',' attrib
147 /// [GNU] attrib:
148 /// empty
149 /// attrib-name
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:
155 /// identifier
156 /// typespec
157 /// typequal
158 /// storageclass
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
168 /// limited).
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,
188 "attribute")) {
189 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
190 return;
192 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
193 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
194 return;
196 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
197 do {
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())
204 break;
205 if (Tok.is(tok::code_completion)) {
206 cutOffParsing();
207 Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
208 break;
210 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
211 if (!AttrName)
212 break;
214 SourceLocation AttrNameLoc = ConsumeToken();
216 if (Tok.isNot(tok::l_paren)) {
217 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
218 ParsedAttr::Form::GNU());
219 continue;
222 // Handle "parameterized" attributes
223 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
224 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
225 SourceLocation(), ParsedAttr::Form::GNU(), D);
226 continue;
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);
242 ConsumeParen();
243 // Consume everything up to and including the matching right parens.
244 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
246 Token Eof;
247 Eof.startToken();
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);
257 EndLoc = Loc;
259 // If this was declared in a macro, attach the macro IdentifierInfo to the
260 // parsed attribute.
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());
272 if (LateAttrs) {
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"
287 .Default(false);
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"
296 .Default(false);
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"
305 .Default(false);
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"
314 .Default(false);
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"
323 .Default(false);
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"
333 .Default(false);
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,
340 Tok.getLocation(),
341 Tok.getIdentifierInfo());
342 ConsumeToken();
343 return IL;
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();
355 TypeResult T;
356 if (Tok.isNot(tok::r_paren))
357 T = ParseTypeName();
359 if (Parens.consumeClose())
360 return;
362 if (T.isInvalid())
363 return;
365 if (T.isUsable())
366 Attrs.addNewTypeAttr(&AttrName,
367 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
368 ScopeName, ScopeLoc, T.get(), Form);
369 else
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.
379 ConsumeParen();
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);
390 ArgsVector ArgExprs;
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);
406 if (IsIdentifierArg)
407 ArgExprs.push_back(ParseIdentifierLoc());
410 ParsedType TheParsedType;
411 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
412 // Eat the comma.
413 if (!ArgExprs.empty())
414 ConsumeToken();
416 if (AttributeIsTypeArgAttr) {
417 // FIXME: Multiple type arguments are not implemented.
418 TypeResult T = ParseTypeName();
419 if (T.isInvalid()) {
420 SkipUntil(tok::r_paren, StopAtSemi);
421 return 0;
423 if (T.isUsable())
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.
431 do {
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);
436 ExprResult ArgExpr;
437 if (Tok.is(tok::identifier)) {
438 ArgExprs.push_back(ParseIdentifierLoc());
439 } else {
440 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
441 EnterExpressionEvaluationContext Unevaluated(
442 Actions,
443 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
444 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
446 ExprResult ArgExpr(
447 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
449 if (ArgExpr.isInvalid()) {
450 SkipUntil(tok::r_paren, StopAtSemi);
451 return 0;
453 ArgExprs.push_back(ArgExpr.get());
455 // Eat the comma, move to the next argument
456 } while (TryConsumeToken(tok::comma));
457 } else {
458 // General case. Parse all available expressions.
459 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
460 EnterExpressionEvaluationContext Unevaluated(
461 Actions, Uneval
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);
470 return 0;
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]))
476 continue;
478 if (!attributeAcceptsExprPack(*AttrName)) {
479 Diag(Tok.getLocation(),
480 diag::err_attribute_argument_parm_pack_not_supported)
481 << AttrName;
482 SkipUntil(tok::r_paren, StopAtSemi);
483 return 0;
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);
498 } else {
499 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
500 ArgExprs.data(), ArgExprs.size(), Form);
504 if (EndLoc)
505 *EndLoc = RParen;
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,
524 ScopeLoc, Form);
525 return;
526 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
527 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
528 ScopeName, ScopeLoc, Form);
529 return;
530 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
531 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
532 ScopeName, ScopeLoc, Form);
533 return;
534 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
535 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
536 ScopeLoc, Form);
537 return;
538 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
539 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
540 ScopeName, ScopeLoc, Form);
541 return;
542 } else if (attributeIsTypeArgAttr(*AttrName)) {
543 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
544 ScopeLoc, Form);
545 return;
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 |
556 Scope::DeclScope);
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,
564 ScopeLoc, Form);
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());
576 switch (AttrKind) {
577 default:
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);
583 break;
584 case ParsedAttr::AT_Availability:
585 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
586 ScopeLoc, Form);
587 break;
588 case ParsedAttr::AT_ObjCBridgeRelated:
589 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
590 ScopeName, ScopeLoc, Form);
591 break;
592 case ParsedAttr::AT_SwiftNewType:
593 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
594 ScopeLoc, Form);
595 break;
596 case ParsedAttr::AT_TypeTagForDatatype:
597 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
598 ScopeName, ScopeLoc, Form);
599 break;
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
610 // arguments.
611 if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
612 getTargetInfo(), getLangOpts())) {
613 // Eat the left paren, then skip to the ending right paren.
614 ConsumeParen();
615 SkipUntil(tok::r_paren);
616 return false;
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);
630 enum AccessorKind {
631 AK_Invalid = -1,
632 AK_Put = 0,
633 AK_Get = 1 // indices into AccessorNames
635 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
636 bool HasInvalidAccessor = false;
638 // Parse the accessor specifications.
639 while (true) {
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);
647 break;
650 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
651 break;
654 AccessorKind Kind;
655 SourceLocation KindLoc = Tok.getLocation();
656 StringRef KindStr = Tok.getIdentifierInfo()->getName();
657 if (KindStr == "get") {
658 Kind = AK_Get;
659 } else if (KindStr == "put") {
660 Kind = AK_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");
666 Kind = AK_Put;
668 // Handle the mistake of forgetting the accessor kind by skipping
669 // this accessor.
670 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
671 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
672 ConsumeToken();
673 HasInvalidAccessor = true;
674 goto next_property_accessor;
676 // Otherwise, complain about the unknown accessor kind.
677 } else {
678 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
679 HasInvalidAccessor = true;
680 Kind = AK_Invalid;
682 // Try to keep parsing unless it doesn't look like an accessor spec.
683 if (!NextToken().is(tok::equal))
684 break;
687 // Consume the identifier.
688 ConsumeToken();
690 // Consume the '='.
691 if (!TryConsumeToken(tok::equal)) {
692 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
693 << KindStr;
694 break;
697 // Expect the method name.
698 if (!Tok.is(tok::identifier)) {
699 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
700 break;
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;
708 } else {
709 AccessorNames[Kind] = Tok.getIdentifierInfo();
711 ConsumeToken();
713 next_property_accessor:
714 // Keep processing accessors until we run out.
715 if (TryConsumeToken(tok::comma))
716 continue;
718 // If we run into the ')', stop without consuming it.
719 if (Tok.is(tok::r_paren))
720 break;
722 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
723 break;
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());
731 T.skipToEnd();
732 return !HasInvalidAccessor;
735 unsigned NumArgs =
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;
743 return false;
745 return true;
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)) {
762 ConsumeToken();
763 BalancedDelimiterTracker T(*this, tok::l_paren);
764 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
765 tok::r_paren))
766 return;
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))
773 continue;
775 if (Tok.is(tok::code_completion)) {
776 cutOffParsing();
777 Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Declspec);
778 return;
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);
787 T.skipToEnd();
788 return;
791 IdentifierInfo *AttrName;
792 SourceLocation AttrNameLoc;
793 if (IsString) {
794 SmallString<8> StrBuffer;
795 bool Invalid = false;
796 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
797 if (Invalid) {
798 T.skipToEnd();
799 return;
801 AttrName = PP.getIdentifierInfo(Str);
802 AttrNameLoc = ConsumeStringToken();
803 } else {
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();
818 if (!AttrHandled)
819 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
820 ParsedAttr::Form::Declspec());
822 T.consumeClose();
823 EndLoc = T.getCloseLocation();
826 Attrs.Range = SourceRange(StartLoc, EndLoc);
829 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
830 // Treat these like attributes
831 while (true) {
832 auto Kind = Tok.getKind();
833 switch (Kind) {
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:
841 case tok::kw___w64:
842 case tok::kw___ptr32:
843 case tok::kw___sptr:
844 case tok::kw___uptr: {
845 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
846 SourceLocation AttrNameLoc = ConsumeToken();
847 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
848 Kind);
849 break;
851 default:
852 return;
857 void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
858 assert(Tok.is(tok::kw___funcref));
859 SourceLocation StartLoc = Tok.getLocation();
860 if (!getTargetInfo().getTriple().isWasm()) {
861 ConsumeToken();
862 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
863 return;
866 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
867 SourceLocation AttrNameLoc = ConsumeToken();
868 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
869 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
870 tok::kw___funcref);
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;
886 while (true) {
887 switch (Tok.getKind()) {
888 case tok::kw_const:
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:
897 case tok::kw___w64:
898 case tok::kw___unaligned:
899 case tok::kw___sptr:
900 case tok::kw___uptr:
901 EndLoc = ConsumeToken();
902 break;
903 default:
904 return EndLoc;
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,
915 tok::kw___pascal);
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,
925 tok::kw___kernel);
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,
942 Tok.getKind());
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.
958 while (true) {
959 auto Kind = Tok.getKind();
960 switch (Kind) {
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)
969 << AttrName;
970 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
971 Kind);
972 break;
974 default:
975 return;
980 static bool VersionNumberSeparator(const char Separator) {
981 return (Separator == '.' || Separator == '_');
984 /// Parse a version number.
986 /// version:
987 /// simple-integer
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);
1013 if (Invalid)
1014 return VersionTuple();
1016 // Parse the major version.
1017 unsigned AfterMajor = 0;
1018 unsigned Major = 0;
1019 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1020 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1021 ++AfterMajor;
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) {
1032 ConsumeToken();
1034 // We only had a single version component.
1035 if (Major == 0) {
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;
1054 unsigned Minor = 0;
1055 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1056 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1057 ++AfterMinor;
1060 if (AfterMinor == ActualLength) {
1061 ConsumeToken();
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';
1090 ++AfterSubminor;
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();
1099 ConsumeToken();
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')'
1109 /// platform:
1110 /// identifier
1112 /// opt-strict:
1113 /// 'strict' ','
1115 /// version-arg-list:
1116 /// version-arg
1117 /// version-arg ',' version-arg-list
1119 /// version-arg:
1120 /// 'introduced' '=' version
1121 /// 'deprecated' '=' version
1122 /// 'obsoleted' = version
1123 /// 'unavailable'
1124 /// opt-replacement:
1125 /// 'replacement' '=' <string>
1126 /// opt-message:
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;
1136 // Opening '('.
1137 BalancedDelimiterTracker T(*this, tok::l_paren);
1138 if (T.consumeOpen()) {
1139 Diag(Tok, diag::err_expected) << tok::l_paren;
1140 return;
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);
1147 return;
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");
1158 else
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);
1166 return;
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;
1184 do {
1185 if (Tok.isNot(tok::identifier)) {
1186 Diag(Tok, diag::err_availability_expected_change);
1187 SkipUntil(tok::r_paren, StopAtSemi);
1188 return;
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;
1199 continue;
1202 if (Keyword == Ident_unavailable) {
1203 if (UnavailableLoc.isValid()) {
1204 Diag(KeywordLoc, diag::err_availability_redundant)
1205 << Keyword << SourceRange(UnavailableLoc);
1207 UnavailableLoc = KeywordLoc;
1208 continue;
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)
1216 << Keyword
1217 << SourceRange(Changes[Deprecated].KeywordLoc);
1220 Changes[Deprecated].KeywordLoc = KeywordLoc;
1221 // Use a fake version here.
1222 Changes[Deprecated].Version = VersionTuple(1);
1223 continue;
1226 if (Tok.isNot(tok::equal)) {
1227 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1228 SkipUntil(tok::r_paren, StopAtSemi);
1229 return;
1231 ConsumeToken();
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);
1237 return;
1239 if (Keyword == Ident_message)
1240 MessageExpr = ParseStringLiteralExpression();
1241 else
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);
1251 return;
1254 if (Keyword == Ident_message)
1255 break;
1256 else
1257 continue;
1260 // Special handling of 'NA' only when applied to introduced or
1261 // deprecated.
1262 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1263 Tok.is(tok::identifier)) {
1264 IdentifierInfo *NA = Tok.getIdentifierInfo();
1265 if (NA->getName() == "NA") {
1266 ConsumeToken();
1267 if (Keyword == Ident_introduced)
1268 UnavailableLoc = KeywordLoc;
1269 continue;
1273 SourceRange VersionRange;
1274 VersionTuple Version = ParseVersionTuple(VersionRange);
1276 if (Version.empty()) {
1277 SkipUntil(tok::r_paren, StopAtSemi);
1278 return;
1281 unsigned Index;
1282 if (Keyword == Ident_introduced)
1283 Index = Introduced;
1284 else if (Keyword == Ident_deprecated)
1285 Index = Deprecated;
1286 else if (Keyword == Ident_obsoleted)
1287 Index = Obsoleted;
1288 else
1289 Index = Unknown;
1291 if (Index < Unknown) {
1292 if (!Changes[Index].KeywordLoc.isInvalid()) {
1293 Diag(KeywordLoc, diag::err_availability_redundant)
1294 << Keyword
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;
1302 } else {
1303 Diag(KeywordLoc, diag::err_availability_unknown_change)
1304 << Keyword << VersionRange;
1307 } while (TryConsumeToken(tok::comma));
1309 // Closing ')'.
1310 if (T.consumeClose())
1311 return;
1313 if (endLoc)
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()) {
1322 if (!Complained) {
1323 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1324 << SourceRange(Changes[Index].KeywordLoc,
1325 Changes[Index].VersionRange.getEnd());
1326 Complained = true;
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:
1349 /// keyword-arg
1350 /// keyword-arg ',' keyword-arg-list
1352 /// keyword-arg:
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) {
1361 // Opening '('.
1362 BalancedDelimiterTracker T(*this, tok::l_paren);
1363 if (T.expectAndConsume())
1364 return;
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;
1379 ExprResult USR;
1380 bool HasUSR = false;
1382 // Parse the language/defined_in/generated_declaration keywords
1383 do {
1384 if (Tok.isNot(tok::identifier)) {
1385 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1386 SkipUntil(tok::r_paren, StopAtSemi);
1387 return;
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);
1396 return;
1398 GeneratedDeclaration = ParseIdentifierLoc();
1399 continue;
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);
1406 return;
1409 ConsumeToken();
1410 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1411 Keyword->getName())) {
1412 SkipUntil(tok::r_paren, StopAtSemi);
1413 return;
1416 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1417 HadUSR = HasUSR;
1418 if (Keyword == Ident_language)
1419 HasLanguage = true;
1420 else if (Keyword == Ident_USR)
1421 HasUSR = true;
1422 else
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);
1433 continue;
1435 if (Keyword == Ident_language) {
1436 if (HadLanguage) {
1437 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1438 << Keyword;
1439 ParseStringLiteralExpression();
1440 continue;
1442 Language = ParseStringLiteralExpression();
1443 } else if (Keyword == Ident_USR) {
1444 if (HadUSR) {
1445 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1446 << Keyword;
1447 ParseStringLiteralExpression();
1448 continue;
1450 USR = ParseStringLiteralExpression();
1451 } else {
1452 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1453 if (HadDefinedIn) {
1454 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1455 << Keyword;
1456 ParseStringLiteralExpression();
1457 continue;
1459 DefinedInExpr = ParseStringLiteralExpression();
1461 } while (TryConsumeToken(tok::comma));
1463 // Closing ')'.
1464 if (T.consumeClose())
1465 return;
1466 if (EndLoc)
1467 *EndLoc = T.getCloseLocation();
1469 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1470 USR.get()};
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 ')'
1477 /// related_class:
1478 /// Identifier
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) {
1490 // Opening '('.
1491 BalancedDelimiterTracker T(*this, tok::l_paren);
1492 if (T.consumeOpen()) {
1493 Diag(Tok, diag::err_expected) << tok::l_paren;
1494 return;
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);
1501 return;
1503 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1504 if (ExpectAndConsume(tok::comma)) {
1505 SkipUntil(tok::r_paren, StopAtSemi);
1506 return;
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
1511 // nullptr.
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);
1518 return;
1521 if (!TryConsumeToken(tok::comma)) {
1522 if (Tok.is(tok::colon))
1523 Diag(Tok, diag::err_objcbridge_related_selector_name);
1524 else
1525 Diag(Tok, diag::err_expected) << tok::comma;
1526 SkipUntil(tok::r_paren, StopAtSemi);
1527 return;
1530 // Parse instance method name. Also non-optional but empty string is
1531 // permitted.
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);
1538 return;
1541 // Closing ')'.
1542 if (T.consumeClose())
1543 return;
1545 if (EndLoc)
1546 *EndLoc = T.getCloseLocation();
1548 // Record this attribute
1549 Attrs.addNew(&ObjCBridgeRelated,
1550 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1551 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1552 Form);
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);
1561 // Opening '('
1562 if (T.consumeOpen()) {
1563 Diag(Tok, diag::err_expected) << tok::l_paren;
1564 return;
1567 if (Tok.is(tok::r_paren)) {
1568 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1569 T.consumeClose();
1570 return;
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())
1576 ConsumeToken();
1577 T.consumeClose();
1578 return;
1581 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1582 Tok.getIdentifierInfo());
1583 ConsumeToken();
1585 // Closing ')'
1586 if (T.consumeClose())
1587 return;
1588 if (EndLoc)
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);
1603 T.consumeOpen();
1605 if (Tok.isNot(tok::identifier)) {
1606 Diag(Tok, diag::err_expected) << tok::identifier;
1607 T.skipToEnd();
1608 return;
1610 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1612 if (ExpectAndConsume(tok::comma)) {
1613 T.skipToEnd();
1614 return;
1617 SourceRange MatchingCTypeRange;
1618 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1619 if (MatchingCType.isInvalid()) {
1620 T.skipToEnd();
1621 return;
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;
1629 T.skipToEnd();
1630 return;
1632 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1633 if (Flag->isStr("layout_compatible"))
1634 LayoutCompatible = true;
1635 else if (Flag->isStr("must_be_null"))
1636 MustBeNull = true;
1637 else {
1638 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1639 T.skipToEnd();
1640 return;
1642 ConsumeToken(); // consume flag
1645 if (!T.consumeClose()) {
1646 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1647 ArgumentKind, MatchingCType.get(),
1648 LayoutCompatible, MustBeNull, Form);
1651 if (EndLoc)
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
1658 /// situation.
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.
1669 return false;
1671 case CAK_InvalidAttributeSpecifier:
1672 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1673 return false;
1675 case CAK_AttributeSpecifier:
1676 // Parse and discard the attributes.
1677 SourceLocation BeginLoc = ConsumeBracket();
1678 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);
1684 return true;
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);
1715 } else
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();
1728 Token FirstLSquare;
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;
1740 return;
1745 for (const ParsedAttr &AL : Attrs) {
1746 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1747 continue;
1748 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1749 if (WarnOnUnknownAttrs)
1750 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1751 << AL << AL.getRange();
1752 } else {
1753 Diag(AL.getLoc(), DiagID) << AL;
1754 AL.setInvalid();
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
1771 // variable.
1772 // This function moves attributes that should apply to the type off DS to Attrs.
1773 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1774 DeclSpec &DS,
1775 Sema::TagUseKind TUK) {
1776 if (TUK == Sema::TUK_Reference)
1777 return;
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);
1790 Attrs.addAtEnd(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
1802 /// others [FIXME]
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);
1826 SingleDecl =
1827 ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1828 break;
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);
1843 break;
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(),
1852 DeclEnd, Attrs);
1854 case tok::kw_static_assert:
1855 case tok::kw__Static_assert:
1856 ProhibitAttributes(DeclAttrs);
1857 ProhibitAttributes(DeclSpecAttrs);
1858 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1859 break;
1860 default:
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))
1911 return nullptr;
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);
1923 if (AnonRecord) {
1924 Decl* decls[] = {AnonRecord, TheDecl};
1925 return Actions.BuildDeclaratorGroup(decls);
1927 return Actions.ConvertDeclToDeclGroup(TheDecl);
1930 if (DeclSpecStart)
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:
1942 case tok::caret:
1943 case tok::code_completion:
1944 case tok::coloncolon:
1945 case tok::ellipsis:
1946 case tok::kw___attribute:
1947 case tok::kw_operator:
1948 case tok::l_paren:
1949 case tok::star:
1950 return true;
1952 case tok::amp:
1953 case tok::ampamp:
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:
1967 case tok::comma:
1968 case tok::equal:
1969 case tok::equalequal: // Might be a typo for '='.
1970 case tok::kw_alignas:
1971 case tok::kw_asm:
1972 case tok::kw___attribute:
1973 case tok::l_brace:
1974 case tok::l_paren:
1975 case tok::l_square:
1976 case tok::less:
1977 case tok::r_brace:
1978 case tok::r_paren:
1979 case tok::r_square:
1980 case tok::semi:
1981 return true;
1983 case tok::colon:
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());
1993 default:
1994 return false;
1997 default:
1998 return false;
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() {
2006 while (true) {
2007 switch (Tok.getKind()) {
2008 case tok::l_brace:
2009 // Skip until matching }, then stop. We've probably skipped over
2010 // a malformed class or function definition or similar.
2011 ConsumeBrace();
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.
2015 continue;
2017 TryConsumeToken(tok::semi);
2018 return;
2020 case tok::l_square:
2021 ConsumeBracket();
2022 SkipUntil(tok::r_square);
2023 continue;
2025 case tok::l_paren:
2026 ConsumeParen();
2027 SkipUntil(tok::r_paren);
2028 continue;
2030 case tok::r_brace:
2031 return;
2033 case tok::semi:
2034 ConsumeToken();
2035 return;
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))
2043 return;
2044 break;
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))
2052 return;
2053 break;
2055 case tok::at:
2056 // @end is very much like } in Objective-C contexts.
2057 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2058 ParsingInObjCContainer)
2059 return;
2060 break;
2062 case tok::minus:
2063 case tok::plus:
2064 // - and + probably start new method declarations in Objective-C contexts.
2065 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2066 return;
2067 break;
2069 case tok::eof:
2070 case tok::annot_module_begin:
2071 case tok::annot_module_end:
2072 case tok::annot_module_include:
2073 return;
2075 default:
2076 break;
2079 ConsumeAnyToken();
2083 /// ParseDeclGroup - Having concluded that this is either a function
2084 /// definition or a group of object declarations, actually parse the
2085 /// result.
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);
2098 ParseDeclarator(D);
2100 // Bail out if the first declarator didn't seem well-formed.
2101 if (!D.hasName() && !D.mayOmitIdentifier()) {
2102 SkipMalformedDecl();
2103 return nullptr;
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;
2125 unsigned DiagID;
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 ")
2136 : FixItHint());
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)) {
2141 cutOffParsing();
2142 Actions.CodeCompleteAfterFunctionEquals(D);
2143 return nullptr;
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
2150 // the declarator.
2151 while (auto Specifier = isCXX11VirtSpecifier()) {
2152 Diag(Tok, diag::err_virt_specifier_outside_class)
2153 << VirtSpecifiers::getSpecifierName(Specifier)
2154 << FixItHint::CreateRemoval(Tok.getLocation());
2155 ConsumeToken();
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(),
2175 &LateParsedAttrs);
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
2185 // semicolon.
2186 } else {
2187 Diag(Tok, diag::err_expected_fn_body);
2188 SkipUntil(tok::semi);
2189 return nullptr;
2191 } else {
2192 if (Tok.is(tok::l_brace)) {
2193 Diag(Tok, diag::err_function_definition_not_allowed);
2194 SkipMalformedDecl();
2195 return nullptr;
2201 if (ParseAsmAttributesAfterDeclarator(D))
2202 return nullptr;
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
2206 // analyzed.
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();
2218 else
2219 FRI->RangeExpr = ParseExpression();
2222 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2223 if (IsForRangeLoop) {
2224 Actions.ActOnCXXForRangeDecl(ThisDecl);
2225 } else {
2226 // Obj-C for loop
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);
2241 if (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
2247 // error, bail out.
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
2253 // semicolon.
2254 Diag(CommaLoc, diag::err_expected_semi_declaration)
2255 << FixItHint::CreateReplacement(CommaLoc, ";");
2256 ExpectSemi = false;
2257 break;
2260 // Parse the next declarator.
2261 D.clear();
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();
2277 ParseDeclarator(D);
2279 if (getLangOpts().HLSL)
2280 MaybeParseHLSLSemantics(D);
2282 if (!D.isInvalidType()) {
2283 // C++2a [dcl.decl]p1
2284 // init-declarator:
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);
2291 if (ThisDecl)
2292 DeclsInGroup.push_back(ThisDecl);
2296 if (DeclEnd)
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)) {
2320 SourceLocation Loc;
2321 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2322 if (AsmLabel.isInvalid()) {
2323 SkipUntil(tok::semi, StopBeforeMatch);
2324 return true;
2327 D.setAsmLabel(AsmLabel.get());
2328 D.SetRangeEnd(Loc);
2331 MaybeParseGNUAttributes(D);
2332 return false;
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]
2341 /// declarator
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))
2360 return nullptr;
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 {
2369 Parser &P;
2370 Declarator &D;
2371 Decl *ThisDecl;
2373 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2374 : P(P), D(D), ThisDecl(ThisDecl) {
2375 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2376 Scope *S = nullptr;
2377 if (D.getCXXScopeSpec().isSet()) {
2378 P.EnterScope(0);
2379 S = P.getCurScope();
2381 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2384 ~InitializerScopeRAII() { pop(); }
2385 void pop() {
2386 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2387 Scope *S = nullptr;
2388 if (D.getCXXScopeSpec().isSet())
2389 S = P.getCurScope();
2390 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2391 if (S)
2392 P.ExitScope();
2394 ThisDecl = nullptr;
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;
2408 else
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);
2419 break;
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
2428 // initialize it.
2429 ThisDecl = VT->getTemplatedDecl();
2430 OuterDecl = VT;
2432 break;
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);
2440 return nullptr;
2442 ThisDecl = ThisRes.get();
2443 } else {
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);
2453 } else {
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));
2467 ThisDecl =
2468 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2471 break;
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)
2483 << 1 /* delete */;
2484 else
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)
2489 << 0 /* default */;
2490 else
2491 Diag(ConsumeToken(), diag::err_default_special_members)
2492 << getLangOpts().CPlusPlus20;
2493 } else {
2494 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2496 if (Tok.is(tok::code_completion)) {
2497 cutOffParsing();
2498 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2499 Actions.FinalizeDeclaration(ThisDecl);
2500 return nullptr;
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;
2514 Init = ExprError();
2515 FRI->RangeExpr = Init;
2518 InitScope.pop();
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);
2528 } else
2529 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2530 /*DirectInit=*/false);
2532 break;
2534 case InitKind::CXXDirect: {
2535 // Parse C++ direct initializer: '(' expression-list ')'
2536 BalancedDelimiterTracker T(*this, tok::l_paren);
2537 T.consumeOpen();
2539 ExprVector Exprs;
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(),
2548 /*Braced=*/false);
2549 CalledSignatureHelp = true;
2550 return PreferredType;
2552 auto SetPreferredType = [&] {
2553 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2556 llvm::function_ref<void()> ExpressionStarts;
2557 if (ThisVarDecl) {
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(),
2569 /*Braced=*/false);
2570 CalledSignatureHelp = true;
2572 Actions.ActOnInitializerError(ThisDecl);
2573 SkipUntil(tok::r_paren, StopAtSemi);
2574 } else {
2575 // Match the ')'.
2576 T.consumeClose();
2577 InitScope.pop();
2579 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2580 T.getCloseLocation(),
2581 Exprs);
2582 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2583 /*DirectInit=*/true);
2585 break;
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());
2596 InitScope.pop();
2598 if (Init.isInvalid()) {
2599 Actions.ActOnInitializerError(ThisDecl);
2600 } else
2601 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2602 break;
2604 case InitKind::Uninitialized: {
2605 Actions.ActOnUninitializedDecl(ThisDecl);
2606 break;
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);
2644 else
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).
2687 /// int (x)
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,
2692 tok::colon);
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.
2735 return false;
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())
2741 return false;
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.
2747 if (SS)
2748 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2749 return 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
2756 // classes.
2757 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2758 *Tok.getIdentifierInfo(), Tok.getLocation(),
2759 DSC == DeclSpecContext::DSC_template_type_arg)) {
2760 const char *PrevSpec;
2761 unsigned DiagID;
2762 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2763 Actions.getASTContext().getPrintingPolicy());
2764 DS.SetRangeEnd(Tok.getLocation());
2765 ConsumeToken();
2766 return false;
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())) {
2781 default: break;
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;
2795 if (TagName) {
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();
2806 I != IEnd; ++I)
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);
2815 else
2816 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2817 /*EnteringContext*/ false,
2818 DeclSpecContext::DSC_normal, Attrs);
2819 return true;
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);
2838 ConsumeToken();
2839 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2840 PA.Revert();
2842 if (TPR != TPResult::False) {
2843 // The identifier is followed by a parenthesized declarator.
2844 // It's supposed to be a type.
2845 break;
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);
2860 // Fall through.
2861 [[fallthrough]];
2863 case tok::comma:
2864 case tok::equal:
2865 case tok::kw_asm:
2866 case tok::l_brace:
2867 case tok::l_square:
2868 case tok::semi:
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())
2873 break;
2874 if (SS)
2875 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2876 return false;
2878 default:
2879 // This is probably supposed to be a type. This includes cases like:
2880 // int f(itn);
2881 // struct S { unsigned : 4; };
2882 break;
2886 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2887 // and attempt to recover.
2888 ParsedType T;
2889 IdentifierInfo *II = Tok.getIdentifierInfo();
2890 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2891 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2892 IsTemplateName);
2893 if (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;
2898 unsigned DiagID;
2899 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2900 Actions.getASTContext().getPrintingPolicy());
2901 DS.SetRangeEnd(Tok.getLocation());
2902 ConsumeToken();
2903 // There may be other declaration specifiers after this.
2904 return true;
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.
2909 return true;
2912 // Otherwise, the action had no suggestion for us. Mark this as an error.
2913 DS.SetTypeSpecError();
2914 DS.SetRangeEnd(Tok.getLocation());
2915 ConsumeToken();
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.
2927 return true;
2930 /// Determine the declaration specifier context from the declarator
2931 /// context.
2933 /// \param Context the declarator context, which is one of the
2934 /// DeclaratorContext enumerator values.
2935 Parser::DeclSpecContext
2936 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2937 switch (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.
2988 /// [C11] type-id
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) {
2994 ExprResult ER;
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);
3001 } else
3002 ER = ParseConstantExpression();
3004 if (getLangOpts().CPlusPlus11)
3005 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3007 return ER;
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())
3029 return;
3031 SourceLocation EllipsisLoc;
3032 ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
3033 if (ArgExpr.isInvalid()) {
3034 T.skipToEnd();
3035 return;
3038 T.consumeClose();
3039 if (EndLoc)
3040 *EndLoc = T.getCloseLocation();
3042 ArgsVector ArgExprs;
3043 ArgExprs.push_back(ArgExpr.get());
3044 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3045 EllipsisLoc);
3048 ExprResult Parser::ParseExtIntegerArgument() {
3049 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3050 "Not an extended int type");
3051 ConsumeToken();
3053 BalancedDelimiterTracker T(*this, tok::l_paren);
3054 if (T.expectAndConsume())
3055 return ExprError();
3057 ExprResult ER = ParseConstantExpression();
3058 if (ER.isInvalid()) {
3059 T.skipToEnd();
3060 return ExprError();
3063 if(T.consumeClose())
3064 return ExprError();
3065 return ER;
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
3071 /// specifier.
3073 /// \return \c true if an error occurred and this can't be any kind of
3074 /// declaration.
3075 bool
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();
3089 return true;
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
3097 // declarator.
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.
3122 CXXScopeSpec SS;
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,
3128 /*CCC=*/nullptr);
3129 switch (Classification.getKind()) {
3130 case Sema::NC_Error:
3131 SkipMalformedDecl();
3132 return true;
3134 case Sema::NC_Keyword:
3135 llvm_unreachable("typo correction is not possible here");
3137 case Sema::NC_Type:
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;
3143 break;
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.
3153 break;
3158 if (MightBeDeclarator)
3159 return false;
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);
3176 return false;
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,
3183 bool &isInvalid) {
3184 assert(!LangOpts.FixedPoint);
3185 DiagID = diag::err_fixed_point_not_enabled;
3186 PrevSpec = ""; // Not used by diagnostic
3187 isInvalid = true;
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]
3201 /// 'typedef'
3202 /// 'extern'
3203 /// 'static'
3204 /// 'auto'
3205 /// 'register'
3206 /// [C++] 'mutable'
3207 /// [C++11] 'thread_local'
3208 /// [C11] '_Thread_local'
3209 /// [GNU] '__thread'
3210 /// function-specifier: [C99 6.7.4]
3211 /// [C99] 'inline'
3212 /// [C++] 'virtual'
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
3224 // consume a token.
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();
3243 while (true) {
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);
3274 return false;
3276 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3277 return true;
3280 // Turn off usual access checking for template specializations and
3281 // instantiations.
3282 bool IsTemplateSpecOrInst =
3283 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3284 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3286 switch (Tok.getKind()) {
3287 default:
3288 DoneWithDeclSpec:
3289 if (!AttrsLastTime)
3290 ProhibitAttributes(attrs);
3291 else {
3292 // Reject C++11 / C2x attributes that aren't type attributes.
3293 for (const ParsedAttr &PA : attrs) {
3294 if (!PA.isCXX11Attribute() && !PA.isC2xAttribute())
3295 continue;
3296 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3297 // We will warn about the unknown attribute elsewhere (in
3298 // SemaDeclAttr.cpp)
3299 continue;
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;
3304 PA.setInvalid();
3305 continue;
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)
3312 continue;
3313 Diag(PA.getLoc(), diag::err_attribute_not_type_attr) << PA;
3314 PA.setInvalid();
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);
3323 return;
3325 case tok::l_square:
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.
3334 attrs.clear();
3335 attrs.Range = SourceRange();
3337 ParseCXX11Attributes(attrs);
3338 AttrsLastTime = true;
3339 continue;
3341 case tok::code_completion: {
3342 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3343 if (DS.hasTypeSpecifier()) {
3344 bool AllowNonIdentifiers
3345 = (getCurScope()->getFlags() & (Scope::ControlScope |
3346 Scope::BlockScope |
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());
3354 cutOffParsing();
3355 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3356 AllowNonIdentifiers,
3357 AllowNestedNameSpecifiers);
3358 return;
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;
3372 cutOffParsing();
3373 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3374 return;
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;
3386 continue;
3388 case tok::annot_cxxscope: {
3389 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3390 goto DoneWithDeclSpec;
3392 CXXScopeSpec SS;
3393 if (TemplateInfo.TemplateParams)
3394 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3395 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3396 Tok.getAnnotationRange(),
3397 SS);
3399 // We are looking for a qualified typename.
3400 Token Next = NextToken();
3402 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3403 ? takeTemplateIdAnnotation(Next)
3404 : nullptr;
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();
3410 break;
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) &&
3425 TemplateId->Name &&
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);
3442 continue;
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();
3452 continue;
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);
3462 if (isInvalid)
3463 break;
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);
3475 continue;
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(),
3487 &SS) &&
3488 isConstructorDeclarator(/*Unqualified=*/false,
3489 /*DeductionGuide=*/false,
3490 DS.isFriendSpecified(),
3491 &TemplateInfo))
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:
3497 // - `return type`.
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)
3508 SAC.done();
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
3513 // typename.
3514 if (!TypeRep) {
3515 if (TryAnnotateTypeConstraint())
3516 goto DoneWithDeclSpec;
3517 if (Tok.isNot(tok::annot_cxxscope) ||
3518 NextToken().isNot(tok::identifier))
3519 continue;
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);
3528 continue;
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);
3538 if (isInvalid)
3539 break;
3541 DS.SetRangeEnd(Tok.getLocation());
3542 ConsumeToken(); // The typename.
3544 continue;
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,
3555 DiagID, T, Policy);
3556 if (isInvalid)
3557 break;
3559 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3560 ConsumeAnnotationToken(); // The typename
3562 continue;
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;
3581 // typedef-name
3582 case tok::kw___super:
3583 case tok::kw_decltype:
3584 case tok::identifier:
3585 ParseIdentifier: {
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.
3604 ConsumeToken();
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?");
3610 return;
3612 T.skipToEnd();
3613 continue;
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:
3623 // - `return type`.
3624 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3626 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3628 if (IsTemplateSpecOrInst)
3629 SAC.done();
3631 if (Success) {
3632 if (IsTemplateSpecOrInst)
3633 SAC.redelay();
3634 DS.SetTypeSpecError();
3635 goto DoneWithDeclSpec;
3638 if (!Tok.is(tok::identifier))
3639 continue;
3642 // Check for need to substitute AltiVec keyword tokens.
3643 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3644 break;
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);
3654 assert(TypeRep);
3655 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3656 DiagID, TypeRep, Policy);
3657 if (isInvalid)
3658 break;
3660 DS.SetRangeEnd(Loc);
3661 ConsumeToken();
3662 continue;
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.
3681 if (!TypeRep) {
3682 if (TryAnnotateTypeConstraint())
3683 goto DoneWithDeclSpec;
3684 if (Tok.isNot(tok::identifier))
3685 continue;
3686 ParsedAttributes Attrs(AttrFactory);
3687 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3688 if (!Attrs.empty()) {
3689 AttrsLastTime = true;
3690 attrs.takeAllFrom(Attrs);
3692 continue;
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.
3699 CXXScopeSpec SS;
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);
3711 if (isInvalid)
3712 break;
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,
3724 NewEndLoc);
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.
3733 continue;
3736 // type-name or placeholder-specifier
3737 case tok::annot_template_id: {
3738 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3740 if (TemplateId->hasInvalidName()) {
3741 DS.SetTypeSpecError();
3742 break;
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
3755 // a matching list.
3756 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3757 tok::kw_volatile, tok::kw_restrict, tok::amp,
3758 tok::ampamp)) {
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);
3764 break;
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;
3779 } else {
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,
3785 Tok.getLocation()),
3786 "auto");
3787 } else {
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);
3797 } else {
3798 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3799 TemplateId, Policy);
3801 break;
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.
3823 CXXScopeSpec SS;
3824 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3825 continue;
3828 // Attributes support.
3829 case tok::kw___attribute:
3830 case tok::kw___declspec:
3831 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
3832 continue;
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);
3841 break;
3844 case tok::kw___unaligned:
3845 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3846 getLangOpts());
3847 break;
3849 case tok::kw___sptr:
3850 case tok::kw___uptr:
3851 case tok::kw___ptr64:
3852 case tok::kw___ptr32:
3853 case tok::kw___w64:
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());
3861 continue;
3863 case tok::kw___funcref:
3864 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
3865 continue;
3867 // Borland single token adornments.
3868 case tok::kw___pascal:
3869 ParseBorlandTypeAttributes(DS.getAttributes());
3870 continue;
3872 // OpenCL single token adornments.
3873 case tok::kw___kernel:
3874 ParseOpenCLKernelAttributes(DS.getAttributes());
3875 continue;
3877 // CUDA/HIP single token adornments.
3878 case tok::kw___noinline__:
3879 ParseCUDAFunctionAttributes(DS.getAttributes());
3880 continue;
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());
3888 continue;
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();
3895 continue;
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;
3902 break;
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;
3909 break;
3910 case tok::kw___private_extern__:
3911 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3912 Loc, PrevSpec, DiagID, Policy);
3913 isStorageClass = true;
3914 break;
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;
3921 break;
3922 case tok::kw_auto:
3923 if (getLangOpts().CPlusPlus11) {
3924 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3925 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3926 PrevSpec, DiagID, Policy);
3927 if (!isInvalid)
3928 Diag(Tok, diag::ext_auto_storage_class)
3929 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3930 } else
3931 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3932 DiagID, Policy);
3933 } else
3934 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3935 PrevSpec, DiagID, Policy);
3936 isStorageClass = true;
3937 break;
3938 case tok::kw___auto_type:
3939 Diag(Tok, diag::ext_auto_type);
3940 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3941 DiagID, Policy);
3942 break;
3943 case tok::kw_register:
3944 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3945 PrevSpec, DiagID, Policy);
3946 isStorageClass = true;
3947 break;
3948 case tok::kw_mutable:
3949 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3950 PrevSpec, DiagID, Policy);
3951 isStorageClass = true;
3952 break;
3953 case tok::kw___thread:
3954 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3955 PrevSpec, DiagID);
3956 isStorageClass = true;
3957 break;
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,
3962 PrevSpec, DiagID);
3963 isStorageClass = true;
3964 break;
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;
3971 break;
3973 // function-specifier
3974 case tok::kw_inline:
3975 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3976 break;
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();
3985 isInvalid = true;
3986 } else {
3987 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3989 break;
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();
4010 ExplicitSpec =
4011 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4012 } else
4013 Tracker.skipToEnd();
4014 } else {
4015 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4018 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4019 ExplicitSpec, CloseParenLoc);
4020 break;
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);
4026 break;
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());
4033 continue;
4035 // friend
4036 case tok::kw_friend:
4037 if (DSContext == DeclSpecContext::DSC_class)
4038 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4039 else {
4040 PrevSpec = ""; // not actually used by the diagnostic
4041 DiagID = diag::err_friend_invalid_in_context;
4042 isInvalid = true;
4044 break;
4046 // Modules
4047 case tok::kw___module_private__:
4048 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4049 break;
4051 // constexpr, consteval, constinit specifiers
4052 case tok::kw_constexpr:
4053 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
4054 PrevSpec, DiagID);
4055 break;
4056 case tok::kw_consteval:
4057 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
4058 PrevSpec, DiagID);
4059 break;
4060 case tok::kw_constinit:
4061 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
4062 PrevSpec, DiagID);
4063 break;
4065 // type-specifier
4066 case tok::kw_short:
4067 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
4068 DiagID, Policy);
4069 break;
4070 case tok::kw_long:
4071 if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
4072 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
4073 DiagID, Policy);
4074 else
4075 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4076 PrevSpec, DiagID, Policy);
4077 break;
4078 case tok::kw___int64:
4079 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4080 PrevSpec, DiagID, Policy);
4081 break;
4082 case tok::kw_signed:
4083 isInvalid =
4084 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4085 break;
4086 case tok::kw_unsigned:
4087 isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
4088 DiagID);
4089 break;
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,
4094 DiagID);
4095 break;
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,
4100 DiagID);
4101 break;
4102 case tok::kw_void:
4103 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4104 DiagID, Policy);
4105 break;
4106 case tok::kw_char:
4107 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4108 DiagID, Policy);
4109 break;
4110 case tok::kw_int:
4111 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4112 DiagID, Policy);
4113 break;
4114 case tok::kw__ExtInt:
4115 case tok::kw__BitInt: {
4116 DiagnoseBitIntUse(Tok);
4117 ExprResult ER = ParseExtIntegerArgument();
4118 if (ER.isInvalid())
4119 continue;
4120 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4121 ConsumedEnd = PrevTokLocation;
4122 break;
4124 case tok::kw___int128:
4125 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
4126 DiagID, Policy);
4127 break;
4128 case tok::kw_half:
4129 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4130 DiagID, Policy);
4131 break;
4132 case tok::kw___bf16:
4133 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
4134 DiagID, Policy);
4135 break;
4136 case tok::kw_float:
4137 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4138 DiagID, Policy);
4139 break;
4140 case tok::kw_double:
4141 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
4142 DiagID, Policy);
4143 break;
4144 case tok::kw__Float16:
4145 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
4146 DiagID, Policy);
4147 break;
4148 case tok::kw__Accum:
4149 if (!getLangOpts().FixedPoint) {
4150 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4151 } else {
4152 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
4153 DiagID, Policy);
4155 break;
4156 case tok::kw__Fract:
4157 if (!getLangOpts().FixedPoint) {
4158 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4159 } else {
4160 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
4161 DiagID, Policy);
4163 break;
4164 case tok::kw__Sat:
4165 if (!getLangOpts().FixedPoint) {
4166 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4167 } else {
4168 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4170 break;
4171 case tok::kw___float128:
4172 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
4173 DiagID, Policy);
4174 break;
4175 case tok::kw___ibm128:
4176 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
4177 DiagID, Policy);
4178 break;
4179 case tok::kw_wchar_t:
4180 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4181 DiagID, Policy);
4182 break;
4183 case tok::kw_char8_t:
4184 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4185 DiagID, Policy);
4186 break;
4187 case tok::kw_char16_t:
4188 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
4189 DiagID, Policy);
4190 break;
4191 case tok::kw_char32_t:
4192 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
4193 DiagID, Policy);
4194 break;
4195 case tok::kw_bool:
4196 if (getLangOpts().C2x)
4197 Diag(Tok, diag::warn_c2x_compat_keyword) << Tok.getName();
4198 [[fallthrough]];
4199 case tok::kw__Bool:
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);
4210 isInvalid = true;
4211 } else {
4212 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4213 DiagID, Policy);
4215 break;
4216 case tok::kw__Decimal32:
4217 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
4218 DiagID, Policy);
4219 break;
4220 case tok::kw__Decimal64:
4221 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
4222 DiagID, Policy);
4223 break;
4224 case tok::kw__Decimal128:
4225 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
4226 DiagID, Policy);
4227 break;
4228 case tok::kw___vector:
4229 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4230 break;
4231 case tok::kw___pixel:
4232 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4233 break;
4234 case tok::kw___bool:
4235 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4236 break;
4237 case tok::kw_pipe:
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();
4248 isInvalid = true;
4249 } else
4250 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4251 break;
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; \
4259 break;
4260 #include "clang/Basic/OpenCLImageTypes.def"
4261 case tok::kw___unknown_anytype:
4262 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
4263 PrevSpec, DiagID, Policy);
4264 break;
4266 // class-specifier:
4267 case tok::kw_class:
4268 case tok::kw_struct:
4269 case tok::kw___interface:
4270 case tok::kw_union: {
4271 tok::TokenKind Kind = Tok.getKind();
4272 ConsumeToken();
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);
4287 continue;
4290 // enum-specifier:
4291 case tok::kw_enum:
4292 ConsumeToken();
4293 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4294 continue;
4296 // cv-qualifier:
4297 case tok::kw_const:
4298 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4299 getLangOpts());
4300 break;
4301 case tok::kw_volatile:
4302 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4303 getLangOpts());
4304 break;
4305 case tok::kw_restrict:
4306 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4307 getLangOpts());
4308 break;
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))
4317 continue;
4318 break;
4320 // C2x/GNU typeof support.
4321 case tok::kw_typeof:
4322 case tok::kw_typeof_unqual:
4323 ParseTypeofSpecifier(DS);
4324 continue;
4326 case tok::annot_decltype:
4327 ParseDecltypeSpecifier(DS);
4328 continue;
4330 case tok::annot_pragma_pack:
4331 HandlePragmaPack();
4332 continue;
4334 case tok::annot_pragma_ms_pragma:
4335 HandlePragmaMSPragma();
4336 continue;
4338 case tok::annot_pragma_ms_vtordisp:
4339 HandlePragmaMSVtorDisp();
4340 continue;
4342 case tok::annot_pragma_ms_pointers_to_members:
4343 HandlePragmaMSPointersToMembers();
4344 continue;
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;
4353 continue;
4355 case tok::kw__Atomic:
4356 // C11 6.7.2.4/4:
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
4359 // type qualifier.
4360 if (!getLangOpts().C11)
4361 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4363 if (NextToken().is(tok::l_paren)) {
4364 ParseAtomicSpecifier(DS);
4365 continue;
4367 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4368 getLangOpts());
4369 break;
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();
4380 isInvalid = true;
4381 break;
4383 [[fallthrough]];
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;
4389 [[fallthrough]];
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());
4399 break;
4401 case tok::kw_groupshared:
4402 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4403 ParseHLSLQualifiers(DS.getAttributes());
4404 continue;
4406 case tok::less:
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);
4423 } else {
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.
4429 continue;
4432 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4434 // If the specifier wasn't legal, issue a diagnostic.
4435 if (isInvalid) {
4436 assert(PrevSpec && "Method did not return previous specifier!");
4437 assert(DiagID);
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
4447 << isStorageClass;
4448 } else
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.
4454 ConsumeAnyToken();
4456 AttrsLastTime = false;
4460 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4461 /// semicolon.
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:
4476 /// 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.
4488 ConsumeToken();
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);
4512 return;
4515 // Read struct-declarators until we find the semicolon.
4516 bool FirstDeclarator = true;
4517 SourceLocation CommaLoc;
4518 while (true) {
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);
4537 } else
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);
4544 else
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))
4557 return;
4559 FirstDeclarator = false;
4563 /// ParseStructUnionBody
4564 /// struct-contents:
4565 /// struct-declaration-list
4566 /// [EXT] empty
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())
4581 return;
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);
4594 continue;
4597 // Parse _Static_assert declaration.
4598 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4599 SourceLocation DeclEnd;
4600 ParseStaticAssertDeclaration(DeclEnd);
4601 continue;
4604 if (Tok.is(tok::annot_pragma_pack)) {
4605 HandlePragmaPack();
4606 continue;
4609 if (Tok.is(tok::annot_pragma_align)) {
4610 HandlePragmaAlign();
4611 continue;
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);
4619 continue;
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();
4627 continue;
4630 if (!Tok.is(tok::at)) {
4631 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4632 // Install the declarator into the current TagDecl.
4633 Decl *Field =
4634 Actions.ActOnField(getCurScope(), TagDecl,
4635 FD.D.getDeclSpec().getSourceRange().getBegin(),
4636 FD.D, FD.BitfieldSize);
4637 FD.complete(Field);
4640 // Parse all the comma separated declarators.
4641 ParsingDeclSpec DS(*this);
4642 ParseStructDeclaration(DS, CFieldCallback);
4643 } else { // Handle @defs
4644 ConsumeToken();
4645 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4646 Diag(Tok, diag::err_unexpected_at);
4647 SkipUntil(tok::semi);
4648 continue;
4650 ConsumeToken();
4651 ExpectAndConsume(tok::l_paren);
4652 if (!Tok.is(tok::identifier)) {
4653 Diag(Tok, diag::err_expected) << tok::identifier;
4654 SkipUntil(tok::semi);
4655 continue;
4657 SmallVector<Decl *, 16> Fields;
4658 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4659 Tok.getIdentifierInfo(), Fields);
4660 ConsumeToken();
4661 ExpectAndConsume(tok::r_paren);
4664 if (TryConsumeToken(tok::semi))
4665 continue;
4667 if (Tok.is(tok::r_brace)) {
4668 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4669 break;
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);
4679 T.consumeClose();
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);
4689 StructScope.Exit();
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]
4700 /// '}'
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]
4713 /// 'enum'
4714 /// 'enum' 'class'
4715 /// 'enum' 'struct'
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.
4729 cutOffParsing();
4730 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4731 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4732 return;
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
4762 // specifier.
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);
4783 CXXScopeSpec Spec;
4784 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4785 /*ObjectHasErrors=*/false,
4786 /*EnteringContext=*/true))
4787 return;
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);
4796 return;
4800 SS = Spec;
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);
4811 return;
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{})
4854 // properly.
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
4861 // an enum-base.
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,
4877 // enum E : int *p;
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)
4893 << BaseRange;
4894 else if (getLangOpts().CPlusPlus)
4895 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4896 << BaseRange;
4897 else if (getLangOpts().MicrosoftExt)
4898 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4899 << BaseRange;
4900 else
4901 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4902 << BaseRange;
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());
4924 ConsumeBrace();
4925 SkipUntil(tok::r_brace, StopAtSemi);
4926 // Discard any other definition-only pieces.
4927 attrs.clear();
4928 ScopedEnumKWLoc = SourceLocation();
4929 IsScopedUsingClassTag = false;
4930 BaseType = TypeResult();
4931 TUK = Sema::TUK_Friend;
4932 } else {
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);
4949 } else {
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);
4969 return;
4972 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4973 // Enumerations can't be explicitly instantiated.
4974 DS.SetTypeSpecError();
4975 Diag(StartLoc, diag::err_explicit_instantiation_enum);
4976 return;
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);
4991 return;
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());
5023 bool Owned = false;
5024 bool IsDependent = false;
5025 const char *PrevSpec = nullptr;
5026 unsigned DiagID;
5027 Decl *TagDecl =
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);
5041 T.consumeOpen();
5042 T.skipToEnd();
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;
5049 return;
5052 if (IsDependent) {
5053 // This enum has a dependent nested-name-specifier. Handle it as a
5054 // dependent tag.
5055 if (!Name) {
5056 DS.SetTypeSpecError();
5057 Diag(Tok, diag::err_expected_type_name_after_typename);
5058 return;
5061 TypeResult Type = Actions.ActOnDependentTag(
5062 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5063 if (Type.isInvalid()) {
5064 DS.SetTypeSpecError();
5065 return;
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;
5074 return;
5077 if (!TagDecl) {
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) {
5081 ConsumeBrace();
5082 SkipUntil(tok::r_brace, StopAtSemi);
5085 DS.SetTypeSpecError();
5086 return;
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();
5095 return;
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:
5108 /// enumerator
5109 /// enumerator-list ',' enumerator
5110 /// enumerator:
5111 /// enumeration-constant attributes[opt]
5112 /// enumeration-constant attributes[opt] '=' constant-expression
5113 /// enumeration-constant:
5114 /// identifier
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);
5122 T.consumeOpen();
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))
5141 continue;
5142 break;
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, ", ");
5185 continue;
5188 // Emumerator definition must be finished, only comma or r_brace are
5189 // allowed here.
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
5194 << tok::comma;
5195 else
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))
5199 continue;
5200 } else {
5201 break;
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);
5215 break;
5219 // Eat the }.
5220 T.consumeClose();
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]);
5237 EnumScope.Exit();
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;
5259 // type-specifiers
5260 case tok::kw_short:
5261 case tok::kw_long:
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:
5268 case tok::kw_void:
5269 case tok::kw_char:
5270 case tok::kw_wchar_t:
5271 case tok::kw_char8_t:
5272 case tok::kw_char16_t:
5273 case tok::kw_char32_t:
5274 case tok::kw_int:
5275 case tok::kw__ExtInt:
5276 case tok::kw__BitInt:
5277 case tok::kw___bf16:
5278 case tok::kw_half:
5279 case tok::kw_float:
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:
5286 case tok::kw_bool:
5287 case tok::kw__Bool:
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++)
5296 case tok::kw_class:
5297 case tok::kw_struct:
5298 case tok::kw___interface:
5299 case tok::kw_union:
5300 // enum-specifier
5301 case tok::kw_enum:
5303 // typedef-name
5304 case tok::annot_typename:
5305 return true;
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())
5317 return true;
5318 [[fallthrough]];
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())
5323 return true;
5324 if (Tok.is(tok::identifier))
5325 return false;
5326 return isTypeSpecifierQualifier();
5328 case tok::coloncolon: // ::foo::bar
5329 if (NextToken().is(tok::kw_new) || // ::new
5330 NextToken().is(tok::kw_delete)) // ::delete
5331 return false;
5333 if (TryAnnotateTypeOrScopeToken())
5334 return true;
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:
5343 // type-specifiers
5344 case tok::kw_short:
5345 case tok::kw_long:
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:
5352 case tok::kw_void:
5353 case tok::kw_char:
5354 case tok::kw_wchar_t:
5355 case tok::kw_char8_t:
5356 case tok::kw_char16_t:
5357 case tok::kw_char32_t:
5358 case tok::kw_int:
5359 case tok::kw__ExtInt:
5360 case tok::kw__BitInt:
5361 case tok::kw_half:
5362 case tok::kw___bf16:
5363 case tok::kw_float:
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:
5370 case tok::kw_bool:
5371 case tok::kw__Bool:
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++)
5380 case tok::kw_class:
5381 case tok::kw_struct:
5382 case tok::kw___interface:
5383 case tok::kw_union:
5384 // enum-specifier
5385 case tok::kw_enum:
5387 // type-qualifier
5388 case tok::kw_const:
5389 case tok::kw_volatile:
5390 case tok::kw_restrict:
5391 case tok::kw__Sat:
5393 // Debugger support.
5394 case tok::kw___unknown_anytype:
5396 // typedef-name
5397 case tok::annot_typename:
5398 return true;
5400 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5401 case tok::less:
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:
5410 case tok::kw___w64:
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:
5433 return true;
5435 case tok::kw_private:
5436 return getLangOpts().OpenCL;
5438 // C11 _Atomic
5439 case tok::kw__Atomic:
5440 return true;
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();
5453 if (!R.isUsable())
5454 return nullptr;
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.
5479 case tok::kw_pipe:
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))
5486 return false;
5487 if (TryAltiVecVectorToken())
5488 return true;
5489 [[fallthrough]];
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))
5495 return true;
5496 if (TryAnnotateTypeConstraint())
5497 return true;
5498 if (Tok.is(tok::identifier))
5499 return false;
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())
5508 return false;
5510 return isDeclarationSpecifier(AllowImplicitTypename);
5512 case tok::coloncolon: // ::foo::bar
5513 if (!getLangOpts().CPlusPlus)
5514 return false;
5515 if (NextToken().is(tok::kw_new) || // ::new
5516 NextToken().is(tok::kw_delete)) // ::delete
5517 return false;
5519 // Annotate typenames and C++ scope specifiers. If we get one, just
5520 // recurse to handle whatever we get.
5521 if (TryAnnotateTypeOrScopeToken())
5522 return true;
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:
5530 case tok::kw_auto:
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:
5537 // Modules
5538 case tok::kw___module_private__:
5540 // Debugger support
5541 case tok::kw___unknown_anytype:
5543 // type-specifiers
5544 case tok::kw_short:
5545 case tok::kw_long:
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:
5552 case tok::kw_void:
5553 case tok::kw_char:
5554 case tok::kw_wchar_t:
5555 case tok::kw_char8_t:
5556 case tok::kw_char16_t:
5557 case tok::kw_char32_t:
5559 case tok::kw_int:
5560 case tok::kw__ExtInt:
5561 case tok::kw__BitInt:
5562 case tok::kw_half:
5563 case tok::kw___bf16:
5564 case tok::kw_float:
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:
5571 case tok::kw_bool:
5572 case tok::kw__Bool:
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++)
5579 case tok::kw_class:
5580 case tok::kw_struct:
5581 case tok::kw_union:
5582 case tok::kw___interface:
5583 // enum-specifier
5584 case tok::kw_enum:
5586 // type-qualifier
5587 case tok::kw_const:
5588 case tok::kw_volatile:
5589 case tok::kw_restrict:
5590 case tok::kw__Sat:
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:
5601 // friend keyword.
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:
5612 // GNU attributes.
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:
5623 // C11 _Atomic
5624 case tok::kw__Atomic:
5625 return true;
5627 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5628 case tok::less:
5629 return getLangOpts().ObjC;
5631 // typedef-name
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())
5640 return true;
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())
5651 : nullptr;
5652 if (TemplateId && TemplateId->hasInvalidName())
5653 return true;
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())
5657 return true;
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:
5669 case tok::kw___w64:
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:
5698 return true;
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.
5711 CXXScopeSpec SS;
5712 if (TemplateInfo && TemplateInfo->TemplateParams)
5713 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
5715 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5716 /*ObjectHasErrors=*/false,
5717 /*EnteringContext=*/true)) {
5718 TPA.Revert();
5719 return false;
5722 // Parse the constructor name.
5723 if (Tok.is(tok::identifier)) {
5724 // We already know that we have a constructor name; just consume
5725 // the token.
5726 ConsumeToken();
5727 } else if (Tok.is(tok::annot_template_id)) {
5728 ConsumeAnnotationToken();
5729 } else {
5730 TPA.Revert();
5731 return false;
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)) {
5740 TPA.Revert();
5741 return false;
5743 ConsumeParen();
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))) {
5749 TPA.Revert();
5750 return true;
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)) {
5758 TPA.Revert();
5759 return 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
5785 // looking.
5786 if (Tok.is(tok::annot_cxxscope))
5787 ConsumeAnnotationToken();
5788 ConsumeToken();
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()) {
5794 case tok::l_paren:
5795 // C(X ( int));
5796 case tok::l_square:
5797 // C(X [ 5]);
5798 // C(X [ [attribute]]);
5799 case tok::coloncolon:
5800 // C(X :: Y);
5801 // C(X :: *p);
5802 // Assume this isn't a constructor, rather than assuming it's a
5803 // constructor with an unnamed parameter of an ill-formed type.
5804 break;
5806 case tok::r_paren:
5807 // C(X )
5809 // Skip past the right-paren and any following attributes to get to
5810 // the function body or trailing-return-type.
5811 ConsumeParen();
5812 SkipCXX11Attributes();
5814 if (DeductionGuide) {
5815 // C(X) -> ... is a deduction guide.
5816 IsConstructor = Tok.is(tok::arrow);
5817 break;
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:
5828 // C(X) {
5829 // C(X) ;
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;
5840 break;
5842 default:
5843 IsConstructor = true;
5844 break;
5848 TPA.Revert();
5849 return IsConstructor;
5852 /// ParseTypeQualifierListOpt
5853 /// type-qualifier-list: [C99 6.7.5]
5854 /// type-qualifier
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;
5877 while (true) {
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:
5885 cutOffParsing();
5886 if (CodeCompletionHandler)
5887 (*CodeCompletionHandler)();
5888 else
5889 Actions.CodeCompleteTypeQualifiers(DS);
5890 return;
5892 case tok::kw_const:
5893 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5894 getLangOpts());
5895 break;
5896 case tok::kw_volatile:
5897 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5898 getLangOpts());
5899 break;
5900 case tok::kw_restrict:
5901 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5902 getLangOpts());
5903 break;
5904 case tok::kw__Atomic:
5905 if (!AtomicAllowed)
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,
5910 getLangOpts());
5911 break;
5913 // OpenCL qualifiers:
5914 case tok::kw_private:
5915 if (!getLangOpts().OpenCL)
5916 goto DoneWithTypeQuals;
5917 [[fallthrough]];
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());
5927 break;
5929 case tok::kw_groupshared:
5930 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
5931 ParseHLSLQualifiers(DS.getAttributes());
5932 continue;
5934 case tok::kw___unaligned:
5935 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5936 getLangOpts());
5937 break;
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))
5944 continue;
5946 [[fallthrough]];
5947 case tok::kw___sptr:
5948 case tok::kw___w64:
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());
5959 continue;
5961 goto DoneWithTypeQuals;
5963 case tok::kw___funcref:
5964 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
5965 continue;
5966 goto DoneWithTypeQuals;
5968 case tok::kw___pascal:
5969 if (AttrReqs & AR_VendorAttributesParsed) {
5970 ParseBorlandTypeAttributes(DS.getAttributes());
5971 continue;
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());
5981 continue;
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();
5988 continue;
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!
6003 [[fallthrough]];
6004 default:
6005 DoneWithTypeQuals:
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);
6011 return;
6014 // If the specifier combination wasn't legal, issue a diagnostic.
6015 if (isInvalid) {
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)
6035 return true;
6037 // OpenCL 2.0 and later define this keyword.
6038 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6039 Lang.getOpenCLCompatibleVersion() >= 200)
6040 return true;
6042 if (!Lang.CPlusPlus)
6043 return false;
6045 if (Kind == tok::amp)
6046 return true;
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);
6057 return false;
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)
6066 return true;
6068 return false;
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
6089 /// ptr-operator:
6090 /// '*' cv-qualifier-seq[opt]
6091 /// '&'
6092 /// [C++0x] '&&'
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())
6099 D.setExtension();
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;
6111 CXXScopeSpec SS;
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;
6121 else
6122 AnnotateScopeToken(SS, true);
6124 if (DirectDeclParser)
6125 (this->*DirectDeclParser)(D);
6126 return;
6129 if (SS.isValid()) {
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());
6151 return;
6155 tok::TokenKind Kind = Tok.getKind();
6157 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6158 DeclSpec DS(AttrFactory);
6159 ParseTypeQualifierListOpt(DS);
6161 D.AddTypeInfo(
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);
6170 return;
6173 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6174 // '&&' -> rvalue reference
6175 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6176 D.SetRangeEnd(Loc);
6178 if (Kind == tok::star || Kind == tok::caret) {
6179 // Is a pointer.
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());
6201 else
6202 // Remember that we parsed a Block type, and remember the type-quals.
6203 D.AddTypeInfo(
6204 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
6205 std::move(DS.getAttributes()), SourceLocation());
6206 } else {
6207 // Is a reference
6208 DeclSpec DS(AttrFactory);
6210 // Complain about rvalue references in C++03, but then go on and build
6211 // the declarator.
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)
6247 << II;
6248 else
6249 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6250 << "type name";
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,
6260 Kind == tok::amp),
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;
6275 return Loc;
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]
6307 /// unqualified-id
6308 /// qualified-id
6310 /// unqualified-id: [C++ 5.1]
6311 /// identifier
6312 /// operator-function-id
6313 /// conversion-function-id
6314 /// '~' class-name
6315 /// template-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);
6361 ConsumeToken();
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.
6384 ParseDeclarator(D);
6385 if (EllipsisLoc.isValid())
6386 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6387 return;
6388 } else
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,
6397 tok::tilde)) {
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;
6409 } else {
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);
6427 } else {
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)
6447 << /*C++*/1;
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());
6457 ConsumeToken();
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());
6485 ConsumeToken();
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) ==
6497 TPResult::False) {
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);
6531 } else {
6532 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6533 LLVM_BUILTIN_TRAP;
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());
6549 ConsumeToken();
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());
6556 } else {
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);
6562 else {
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;
6567 else
6568 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6569 diag::err_expected_unqualified_id)
6570 << getLangOpts().CPlusPlus;
6572 } else {
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);
6582 PastIdentifier:
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);
6590 while (true) {
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
6607 // - [...]
6608 // - it is a decl-specifier of the decl-specifier-seq of a
6609 // - [...]
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)
6628 break;
6630 ParsedAttributes attrs(AttrFactory);
6631 BalancedDelimiterTracker T(*this, tok::l_paren);
6632 T.consumeOpen();
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);
6646 // instead of
6647 // void f() requires true;
6648 // or
6649 // void (f()) requires true;
6650 Diag(Tok, diag::err_requires_clause_inside_parens);
6651 ConsumeToken();
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());
6658 } else {
6659 break;
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
6670 // this.
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);
6678 T.consumeOpen();
6680 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6681 while (Tok.isNot(tok::r_square)) {
6682 if (!Bindings.empty()) {
6683 if (Tok.is(tok::comma))
6684 ConsumeToken();
6685 else {
6686 if (Tok.is(tok::identifier)) {
6687 SourceLocation EndLoc = getEndOfPreviousToken();
6688 Diag(EndLoc, diag::err_expected)
6689 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6690 } else {
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))
6697 ConsumeToken();
6698 else if (Tok.isNot(tok::identifier))
6699 break;
6703 if (Tok.isNot(tok::identifier)) {
6704 Diag(Tok, diag::err_expected) << tok::identifier;
6705 break;
6708 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6709 ConsumeToken();
6712 if (Tok.isNot(tok::r_square))
6713 // We've already diagnosed a problem here.
6714 T.skipToEnd();
6715 else {
6716 // C++17 does not allow the identifier-list in a structured binding
6717 // to be empty.
6718 if (Bindings.empty())
6719 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6721 T.consumeClose();
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);
6743 T.consumeOpen();
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.
6764 RequiresArg = true;
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()').
6778 bool isGrouping;
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.
6783 isGrouping = true;
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.
6792 isGrouping = false;
6793 } else {
6794 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6795 isGrouping = true;
6798 // If this is a grouping paren, handle:
6799 // direct-declarator: '(' declarator ')'
6800 // direct-declarator: '(' attributes declarator ')'
6801 if (isGrouping) {
6802 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6803 D.setEllipsisLoc(SourceLocation());
6805 bool hadGroupingParens = D.hasGroupingParens();
6806 D.setGroupingParens(true);
6807 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6808 // Match the ')'.
6809 T.consumeClose();
6810 D.AddTypeInfo(
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);
6820 return;
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
6847 // declarator.
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)
6858 return;
6860 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6861 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6862 Q.addConst();
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);
6873 break;
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
6883 /// arguments.
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,
6904 bool IsAmbiguous,
6905 bool RequiresArg) {
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()) {
6941 if (RequiresArg)
6942 Diag(Tok, diag::err_argument_required_after_attribute);
6944 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6946 Tracker.consumeClose();
6947 RParenLoc = Tracker.getCloseLocation();
6948 LocalEndLoc = RParenLoc;
6949 EndLoc = RParenLoc;
6951 // If there are attributes following the identifier list, parse them and
6952 // prohibit them.
6953 MaybeParseCXX11Attributes(FnAttrs);
6954 ProhibitAttributes(FnAttrs);
6955 } else {
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;
6971 EndLoc = 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);
6984 }));
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(...)))
7012 // or
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.
7018 Delayed = false;
7020 ESpecType = tryParseExceptionSpecification(Delayed,
7021 ESpecRange,
7022 DynamicExceptions,
7023 DynamicExceptionRanges,
7024 NoexceptExpr,
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();
7040 SourceRange Range;
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))
7060 continue;
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,
7085 &DS),
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();
7100 return true;
7102 return false;
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
7115 // 6.7.5.3p11.
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
7124 // invalid type.
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
7128 // identifier list.
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]
7139 /// identifier
7140 /// identifier-list ',' identifier
7142 void Parser::ParseFunctionDeclaratorIdentifierList(
7143 Declarator &D,
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:
7152 // diagnose this.
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;
7159 do {
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.
7165 ParamInfo.clear();
7166 return;
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;
7178 } else {
7179 // Remember this identifier in ParamInfo.
7180 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7181 Tok.getLocation(),
7182 nullptr));
7185 // Eat the identifier.
7186 ConsumeToken();
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]
7203 /// parameter-list
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();
7235 cutOffParsing();
7236 return;
7239 // C++2a [temp.res]p5
7240 // A qualified-id is assumed to name a type if
7241 // - [...]
7242 // - it is a decl-specifier of the decl-specifier-seq of a
7243 // - [...]
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;
7256 do {
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))
7260 break;
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);
7275 } else {
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);
7310 Diag(Tok,
7311 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7312 ConsumeToken();
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
7321 // to be delayed.
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);
7330 } else {
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
7349 // (no identifier)
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.
7366 ConsumeToken();
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
7374 // C.
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,
7388 ArgStartLoc);
7389 } else {
7390 // Consume the '='.
7391 ConsumeToken();
7393 // The argument isn't actually potentially evaluated unless it is
7394 // used.
7395 EnterExpressionEvaluationContext Eval(
7396 Actions,
7397 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
7398 Param);
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();
7404 } else {
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);
7410 continue;
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);
7418 } else {
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()) {
7445 Diag(ParmEllipsis,
7446 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7447 } else {
7448 Diag(ParmDeclarator.getIdentifierLoc(),
7449 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7450 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7451 "...")
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.
7459 break;
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())
7475 return;
7477 BalancedDelimiterTracker T(*this, tok::l_square);
7478 T.consumeOpen();
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) {
7483 T.consumeClose();
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());
7492 return;
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()));
7497 ConsumeToken();
7499 T.consumeClose();
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());
7508 return;
7509 } else if (Tok.getKind() == tok::code_completion) {
7510 cutOffParsing();
7511 Actions.CodeCompleteBracketDeclarator(getCurScope());
7512 return;
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.
7544 isStar = true;
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
7552 // on dialect).
7553 if (getLangOpts().CPlusPlus) {
7554 NumElements = ParseConstantExpression();
7555 } else {
7556 EnterExpressionEvaluationContext Unevaluated(
7557 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7558 NumElements =
7559 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
7561 } else {
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);
7573 return;
7576 T.consumeClose();
7578 MaybeParseCXX11Attributes(DS.getAttributes());
7580 // Remember that we parsed a array type, and remember its features.
7581 D.AddTypeInfo(
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(),
7595 D.getContext());
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
7614 // one here.
7615 if (TempDeclarator.getNumTypeObjects() == 0)
7616 return;
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:
7627 NeedParens = true;
7628 break;
7629 case DeclaratorChunk::Array:
7630 case DeclaratorChunk::Function:
7631 case DeclaratorChunk::Paren:
7632 break;
7636 if (NeedParens) {
7637 // Create a DeclaratorChunk for the inserted parens.
7638 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7639 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7640 SourceLocation());
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)
7652 return;
7654 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7656 // Generate the move bracket error message.
7657 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7658 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7660 if (NeedParens) {
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);
7668 } else {
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:
7686 /// expression
7687 /// type-name
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();
7698 Token OpTok = Tok;
7699 SourceLocation StartLoc = ConsumeToken();
7700 bool HasParens = Tok.is(tok::l_paren);
7702 EnterExpressionEvaluationContext Unevaluated(
7703 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7704 Sema::ReuseLambdaContextDecl);
7706 bool isCastExpr;
7707 ParsedType CastTy;
7708 SourceRange CastRange;
7709 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7710 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7711 if (HasParens)
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());
7717 else
7718 DS.SetRangeEnd(CastRange.getEnd());
7720 if (isCastExpr) {
7721 if (!CastTy) {
7722 DS.SetTypeSpecError();
7723 return;
7726 const char *PrevSpec = nullptr;
7727 unsigned DiagID;
7728 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7729 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualType
7730 : DeclSpec::TST_typeofType,
7731 StartLoc, PrevSpec,
7732 DiagID, CastTy,
7733 Actions.getASTContext().getPrintingPolicy()))
7734 Diag(StartLoc, DiagID) << PrevSpec;
7735 return;
7738 // If we get here, the operand to the typeof was an expression.
7739 if (Operand.isInvalid()) {
7740 DS.SetTypeSpecError();
7741 return;
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();
7748 return;
7751 const char *PrevSpec = nullptr;
7752 unsigned DiagID;
7753 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7754 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualExpr
7755 : DeclSpec::TST_typeofExpr,
7756 StartLoc, PrevSpec,
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())
7772 return;
7774 TypeResult Result = ParseTypeName();
7775 if (Result.isInvalid()) {
7776 SkipUntil(tok::r_paren, StopAtSemi);
7777 return;
7780 // Match the ')'
7781 T.consumeClose();
7783 if (T.getCloseLocation().isInvalid())
7784 return;
7786 DS.setTypeArgumentRange(T.getRange());
7787 DS.SetRangeEnd(T.getCloseLocation());
7789 const char *PrevSpec = nullptr;
7790 unsigned DiagID;
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;
7803 case tok::kw_short:
7804 case tok::kw_long:
7805 case tok::kw_signed:
7806 case tok::kw_unsigned:
7807 case tok::kw_void:
7808 case tok::kw_char:
7809 case tok::kw_int:
7810 case tok::kw_float:
7811 case tok::kw_double:
7812 case tok::kw_bool:
7813 case tok::kw__Bool:
7814 case tok::kw___bool:
7815 case tok::kw___pixel:
7816 Tok.setKind(tok::kw___vector);
7817 return true;
7818 case tok::identifier:
7819 if (Next.getIdentifierInfo() == Ident_pixel) {
7820 Tok.setKind(tok::kw___vector);
7821 return true;
7823 if (Next.getIdentifierInfo() == Ident_bool ||
7824 Next.getIdentifierInfo() == Ident_Bool) {
7825 Tok.setKind(tok::kw___vector);
7826 return true;
7828 return false;
7832 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7833 const char *&PrevSpec, unsigned &DiagID,
7834 bool &isInvalid) {
7835 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7836 if (Tok.getIdentifierInfo() == Ident_vector) {
7837 Token Next = NextToken();
7838 switch (Next.getKind()) {
7839 case tok::kw_short:
7840 case tok::kw_long:
7841 case tok::kw_signed:
7842 case tok::kw_unsigned:
7843 case tok::kw_void:
7844 case tok::kw_char:
7845 case tok::kw_int:
7846 case tok::kw_float:
7847 case tok::kw_double:
7848 case tok::kw_bool:
7849 case tok::kw__Bool:
7850 case tok::kw___bool:
7851 case tok::kw___pixel:
7852 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7853 return true;
7854 case tok::identifier:
7855 if (Next.getIdentifierInfo() == Ident_pixel) {
7856 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7857 return true;
7859 if (Next.getIdentifierInfo() == Ident_bool ||
7860 Next.getIdentifierInfo() == Ident_Bool) {
7861 isInvalid =
7862 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7863 return true;
7865 break;
7866 default:
7867 break;
7869 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7870 DS.isTypeAltiVecVector()) {
7871 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7872 return true;
7873 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7874 DS.isTypeAltiVecVector()) {
7875 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7876 return true;
7878 return false;
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
7884 // extension.
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");
7892 } else {
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();
7897 else
7898 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;